diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/.github/dependabot.yml b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..dfa7fa6cba823110c8476a4b4ebcc07cfda12535 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/.github/dependabot.yml @@ -0,0 +1,13 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" + open-pull-requests-limit: 10 + + - package-ecosystem: "npm" + directory: "/" + schedule: + interval: "weekly" + open-pull-requests-limit: 10 diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/.github/release-drafter.yml b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/.github/release-drafter.yml new file mode 100644 index 0000000000000000000000000000000000000000..eba1c60853052e361195b57c1efa7f48d6b963f5 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/.github/release-drafter.yml @@ -0,0 +1,4 @@ +template: | + ## What’s Changed + + $CHANGES diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/.github/tests_checker.yml b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/.github/tests_checker.yml new file mode 100644 index 0000000000000000000000000000000000000000..3092680ef3f3825e5056418aaa471fb2753a8c99 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/.github/tests_checker.yml @@ -0,0 +1,3 @@ +comment: 'Could you please add tests to make sure this change works as expected?', +fileExtensions: ['.php', '.ts', '.js', '.c', '.cs', '.cpp', '.rb', '.java'] +testDir: 'test' diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/.github/workflows/ci.yml b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..7eb421708eeea7475cb9f737e96ff47df76d9057 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/.github/workflows/ci.yml @@ -0,0 +1,24 @@ +name: CI + +on: + push: + branches: + - main + - master + - next + - 'v*' + paths-ignore: + - 'docs/**' + - '*.md' + pull_request: + paths-ignore: + - 'docs/**' + - '*.md' + +jobs: + test: + uses: fastify/workflows/.github/workflows/plugins-ci.yml@v5.0.0 + with: + lint: true + license-check: true + node-versions: '["20", "22"]' diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/examples/example.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/examples/example.js new file mode 100644 index 0000000000000000000000000000000000000000..cbba32b5935c2a05ae0898de7ffc3130314f8337 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/examples/example.js @@ -0,0 +1,72 @@ +'use strict' + +const avvio = require('..')() + +function a (instance, opts, cb) { + (opts.use || []).forEach(_ => { instance.use(_, { use: opts.subUse || [] }) }) + setTimeout(cb, 10) +} +const pointer = a + +function b (instance, opts, cb) { + (opts.use || []).forEach(_ => { instance.use(_, { use: opts.subUse || [] }) }) + setTimeout(cb, 20) +} + +function c (instance, opts, cb) { + (opts.use || []).forEach(_ => { instance.use(_, { use: opts.subUse || [] }) }) + setTimeout(cb, 30) +} + +avvio + .use(first, { hello: 'world' }) + .use(duplicate, { count: 0 }) + .use(function a (instance, opts, cb) { + instance.use(pointer, { use: [b], subUse: [c] }) + .use(b) + setTimeout(cb, 42) + }) + .after(function (err, cb) { + if (err) { + console.log('something bad happened') + console.log(err) + } + console.log('after first and second') + cb() + }) + .use(duplicate, { count: 4 }) + .use(third) + .ready(function (err) { + if (err) { + throw err + } + console.log('application booted!') + }) + +avvio.on('preReady', () => { + console.log(avvio.prettyPrint()) +}) + +function first (instance, opts, cb) { + console.log('first loaded', opts) + instance.use(second) + setTimeout(cb, 42) +} + +function second (instance, opts, cb) { + console.log('second loaded') + process.nextTick(cb) +} + +function third (instance, opts, cb) { + console.log('third loaded') + cb() +} + +function duplicate (instance, opts, cb) { + console.log('duplicate loaded', opts.count) + if (opts.count > 0) { + instance.use(duplicate, { count: opts.count - 1 }) + } + setTimeout(cb, 20) +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/lib/create-promise.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/lib/create-promise.js new file mode 100644 index 0000000000000000000000000000000000000000..4b10c0b0657a12c70d8f3e61fa266b7cae2e9ac3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/lib/create-promise.js @@ -0,0 +1,45 @@ +'use strict' + +/** + * @callback PromiseResolve + * @param {any|PromiseLike} value + * @returns {void} + */ + +/** + * @callback PromiseReject + * @param {any} reason + * @returns {void} + */ + +/** + * @typedef PromiseObject + * @property {Promise} promise + * @property {PromiseResolve} resolve + * @property {PromiseReject} reject + */ + +/** + * @returns {PromiseObject} + */ +function createPromise () { + /** + * @type {PromiseObject} + */ + const obj = { + resolve: null, + reject: null, + promise: null + } + + obj.promise = new Promise((resolve, reject) => { + obj.resolve = resolve + obj.reject = reject + }) + + return obj +} + +module.exports = { + createPromise +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/lib/debug.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/lib/debug.js new file mode 100644 index 0000000000000000000000000000000000000000..e7cdc6fc4ad6ca7df49ceef4ac6dc738ef9705f9 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/lib/debug.js @@ -0,0 +1,19 @@ +'use strict' + +const { debuglog } = require('node:util') + +/** + * @callback DebugLogger + * @param {string} msg + * @param {...unknown} param + * @returns {void} + */ + +/** + * @type {DebugLogger} + */ +const debug = debuglog('avvio') + +module.exports = { + debug +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/lib/errors.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/lib/errors.js new file mode 100644 index 0000000000000000000000000000000000000000..9aa4c8a1070f0c0219a942c0fe0b91a6391ec54b --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/lib/errors.js @@ -0,0 +1,38 @@ +'use strict' + +const { createError } = require('@fastify/error') + +module.exports = { + AVV_ERR_EXPOSE_ALREADY_DEFINED: createError( + 'AVV_ERR_EXPOSE_ALREADY_DEFINED', + "'%s' is already defined, specify an expose option for '%s'" + ), + AVV_ERR_ATTRIBUTE_ALREADY_DEFINED: createError( + 'AVV_ERR_ATTRIBUTE_ALREADY_DEFINED', + "'%s' is already defined" + ), + AVV_ERR_CALLBACK_NOT_FN: createError( + 'AVV_ERR_CALLBACK_NOT_FN', + "Callback for '%s' hook is not a function. Received: '%s'" + ), + AVV_ERR_PLUGIN_NOT_VALID: createError( + 'AVV_ERR_PLUGIN_NOT_VALID', + "Plugin must be a function or a promise. Received: '%s'" + ), + AVV_ERR_ROOT_PLG_BOOTED: createError( + 'AVV_ERR_ROOT_PLG_BOOTED', + 'Root plugin has already booted' + ), + AVV_ERR_PARENT_PLG_LOADED: createError( + 'AVV_ERR_PARENT_PLG_LOADED', + "Impossible to load '%s' plugin because the parent '%s' was already loaded" + ), + AVV_ERR_READY_TIMEOUT: createError( + 'AVV_ERR_READY_TIMEOUT', + "Plugin did not start in time: '%s'. You may have forgotten to call 'done' function or to resolve a Promise" + ), + AVV_ERR_PLUGIN_EXEC_TIMEOUT: createError( + 'AVV_ERR_PLUGIN_EXEC_TIMEOUT', + "Plugin did not start in time: '%s'. You may have forgotten to call 'done' function or to resolve a Promise" + ) +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/lib/execute-with-thenable.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/lib/execute-with-thenable.js new file mode 100644 index 0000000000000000000000000000000000000000..6e2c80956070c57f7b2d2626737e9b3939140f21 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/lib/execute-with-thenable.js @@ -0,0 +1,28 @@ +'use strict' +const { isPromiseLike } = require('./is-promise-like') +const { kAvvio } = require('./symbols') + +/** + * @callback ExecuteWithThenableCallback + * @param {Error} error + * @returns {void} + */ + +/** + * @param {Function} func + * @param {Array} args + * @param {ExecuteWithThenableCallback} [callback] + */ +function executeWithThenable (func, args, callback) { + const result = func.apply(func, args) + if (isPromiseLike(result) && !result[kAvvio]) { + // process promise but not avvio mock thenable + result.then(() => process.nextTick(callback), (error) => process.nextTick(callback, error)) + } else if (callback) { + process.nextTick(callback) + } +} + +module.exports = { + executeWithThenable +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/lib/get-plugin-name.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/lib/get-plugin-name.js new file mode 100644 index 0000000000000000000000000000000000000000..79bf79a1f6e7b243bb7e75a84ba25523a5a0d539 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/lib/get-plugin-name.js @@ -0,0 +1,34 @@ +'use strict' + +// this symbol is assigned by fastify-plugin +const { kPluginMeta } = require('./symbols') + +/** + * @param {function} plugin + * @param {object} [options] + * @param {string} [options.name] + * @returns {string} + */ +function getPluginName (plugin, options) { + // use explicit function metadata if set + if (plugin[kPluginMeta] && plugin[kPluginMeta].name) { + return plugin[kPluginMeta].name + } + + // use explicit name option if set + if (options && options.name) { + return options.name + } + + // determine from the function + if (plugin.name) { + return plugin.name + } else { + // takes the first two lines of the function if nothing else works + return plugin.toString().split('\n').slice(0, 2).map(s => s.trim()).join(' -- ') + } +} + +module.exports = { + getPluginName +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/lib/is-bundled-or-typescript-plugin.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/lib/is-bundled-or-typescript-plugin.js new file mode 100644 index 0000000000000000000000000000000000000000..42003dd9311e2894cdb578eccf7d4a56fc6aee83 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/lib/is-bundled-or-typescript-plugin.js @@ -0,0 +1,23 @@ +'use strict' + +/** + * bundled or typescript plugin + * @typedef {object} BundledOrTypescriptPlugin + * @property {function} default + */ + +/** + * @param {any} maybeBundledOrTypescriptPlugin + * @returns {plugin is BundledOrTypescriptPlugin} + */ +function isBundledOrTypescriptPlugin (maybeBundledOrTypescriptPlugin) { + return ( + maybeBundledOrTypescriptPlugin !== null && + typeof maybeBundledOrTypescriptPlugin === 'object' && + typeof maybeBundledOrTypescriptPlugin.default === 'function' + ) +} + +module.exports = { + isBundledOrTypescriptPlugin +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/lib/is-promise-like.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/lib/is-promise-like.js new file mode 100644 index 0000000000000000000000000000000000000000..909f8dbd1bec6a222c223cd8ffe6456f41832d76 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/lib/is-promise-like.js @@ -0,0 +1,17 @@ +'use strict' + +/** + * @param {any} maybePromiseLike + * @returns {maybePromiseLike is PromiseLike} + */ +function isPromiseLike (maybePromiseLike) { + return ( + maybePromiseLike !== null && + typeof maybePromiseLike === 'object' && + typeof maybePromiseLike.then === 'function' + ) +} + +module.exports = { + isPromiseLike +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/lib/plugin.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/lib/plugin.js new file mode 100644 index 0000000000000000000000000000000000000000..a3f248d5887e88d6d9d91cdf530fa421f6b1bf1d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/lib/plugin.js @@ -0,0 +1,279 @@ +'use strict' + +const { EventEmitter } = require('node:events') +const { inherits } = require('node:util') +const { debug } = require('./debug') +const { createPromise } = require('./create-promise') +const { AVV_ERR_PLUGIN_EXEC_TIMEOUT } = require('./errors') +const { getPluginName } = require('./get-plugin-name') +const { isPromiseLike } = require('./is-promise-like') + +/** + * @param {*} queue + * @param {*} func + * @param {*} options + * @param {boolean} isAfter + * @param {number} [timeout] + */ +function Plugin (queue, func, options, isAfter, timeout) { + this.queue = queue + this.func = func + this.options = options + + /** + * @type {boolean} + */ + this.isAfter = isAfter + /** + * @type {number} + */ + this.timeout = timeout + + /** + * @type {boolean} + */ + this.started = false + /** + * @type {string} + */ + this.name = getPluginName(func, options) + + this.queue.pause() + + /** + * @type {Error|null} + */ + this._error = null + /** + * @type {boolean} + */ + this.loaded = false + + this._promise = null + + this.startTime = null +} + +inherits(Plugin, EventEmitter) + +/** + * @callback ExecCallback + * @param {Error|null} execErr + * @returns + */ + +/** + * + * @param {*} server + * @param {ExecCallback} callback + * @returns + */ +Plugin.prototype.exec = function (server, callback) { + debug('exec', this.name) + + this.server = server + const func = this.func + const name = this.name + let completed = false + + this.options = typeof this.options === 'function' ? this.options(this.server) : this.options + + let timer = null + + /** + * @param {Error} [execErr] + */ + const done = (execErr) => { + if (completed) { + debug('loading complete', name) + return + } + + this._error = execErr + + if (execErr) { + debug('exec errored', name) + } else { + debug('exec completed', name) + } + + completed = true + + if (timer) { + clearTimeout(timer) + } + + callback(execErr) + } + + if (this.timeout > 0) { + debug('setting up timeout', name, this.timeout) + timer = setTimeout(function () { + debug('timed out', name) + timer = null + const readyTimeoutErr = new AVV_ERR_PLUGIN_EXEC_TIMEOUT(name) + // TODO Remove reference to function + readyTimeoutErr.fn = func + done(readyTimeoutErr) + }, this.timeout) + } + + this.started = true + this.startTime = Date.now() + this.emit('start', this.server ? this.server.name : null, this.name, Date.now()) + + const maybePromiseLike = func(this.server, this.options, done) + + if (isPromiseLike(maybePromiseLike)) { + debug('exec: resolving promise', name) + + maybePromiseLike.then( + () => process.nextTick(done), + (e) => process.nextTick(done, e)) + } else if (func.length < 3) { + done() + } +} + +/** + * @returns {Promise} + */ +Plugin.prototype.loadedSoFar = function () { + debug('loadedSoFar', this.name) + + if (this.loaded) { + return Promise.resolve() + } + + const setup = () => { + this.server.after((afterErr, callback) => { + this._error = afterErr + this.queue.pause() + + if (this._promise) { + if (afterErr) { + debug('rejecting promise', this.name, afterErr) + this._promise.reject(afterErr) + } else { + debug('resolving promise', this.name) + this._promise.resolve() + } + this._promise = null + } + + process.nextTick(callback, afterErr) + }) + this.queue.resume() + } + + let res + + if (!this._promise) { + this._promise = createPromise() + res = this._promise.promise + + if (!this.server) { + this.on('start', setup) + } else { + setup() + } + } else { + res = Promise.resolve() + } + + return res +} + +/** + * @callback EnqueueCallback + * @param {Error|null} enqueueErr + * @param {Plugin} result + */ + +/** + * + * @param {Plugin} plugin + * @param {EnqueueCallback} callback + */ +Plugin.prototype.enqueue = function (plugin, callback) { + debug('enqueue', this.name, plugin.name) + + this.emit('enqueue', this.server ? this.server.name : null, this.name, Date.now()) + this.queue.push(plugin, callback) +} + +/** + * @callback FinishCallback + * @param {Error|null} finishErr + * @returns + */ +/** + * + * @param {Error|null} err + * @param {FinishCallback} callback + * @returns + */ +Plugin.prototype.finish = function (err, callback) { + debug('finish', this.name, err) + + const done = () => { + if (this.loaded) { + return + } + + debug('loaded', this.name) + this.emit('loaded', this.server ? this.server.name : null, this.name, Date.now()) + this.loaded = true + + callback(err) + } + + if (err) { + if (this._promise) { + this._promise.reject(err) + this._promise = null + } + done() + return + } + + const check = () => { + debug('check', this.name, this.queue.length(), this.queue.running(), this._promise) + if (this.queue.length() === 0 && this.queue.running() === 0) { + if (this._promise) { + const wrap = () => { + debug('wrap') + queueMicrotask(check) + } + this._promise.resolve() + this._promise.promise.then(wrap, wrap) + this._promise = null + } else { + done() + } + } else { + debug('delayed', this.name) + // finish when the queue of nested plugins to load is empty + this.queue.drain = () => { + debug('drain', this.name) + this.queue.drain = noop + + // we defer the check, as a safety net for things + // that might be scheduled in the loading callback + queueMicrotask(check) + } + } + } + + queueMicrotask(check) + + // we start loading the dependents plugins only once + // the current level is finished + this.queue.resume() +} + +function noop () {} + +module.exports = { + Plugin +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/lib/symbols.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/lib/symbols.js new file mode 100644 index 0000000000000000000000000000000000000000..62cdf38e3d864597fe29574bfa2756b1af1c9fae --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/lib/symbols.js @@ -0,0 +1,26 @@ +'use strict' + +// Internal Symbols +const kAvvio = Symbol('avvio.Boot') +const kIsOnCloseHandler = Symbol('isOnCloseHandler') +const kThenifyDoNotWrap = Symbol('avvio.ThenifyDoNotWrap') +const kUntrackNode = Symbol('avvio.TimeTree.untrackNode') +const kTrackNode = Symbol('avvio.TimeTree.trackNode') +const kGetParent = Symbol('avvio.TimeTree.getParent') +const kGetNode = Symbol('avvio.TimeTree.getNode') +const kAddNode = Symbol('avvio.TimeTree.addNode') + +// Public Symbols +const kPluginMeta = Symbol.for('plugin-meta') + +module.exports = { + kAvvio, + kIsOnCloseHandler, + kThenifyDoNotWrap, + kUntrackNode, + kTrackNode, + kGetParent, + kGetNode, + kAddNode, + kPluginMeta +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/lib/thenify.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/lib/thenify.js new file mode 100644 index 0000000000000000000000000000000000000000..e1b614d3f8b842a3e4d37e3d5211d144c3aad57f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/lib/thenify.js @@ -0,0 +1,60 @@ +'use strict' + +const { debug } = require('./debug') +const { kThenifyDoNotWrap } = require('./symbols') + +/** + * @callback PromiseConstructorLikeResolve + * @param {any} value + * @returns {void} + */ + +/** + * @callback PromiseConstructorLikeReject + * @param {reason} error + * @returns {void} + */ + +/** + * @callback PromiseConstructorLike + * @param {PromiseConstructorLikeResolve} resolve + * @param {PromiseConstructorLikeReject} reject + * @returns {void} + */ + +/** + * @returns {PromiseConstructorLike} + */ +function thenify () { + // If the instance is ready, then there is + // nothing to await. This is true during + // await server.ready() as ready() resolves + // with the server, end we will end up here + // because of automatic promise chaining. + if (this.booted) { + debug('thenify returning undefined because we are already booted') + return + } + + // Calling resolve(this._server) would fetch the then + // property on the server, which will lead it here. + // If we do not break the recursion, we will loop + // forever. + if (this[kThenifyDoNotWrap]) { + this[kThenifyDoNotWrap] = false + return + } + + debug('thenify') + return (resolve, reject) => { + const p = this._loadRegistered() + return p.then(() => { + this[kThenifyDoNotWrap] = true + return resolve(this._server) + }, reject) + } +} + +module.exports = { + thenify +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/lib/time-tree.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/lib/time-tree.js new file mode 100644 index 0000000000000000000000000000000000000000..5f02d68d44c9dfe5dabf735d8f8e316eb2b4ba54 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/lib/time-tree.js @@ -0,0 +1,200 @@ +'use strict' + +const { + kUntrackNode, + kTrackNode, + kGetParent, + kGetNode, + kAddNode +} = require('./symbols') + +/** + * Node of the TimeTree + * @typedef {object} TimeTreeNode + * @property {string} id + * @property {string|null} parent + * @property {string} label + * @property {Array} nodes + * @property {number} start + * @property {number|undefined} stop + * @property {number|undefined} diff + */ + +class TimeTree { + constructor () { + /** + * @type {TimeTreeNode|null} root + * @public + */ + this.root = null + + /** + * @type {Map} tableId + * @public + */ + this.tableId = new Map() + + /** + * @type {Map>} tableLabel + * @public + */ + this.tableLabel = new Map() + } + + /** + * @param {TimeTreeNode} node + */ + [kTrackNode] (node) { + this.tableId.set(node.id, node) + if (this.tableLabel.has(node.label)) { + this.tableLabel.get(node.label).push(node) + } else { + this.tableLabel.set(node.label, [node]) + } + } + + /** + * @param {TimeTreeNode} node + */ + [kUntrackNode] (node) { + this.tableId.delete(node.id) + + const labelNode = this.tableLabel.get(node.label) + labelNode.pop() + + if (labelNode.length === 0) { + this.tableLabel.delete(node.label) + } + } + + /** + * @param {string} parent + * @returns {TimeTreeNode} + */ + [kGetParent] (parent) { + if (parent === null) { + return null + } else if (this.tableLabel.has(parent)) { + const parentNode = this.tableLabel.get(parent) + return parentNode[parentNode.length - 1] + } else { + return null + } + } + + /** + * + * @param {string} nodeId + * @returns {TimeTreeNode} + */ + [kGetNode] (nodeId) { + return this.tableId.get(nodeId) + } + + /** + * @param {string} parent + * @param {string} label + * @param {number} start + * @returns {TimeTreeNode["id"]} + */ + [kAddNode] (parent, label, start) { + const parentNode = this[kGetParent](parent) + const isRoot = parentNode === null + + if (isRoot) { + this.root = { + parent: null, + id: 'root', + label, + nodes: [], + start, + stop: null, + diff: -1 + } + this[kTrackNode](this.root) + return this.root.id + } + + const nodeId = `${label}-${Math.random()}` + /** + * @type {TimeTreeNode} + */ + const childNode = { + parent, + id: nodeId, + label, + nodes: [], + start, + stop: null, + diff: -1 + } + parentNode.nodes.push(childNode) + this[kTrackNode](childNode) + return nodeId + } + + /** + * @param {string} parent + * @param {string} label + * @param {number|undefined} start + * @returns {TimeTreeNode["id"]} + */ + start (parent, label, start = Date.now()) { + return this[kAddNode](parent, label, start) + } + + /** + * @param {string} nodeId + * @param {number|undefined} stop + */ + stop (nodeId, stop = Date.now()) { + const node = this[kGetNode](nodeId) + if (node) { + node.stop = stop + node.diff = (node.stop - node.start) || 0 + this[kUntrackNode](node) + } + } + + /** + * @returns {TimeTreeNode} + */ + toJSON () { + return Object.assign({}, this.root) + } + + /** + * @returns {string} + */ + prettyPrint () { + return prettyPrintTimeTree(this.toJSON()) + } +} + +/** + * @param {TimeTreeNode} obj + * @param {string|undefined} prefix + * @returns {string} + */ +function prettyPrintTimeTree (obj, prefix = '') { + let result = prefix + + const nodesCount = obj.nodes.length + const lastIndex = nodesCount - 1 + result += `${obj.label} ${obj.diff} ms\n` + + for (let i = 0; i < nodesCount; ++i) { + const node = obj.nodes[i] + const prefix_ = prefix + (i === lastIndex ? ' ' : '│ ') + + result += prefix + result += (i === lastIndex ? '└─' : '├─') + result += (node.nodes.length === 0 ? '─ ' : '┬ ') + result += prettyPrintTimeTree(node, prefix_).slice(prefix.length + 2) + } + return result +} + +module.exports = { + TimeTree +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/lib/validate-plugin.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/lib/validate-plugin.js new file mode 100644 index 0000000000000000000000000000000000000000..374ee5616aff1d8a7ed3a68f5e92783964cce0de --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/lib/validate-plugin.js @@ -0,0 +1,26 @@ +'use strict' + +const { AVV_ERR_PLUGIN_NOT_VALID } = require('./errors') + +/** + * @param {any} maybePlugin + * @throws {AVV_ERR_PLUGIN_NOT_VALID} + * + * @returns {asserts plugin is Function|PromiseLike} + */ +function validatePlugin (maybePlugin) { + // validate if plugin is a function or Promise + if (!(maybePlugin && (typeof maybePlugin === 'function' || typeof maybePlugin.then === 'function'))) { + if (Array.isArray(maybePlugin)) { + throw new AVV_ERR_PLUGIN_NOT_VALID('array') + } else if (maybePlugin === null) { + throw new AVV_ERR_PLUGIN_NOT_VALID('null') + } else { + throw new AVV_ERR_PLUGIN_NOT_VALID(typeof maybePlugin) + } + } +} + +module.exports = { + validatePlugin +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/after-and-ready.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/after-and-ready.test.js new file mode 100644 index 0000000000000000000000000000000000000000..ff3d7306b36a923b7b56d13aea6caf1d00e93025 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/after-and-ready.test.js @@ -0,0 +1,864 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') + +test('boot a plugin and then execute a call after that', (t) => { + t.plan(5) + + const app = boot() + let pluginLoaded = false + let afterCalled = false + + app.use(function (s, opts, done) { + t.notOk(afterCalled, 'after not called') + pluginLoaded = true + done() + }) + + app.after(function (err, cb) { + t.error(err) + t.ok(pluginLoaded, 'afterred!') + afterCalled = true + cb() + }) + + app.on('start', () => { + t.ok(afterCalled, 'after called') + t.ok(pluginLoaded, 'plugin loaded') + }) +}) + +test('after without a done callback', (t) => { + t.plan(5) + + const app = boot() + let pluginLoaded = false + let afterCalled = false + + app.use(function (s, opts, done) { + t.notOk(afterCalled, 'after not called') + pluginLoaded = true + done() + }) + + app.after(function (err) { + t.error(err) + t.ok(pluginLoaded, 'afterred!') + afterCalled = true + }) + + app.on('start', () => { + t.ok(afterCalled, 'after called') + t.ok(pluginLoaded, 'plugin loaded') + }) +}) + +test('verify when a afterred call happens', (t) => { + t.plan(3) + + const app = boot() + + app.use(function (s, opts, done) { + done() + }) + + app.after(function (err, cb) { + t.error(err) + t.pass('afterred finished') + cb() + }) + + app.on('start', () => { + t.pass('booted') + }) +}) + +test('internal after', (t) => { + t.plan(18) + + const app = boot() + let firstLoaded = false + let secondLoaded = false + let thirdLoaded = false + let afterCalled = false + + app.use(first) + app.use(third) + + function first (s, opts, done) { + t.notOk(firstLoaded, 'first is not loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + firstLoaded = true + s.use(second) + s.after(function (err, cb) { + t.error(err) + t.notOk(afterCalled, 'after was not called') + afterCalled = true + cb() + }) + done() + } + + function second (s, opts, done) { + t.ok(firstLoaded, 'first is loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + t.notOk(afterCalled, 'after was not called') + secondLoaded = true + done() + } + + function third (s, opts, done) { + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(afterCalled, 'after was called') + t.notOk(thirdLoaded, 'third is not loaded') + thirdLoaded = true + done() + } + + app.on('start', () => { + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.ok(afterCalled, 'after was called') + t.pass('booted') + }) +}) + +test('ready adds at the end of the queue', (t) => { + t.plan(14) + + const app = boot() + let pluginLoaded = false + let afterCalled = false + let readyCalled = false + + app.ready(function (err, cb) { + t.error(err) + t.ok(pluginLoaded, 'after the plugin') + t.ok(afterCalled, 'after after') + readyCalled = true + process.nextTick(cb) + }) + + app.use(function (s, opts, done) { + t.notOk(afterCalled, 'after not called') + t.notOk(readyCalled, 'ready not called') + pluginLoaded = true + + app.ready(function (err) { + t.error(err) + t.ok(readyCalled, 'after the first ready') + t.ok(afterCalled, 'after the after callback') + }) + + done() + }) + + app.after(function (err, cb) { + t.error(err) + t.ok(pluginLoaded, 'executing after!') + t.notOk(readyCalled, 'ready not called') + afterCalled = true + cb() + }) + + app.on('start', () => { + t.ok(afterCalled, 'after called') + t.ok(pluginLoaded, 'plugin loaded') + t.ok(readyCalled, 'ready called') + }) +}) + +test('if the after/ready callback has two parameters, the first one must be the context', (t) => { + t.plan(4) + + const server = { my: 'server' } + const app = boot(server) + + app.use(function (s, opts, done) { + done() + }) + + app.after(function (err, context, cb) { + t.error(err) + t.equal(server, context) + cb() + }) + + app.ready(function (err, context, cb) { + t.error(err) + t.equal(server, context) + cb() + }) +}) + +test('if the after/ready async, the returns must be the context generated', (t) => { + t.plan(3) + + const server = { my: 'server', index: 0 } + const app = boot(server) + app.override = function (old) { + return { ...old, index: old.index + 1 } + } + + app.use(function (s, opts, done) { + s.use(function (s, opts, done) { + s.ready().then(itself => t.same(itself, s, 'deep deep')) + done() + }) + s.ready().then(itself => t.same(itself, s, 'deep')) + done() + }) + + app.ready().then(itself => t.same(itself, server, 'outer')) +}) + +test('if the after/ready callback, the returns must be the context generated', (t) => { + t.plan(3) + + const server = { my: 'server', index: 0 } + const app = boot(server) + app.override = function (old) { + return { ...old, index: old.index + 1 } + } + + app.use(function (s, opts, done) { + s.use(function (s, opts, done) { + s.ready((_, itself, done) => { + t.same(itself, s, 'deep deep') + done() + }) + done() + }) + s.ready((_, itself, done) => { + t.same(itself, s, 'deep') + done() + }) + done() + }) + + app.ready((_, itself, done) => { + t.same(itself, server, 'outer') + done() + }) +}) + +test('error should come in the first after - one parameter', (t) => { + t.plan(3) + + const server = { my: 'server' } + const app = boot(server) + + app.use(function (s, opts, done) { + done(new Error('err')) + }) + + app.after(function (err) { + t.ok(err instanceof Error) + t.equal(err.message, 'err') + }) + + app.ready(function (err) { + t.error(err) + }) +}) + +test('error should come in the first after - two parameters', (t) => { + t.plan(3) + + const server = { my: 'server' } + const app = boot(server) + + app.use(function (s, opts, done) { + done(new Error('err')) + }) + + app.after(function (err, cb) { + t.ok(err instanceof Error) + t.equal(err.message, 'err') + cb() + }) + + app.ready(function (err) { + t.error(err) + }) +}) + +test('error should come in the first after - three parameter', (t) => { + t.plan(4) + + const server = { my: 'server' } + const app = boot(server) + + app.use(function (s, opts, done) { + done(new Error('err')) + }) + + app.after(function (err, context, cb) { + t.ok(err instanceof Error) + t.equal(err.message, 'err') + t.equal(context, server) + cb() + }) + + app.ready(function (err) { + t.error(err) + }) +}) + +test('error should come in the first ready - one parameter', (t) => { + t.plan(2) + + const server = { my: 'server' } + const app = boot(server) + + app.use(function (s, opts, done) { + done(new Error('err')) + }) + + app.ready(function (err) { + t.ok(err instanceof Error) + t.equal(err.message, 'err') + }) +}) + +test('error should come in the first ready - two parameters', (t) => { + t.plan(2) + + const server = { my: 'server' } + const app = boot(server) + + app.use(function (s, opts, done) { + done(new Error('err')) + }) + + app.ready(function (err, cb) { + t.ok(err instanceof Error) + t.equal(err.message, 'err') + cb() + }) +}) + +test('error should come in the first ready - three parameters', (t) => { + t.plan(3) + + const server = { my: 'server' } + const app = boot(server) + + app.use(function (s, opts, done) { + done(new Error('err')) + }) + + app.ready(function (err, context, cb) { + t.ok(err instanceof Error) + t.equal(err.message, 'err') + t.equal(context, server) + cb() + }) +}) + +test('if `use` has a callback with more then one parameter, the error must not reach ready', (t) => { + t.plan(1) + + const server = { my: 'server' } + const app = boot(server) + + app.use(function (s, opts, done) { + done(new Error('err')) + }) + + app.ready(function (err) { + t.ok(err) + }) +}) + +test('if `use` has a callback without parameters, the error must reach ready', (t) => { + t.plan(1) + + const server = { my: 'server' } + const app = boot(server) + + app.use(function (s, opts, done) { + done(new Error('err')) + }, () => {}) + + app.ready(function (err) { + t.ok(err) + }) +}) + +test('should pass the errors from after to ready', (t) => { + t.plan(6) + + const server = {} + const app = boot(server, {}) + + server.use(function (s, opts, done) { + t.equal(s, server, 'the first argument is the server') + t.same(opts, {}, 'no options') + done() + }).after((err, done) => { + t.error(err) + done(new Error('some error')) + }) + + server.onClose(() => { + t.ok('onClose called') + }) + + server.ready(err => { + t.equal(err.message, 'some error') + }) + + app.on('start', () => { + server.close(() => { + t.pass('booted') + }) + }) +}) + +test('after no encapsulation', t => { + t.plan(4) + + const app = boot() + app.override = function (s, fn, opts) { + s = Object.create(s) + return s + } + + app.use(function (instance, opts, next) { + instance.test = true + instance.after(function (err, i, done) { + t.error(err) + t.notOk(i.test) + done() + }) + next() + }) + + app.after(function (err, i, done) { + t.error(err) + t.notOk(i.test) + done() + }) +}) + +test('ready no encapsulation', t => { + t.plan(4) + + const app = boot() + app.override = function (s, fn, opts) { + s = Object.create(s) + return s + } + + app.use(function (instance, opts, next) { + instance.test = true + instance.ready(function (err, i, done) { + t.error(err) + t.notOk(i.test) + done() + }) + next() + }) + + app.ready(function (err, i, done) { + t.error(err) + t.notOk(i.test) + done() + }) +}) + +test('after encapsulation with a server', t => { + t.plan(4) + + const server = { my: 'server' } + const app = boot(server) + app.override = function (s, fn, opts) { + s = Object.create(s) + return s + } + + app.use(function (instance, opts, next) { + instance.test = true + instance.after(function (err, i, done) { + t.error(err) + t.ok(i.test) + done() + }) + next() + }) + + app.after(function (err, i, done) { + t.error(err) + t.notOk(i.test) + done() + }) +}) + +test('ready encapsulation with a server', t => { + t.plan(4) + + const server = { my: 'server' } + const app = boot(server) + app.override = function (s, fn, opts) { + s = Object.create(s) + return s + } + + app.use(function (instance, opts, next) { + instance.test = true + instance.ready(function (err, i, done) { + t.error(err) + t.ok(i.test) + done() + }) + next() + }) + + app.ready(function (err, i, done) { + t.error(err) + t.notOk(i.test) + done() + }) +}) + +test('after should passthrough the errors', (t) => { + t.plan(5) + + const app = boot() + let pluginLoaded = false + let afterCalled = false + + app.use(function (s, opts, done) { + t.notOk(afterCalled, 'after not called') + pluginLoaded = true + done(new Error('kaboom')) + }) + + app.after(function () { + t.ok(pluginLoaded, 'afterred!') + afterCalled = true + }) + + app.ready(function (err) { + t.ok(err) + t.ok(afterCalled, 'after called') + t.ok(pluginLoaded, 'plugin loaded') + }) +}) + +test('stop loading plugins if it errors', (t) => { + t.plan(2) + + const app = boot() + + app.use(function first (server, opts, done) { + t.pass('first called') + done(new Error('kaboom')) + }) + + app.use(function second (server, opts, done) { + t.fail('this should never be called') + }) + + app.ready((err) => { + t.equal(err.message, 'kaboom') + }) +}) + +test('keep loading if there is an .after', (t) => { + t.plan(4) + + const app = boot() + + app.use(function first (server, opts, done) { + t.pass('first called') + done(new Error('kaboom')) + }) + + app.after(function (err) { + t.equal(err.message, 'kaboom') + }) + + app.use(function second (server, opts, done) { + t.pass('second called') + done() + }) + + app.ready((err) => { + t.error(err) + }) +}) + +test('do not load nested plugin if parent errors', (t) => { + t.plan(4) + + const app = boot() + + app.use(function first (server, opts, done) { + t.pass('first called') + + server.use(function second (_, opts, done) { + t.fail('this should never be called') + }) + + done(new Error('kaboom')) + }) + + app.after(function (err) { + t.equal(err.message, 'kaboom') + }) + + app.use(function third (server, opts, done) { + t.pass('third called') + done() + }) + + app.ready((err) => { + t.error(err) + }) +}) + +test('.after nested', (t) => { + t.plan(4) + + const app = boot() + + app.use(function outer (app, opts, done) { + app.use(function first (app, opts, done) { + t.pass('first called') + done(new Error('kaboom')) + }) + + app.after(function (err) { + t.equal(err.message, 'kaboom') + }) + + app.use(function second (app, opts, done) { + t.pass('second called') + done() + }) + + done() + }) + + app.ready((err) => { + t.error(err) + }) +}) + +test('nested error', (t) => { + t.plan(4) + + const app = boot() + + app.use(function outer (app, opts, done) { + app.use(function first (app, opts, done) { + t.pass('first called') + done(new Error('kaboom')) + }) + + app.use(function second (app, opts, done) { + t.fail('this should never be called') + }) + + done() + }) + + app.after(function (err) { + t.equal(err.message, 'kaboom') + }) + + app.use(function third (server, opts, done) { + t.pass('third called') + done() + }) + + app.ready((err) => { + t.error(err) + }) +}) + +test('preReady event', (t) => { + t.plan(4) + + const app = boot() + const order = [1, 2] + + app.use(function first (server, opts, done) { + t.pass('first called') + done() + }) + + app.use(function second (server, opts, done) { + t.pass('second called') + done() + }) + + app.on('preReady', () => { + t.equal(order.shift(), 1) + }) + + app.ready(() => { + t.equal(order.shift(), 2) + }) +}) + +test('preReady event (multiple)', (t) => { + t.plan(6) + + const app = boot() + const order = [1, 2, 3, 4] + + app.use(function first (server, opts, done) { + t.pass('first called') + done() + }) + + app.use(function second (server, opts, done) { + t.pass('second called') + done() + }) + + app.on('preReady', () => { + t.equal(order.shift(), 1) + }) + + app.on('preReady', () => { + t.equal(order.shift(), 2) + }) + + app.on('preReady', () => { + t.equal(order.shift(), 3) + }) + + app.ready(() => { + t.equal(order.shift(), 4) + }) +}) + +test('preReady event (nested)', (t) => { + t.plan(6) + + const app = boot() + const order = [1, 2, 3, 4] + + app.use(function first (server, opts, done) { + t.pass('first called') + done() + }) + + app.use(function second (server, opts, done) { + t.pass('second called') + + server.on('preReady', () => { + t.equal(order.shift(), 3) + }) + + done() + }) + + app.on('preReady', () => { + t.equal(order.shift(), 1) + }) + + app.on('preReady', () => { + t.equal(order.shift(), 2) + }) + + app.ready(() => { + t.equal(order.shift(), 4) + }) +}) + +test('preReady event (errored)', (t) => { + t.plan(5) + + const app = boot() + const order = [1, 2, 3] + + app.use(function first (server, opts, done) { + t.pass('first called') + done(new Error('kaboom')) + }) + + app.use(function second (server, opts, done) { + t.fail('We should not be here') + }) + + app.on('preReady', () => { + t.equal(order.shift(), 1) + }) + + app.on('preReady', () => { + t.equal(order.shift(), 2) + }) + + app.ready((err) => { + t.ok(err) + t.equal(order.shift(), 3) + }) +}) + +test('after return self', (t) => { + t.plan(6) + + const app = boot() + let pluginLoaded = false + let afterCalled = false + let second = false + + app.use(function (s, opts, done) { + t.notOk(afterCalled, 'after not called') + pluginLoaded = true + done() + }) + + app.after(function () { + t.ok(pluginLoaded, 'afterred!') + afterCalled = true + // happens with after(() => app.use(..)) + return app + }) + + app.use(function (s, opts, done) { + t.ok(afterCalled, 'after called') + second = true + done() + }) + + app.on('start', () => { + t.ok(afterCalled, 'after called') + t.ok(pluginLoaded, 'plugin loaded') + t.ok(second, 'second plugin loaded') + }) +}) + +test('after 1 param swallows errors with server and timeout', (t) => { + t.plan(3) + + const server = {} + boot(server, { autostart: false, timeout: 1000 }) + + server.use(function first (server, opts, done) { + t.pass('first called') + done(new Error('kaboom')) + }) + + server.use(function second (server, opts, done) { + t.fail('We should not be here') + }) + + server.after(function (err) { + t.ok(err) + }) + + server.ready(function (err) { + t.error(err) + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/after-pass-through.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/after-pass-through.test.js new file mode 100644 index 0000000000000000000000000000000000000000..9f1f54a641a9825be3dc1d2248ad8142af7ed00e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/after-pass-through.test.js @@ -0,0 +1,32 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') + +test('proper support for after with a passed async function in wrapped mode', (t) => { + const app = {} + boot(app) + + t.plan(5) + + const e = new Error('kaboom') + + app.use(function (f, opts) { + return Promise.reject(e) + }).after(function (err, cb) { + t.equal(err, e) + cb(err) + }).after(function () { + t.pass('this is just called') + }).after(function (err, cb) { + t.equal(err, e) + cb(err) + }) + + app.ready().then(() => { + t.fail('this should not be called') + }).catch(err => { + t.ok(err) + t.equal(err.message, 'kaboom') + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/after-self-promise.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/after-self-promise.test.js new file mode 100644 index 0000000000000000000000000000000000000000..bc0df24063a2c76d6a29d53b1523176dd754f5a5 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/after-self-promise.test.js @@ -0,0 +1,20 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') + +test('after does not await itself', async (t) => { + t.plan(3) + + const app = {} + boot(app) + + app.use(async (app) => { + t.pass('plugin init') + }) + app.after(() => app) + t.pass('reachable') + + await app.ready() + t.pass('reachable') +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/after-throw.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/after-throw.test.js new file mode 100644 index 0000000000000000000000000000000000000000..c06e725709d42e6fdfd89f48ddc6f083829d5828 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/after-throw.test.js @@ -0,0 +1,24 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') + +test('catched error by Promise.reject', (t) => { + const app = boot() + t.plan(2) + + t.threw = function (err) { + t.equal(err.message, 'kaboom2') + } + + app.use(function (f, opts) { + return Promise.reject(new Error('kaboom')) + }).after(function (err) { + t.equal(err.message, 'kaboom') + throw new Error('kaboom2') + }) + + app.ready(function () { + t.fail('the ready callback should never be called') + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/after-use-after.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/after-use-after.test.js new file mode 100644 index 0000000000000000000000000000000000000000..d0ab5968b090307d470e6e9beda740e7b88dbc8d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/after-use-after.test.js @@ -0,0 +1,90 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') +const app = {} + +boot(app) + +test('multi after', (t) => { + t.plan(6) + + app.use(function (f, opts, cb) { + cb() + }).after(() => { + t.pass('this is just called') + + app.use(function (f, opts, cb) { + t.pass('this is just called') + cb() + }) + }).after(function () { + t.pass('this is just called') + app.use(function (f, opts, cb) { + t.pass('this is just called') + cb() + }) + }).after(function (err, cb) { + t.pass('this is just called') + cb(err) + }) + + app.ready().then(() => { + t.pass('ready') + }).catch(() => { + t.fail('this should not be called') + }) +}) + +test('after grouping - use called after after called', (t) => { + t.plan(9) + const app = {} + boot(app) + + const TEST_VALUE = {} + const OTHER_TEST_VALUE = {} + const NEW_TEST_VALUE = {} + + const sO = (fn) => { + fn[Symbol.for('skip-override')] = true + return fn + } + + app.use(sO(function (f, options, next) { + f.test = TEST_VALUE + + next() + })) + + app.after(function (err, f, done) { + t.error(err) + t.equal(f.test, TEST_VALUE) + + f.test2 = OTHER_TEST_VALUE + done() + }) + + app.use(sO(function (f, options, next) { + t.equal(f.test, TEST_VALUE) + t.equal(f.test2, OTHER_TEST_VALUE) + + f.test3 = NEW_TEST_VALUE + + next() + })) + + app.after(function (err, f, done) { + t.error(err) + t.equal(f.test, TEST_VALUE) + t.equal(f.test2, OTHER_TEST_VALUE) + t.equal(f.test3, NEW_TEST_VALUE) + done() + }) + + app.ready().then(() => { + t.pass('ready') + }).catch((e) => { + console.log(e) + t.fail('this should not be called') + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/async-await.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/async-await.test.js new file mode 100644 index 0000000000000000000000000000000000000000..428e9f017b501eaddb83cc6b3867f9b3f621946a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/async-await.test.js @@ -0,0 +1,325 @@ +'use strict' + +/* eslint no-prototype-builtins: off */ + +const { test } = require('tap') +const sleep = function (ms) { + return new Promise(function (resolve) { + setTimeout(resolve, ms) + }) +} + +const boot = require('..') + +test('one level', async (t) => { + t.plan(14) + + const app = boot() + let firstLoaded = false + let secondLoaded = false + let thirdLoaded = false + + app.use(first) + app.use(third) + + async function first (s, opts) { + t.notOk(firstLoaded, 'first is not loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + firstLoaded = true + s.use(second) + } + + async function second (s, opts) { + t.ok(firstLoaded, 'first is loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + secondLoaded = true + } + + async function third (s, opts) { + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.notOk(thirdLoaded, 'third is not loaded') + thirdLoaded = true + } + + const readyContext = await app.ready() + + t.equal(app, readyContext) + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.pass('booted') +}) + +test('multiple reentrant plugin loading', async (t) => { + t.plan(31) + + const app = boot() + let firstLoaded = false + let secondLoaded = false + let thirdLoaded = false + let fourthLoaded = false + let fifthLoaded = false + + app.use(first) + app.use(fifth) + + async function first (s, opts) { + t.notOk(firstLoaded, 'first is not loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + t.notOk(fourthLoaded, 'fourth is not loaded') + t.notOk(fifthLoaded, 'fifth is not loaded') + firstLoaded = true + s.use(second) + } + + async function second (s, opts) { + t.ok(firstLoaded, 'first is loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + t.notOk(fourthLoaded, 'fourth is not loaded') + t.notOk(fifthLoaded, 'fifth is not loaded') + secondLoaded = true + s.use(third) + await sleep(10) + s.use(fourth) + } + + async function third (s, opts) { + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.notOk(thirdLoaded, 'third is not loaded') + t.notOk(fourthLoaded, 'fourth is not loaded') + t.notOk(fifthLoaded, 'fifth is not loaded') + thirdLoaded = true + } + + async function fourth (s, opts) { + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.notOk(fourthLoaded, 'fourth is not loaded') + t.notOk(fifthLoaded, 'fifth is not loaded') + fourthLoaded = true + } + + async function fifth (s, opts) { + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.ok(fourthLoaded, 'fourth is loaded') + t.notOk(fifthLoaded, 'fifth is not loaded') + fifthLoaded = true + } + + await app.ready() + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.ok(fourthLoaded, 'fourth is loaded') + t.ok(fifthLoaded, 'fifth is loaded') + t.pass('booted') +}) + +test('async ready plugin registration (errored)', async (t) => { + t.plan(1) + + const app = boot() + + app.use(async (server, opts) => { + await sleep(10) + throw new Error('kaboom') + }) + + try { + await app.ready() + t.fail('we should not be here') + } catch (err) { + t.equal(err.message, 'kaboom') + } +}) + +test('after', async (t) => { + t.plan(15) + + const app = boot() + let firstLoaded = false + let secondLoaded = false + let thirdLoaded = false + + app.use(first) + + async function first (s, opts) { + t.notOk(firstLoaded, 'first is not loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + firstLoaded = true + s.after(second) + s.after(third) + } + + async function second (err) { + t.error(err) + t.ok(firstLoaded, 'first is loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + await sleep(10) + secondLoaded = true + } + + async function third () { + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.notOk(thirdLoaded, 'third is not loaded') + await sleep(10) + thirdLoaded = true + } + + const readyContext = await app.ready() + + t.equal(app, readyContext) + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.pass('booted') +}) + +test('after wrapped', async (t) => { + t.plan(15) + + const app = {} + boot(app) + let firstLoaded = false + let secondLoaded = false + let thirdLoaded = false + + app.use(first) + + async function first (s, opts) { + t.notOk(firstLoaded, 'first is not loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + firstLoaded = true + s.after(second) + s.after(third) + } + + async function second (err) { + t.error(err) + t.ok(firstLoaded, 'first is loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + await sleep(10) + secondLoaded = true + } + + async function third () { + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.notOk(thirdLoaded, 'third is not loaded') + await sleep(10) + thirdLoaded = true + } + + const readyContext = await app.ready() + + t.equal(app, readyContext) + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.pass('booted') +}) + +test('promise plugins', async (t) => { + t.plan(14) + + const app = boot() + let firstLoaded = false + let secondLoaded = false + let thirdLoaded = false + + app.use(first()) + app.use(third()) + + async function first () { + return async function (s, opts) { + t.notOk(firstLoaded, 'first is not loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + firstLoaded = true + s.use(second()) + } + } + + async function second () { + return async function (s, opts) { + t.ok(firstLoaded, 'first is loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + secondLoaded = true + } + } + + async function third () { + return async function (s, opts) { + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.notOk(thirdLoaded, 'third is not loaded') + thirdLoaded = true + } + } + + const readyContext = await app.ready() + + t.equal(app, readyContext) + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.pass('booted') +}) + +test('skip override with promise', (t) => { + t.plan(3) + + const server = { my: 'server' } + const app = boot(server) + + app.override = function (s, func) { + t.pass('override called') + + if (func[Symbol.for('skip-override')]) { + return s + } + return Object.create(s) + } + + app.use(first()) + + async function first () { + async function fn (s, opts) { + t.equal(s, server) + t.notOk(Object.prototype.isPrototypeOf.call(server, s)) + } + + fn[Symbol.for('skip-override')] = true + + return fn + } +}) + +test('ready queue error', async (t) => { + const app = boot() + app.use(first) + + async function first (s, opts) {} + + app.ready(function (_, worker, done) { + const error = new Error('kaboom') + done(error) + }) + + await t.rejects(app.ready(), { message: 'kaboom' }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/await-after.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/await-after.test.js new file mode 100644 index 0000000000000000000000000000000000000000..eb801da55b060ee4d6ddd679d6e3d0b21151a8f5 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/await-after.test.js @@ -0,0 +1,449 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') +const { promisify } = require('node:util') +const sleep = promisify(setTimeout) +const fs = require('node:fs').promises +const path = require('node:path') + +test('await after - nested plugins with same tick callbacks', async (t) => { + const app = {} + boot(app) + + let secondLoaded = false + + app.use(async (app) => { + t.pass('plugin init') + app.use(async () => { + t.pass('plugin2 init') + await sleep(1) + secondLoaded = true + }) + }) + await app.after() + t.pass('reachable') + t.equal(secondLoaded, true) + + await app.ready() + t.pass('reachable') +}) + +test('await after without server', async (t) => { + const app = boot() + + let secondLoaded = false + + app.use(async (app) => { + t.pass('plugin init') + app.use(async () => { + t.pass('plugin2 init') + await sleep(1) + secondLoaded = true + }) + }) + await app.after() + t.pass('reachable') + t.equal(secondLoaded, true) + + await app.ready() + t.pass('reachable') +}) + +test('await after with cb functions', async (t) => { + const app = boot() + let secondLoaded = false + let record = '' + + app.use(async (app) => { + t.pass('plugin init') + record += 'plugin|' + app.use(async () => { + t.pass('plugin2 init') + record += 'plugin2|' + await sleep(1) + secondLoaded = true + }) + }) + await app.after(() => { + record += 'after|' + }) + t.pass('reachable') + t.equal(secondLoaded, true) + record += 'ready' + await app.ready() + t.pass('reachable') + t.equal(record, 'plugin|plugin2|after|ready') +}) + +test('await after - nested plugins with future tick callbacks', async (t) => { + const app = {} + boot(app) + + t.plan(4) + + app.use((f, opts, cb) => { + t.pass('plugin init') + app.use((f, opts, cb) => { + t.pass('plugin2 init') + setImmediate(cb) + }) + setImmediate(cb) + }) + await app.after() + t.pass('reachable') + + await app.ready() + t.pass('reachable') +}) + +test('await after - nested async function plugins', async (t) => { + const app = {} + boot(app) + + t.plan(5) + + app.use(async (f, opts) => { + t.pass('plugin init') + await app.use(async (f, opts) => { + t.pass('plugin2 init') + }) + t.pass('reachable') + }) + await app.after() + t.pass('reachable') + + await app.ready() + t.pass('reachable') +}) + +test('await after - promise resolves to undefined', async (t) => { + const app = {} + boot(app) + + t.plan(4) + + app.use(async (f, opts, cb) => { + app.use((f, opts, cb) => { + t.pass('plugin init') + cb() + }) + const instance = await app.after() + t.equal(instance, undefined) + }) + t.pass('reachable') + + await app.ready() + t.pass('reachable') +}) + +test('await after - promise returning function plugins + promise chaining', async (t) => { + const app = {} + boot(app) + + t.plan(6) + + app.use((f, opts) => { + t.pass('plugin init') + return app.use((f, opts) => { + t.pass('plugin2 init') + return Promise.resolve() + }).then((f2) => { + t.equal(f2, f) + return 'test' + }).then((val) => { + t.equal(val, 'test') + }) + }) + await app.after() + t.pass('reachable') + + await app.ready() + t.pass('reachable') +}) + +test('await after - error handling, async throw', async (t) => { + const app = {} + boot(app) + + t.plan(2) + + const e = new Error('kaboom') + + app.use(async (f, opts) => { + throw Error('kaboom') + }) + + await t.rejects(app.after(), e) + + await t.rejects(() => app.ready(), Error('kaboom')) +}) + +test('await after - error handling, async throw, nested', async (t) => { + const app = {} + boot(app) + + t.plan(2) + + const e = new Error('kaboom') + + app.use(async (f, opts) => { + app.use(async (f, opts) => { + throw e + }) + }) + + await t.rejects(app.after()) + await t.rejects(() => app.ready(), e) +}) + +test('await after - error handling, same tick cb err', async (t) => { + const app = {} + boot(app) + + t.plan(2) + + app.use((f, opts, cb) => { + cb(Error('kaboom')) + }) + await t.rejects(app.after()) + await t.rejects(app.ready(), Error('kaboom')) +}) + +test('await after - error handling, same tick cb err, nested', async (t) => { + const app = {} + boot(app) + + t.plan(2) + + app.use((f, opts, cb) => { + app.use((f, opts, cb) => { + cb(Error('kaboom')) + }) + cb() + }) + + await t.rejects(app.after()) + await t.rejects(app.ready(), Error('kaboom')) +}) + +test('await after - error handling, future tick cb err', async (t) => { + const app = {} + boot(app) + + t.plan(2) + + app.use((f, opts, cb) => { + setImmediate(() => { cb(Error('kaboom')) }) + }) + + await t.rejects(app.after()) + await t.rejects(app.ready(), Error('kaboom')) +}) + +test('await after - error handling, future tick cb err, nested', async (t) => { + const app = {} + boot(app) + + t.plan(2) + + app.use((f, opts, cb) => { + app.use((f, opts, cb) => { + setImmediate(() => { cb(Error('kaboom')) }) + }) + cb() + }) + await t.rejects(app.after(), Error('kaboom')) + await t.rejects(app.ready(), Error('kaboom')) +}) + +test('await after complex scenario', async (t) => { + const app = {} + boot(app) + t.plan(16) + + let firstLoaded = false + let secondLoaded = false + let thirdLoaded = false + let fourthLoaded = false + + app.use(first) + await app.after() + t.ok(firstLoaded, 'first is loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + t.notOk(fourthLoaded, 'fourth is not loaded') + app.use(second) + t.ok(firstLoaded, 'first is loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + t.notOk(fourthLoaded, 'fourth is not loaded') + app.use(third) + await app.after() + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.ok(fourthLoaded, 'fourth is loaded') + await app.ready() + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.ok(fourthLoaded, 'fourth is loaded') + + async function first () { + firstLoaded = true + } + + async function second () { + secondLoaded = true + } + + async function third (app) { + thirdLoaded = true + app.use(fourth) + } + + async function fourth () { + fourthLoaded = true + } +}) + +test('without autostart and sync/async plugin mix', async (t) => { + const app = {} + boot(app, { autostart: false }) + t.plan(21) + + let firstLoaded = false + let secondLoaded = false + let thirdLoaded = false + let fourthLoaded = false + + app.use(first) + await app.after() + t.ok(firstLoaded, 'first is loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + t.notOk(fourthLoaded, 'fourth is not loaded') + + app.use(second) + await app.after() + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.notOk(thirdLoaded, 'third is not loaded') + t.notOk(fourthLoaded, 'fourth is not loaded') + + await sleep(10) + + app.use(third) + await app.after() + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.notOk(fourthLoaded, 'fourth is not loaded') + + app.use(fourth) + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.notOk(fourthLoaded, 'fourth is not loaded') + + await app.after() + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.ok(fourthLoaded, 'fourth is loaded') + + await app.ready() + + async function first () { + firstLoaded = true + } + + async function second () { + const contents = await fs.readFile(path.join(__dirname, 'fixtures', 'dummy.txt'), 'utf-8') + t.equal(contents, 'hello, world!') + secondLoaded = true + } + + async function third () { + await sleep(10) + thirdLoaded = true + } + + function fourth (server, opts, done) { + fourthLoaded = true + done() + } +}) + +test('without autostart', async (t) => { + const app = {} + boot(app, { autostart: false }) + let firstLoaded = false + let secondLoaded = false + let thirdLoaded = false + + app.use(async function first (app) { + firstLoaded = true + app.use(async () => { + await sleep(1) + secondLoaded = true + }) + }) + + await app.after() + t.equal(firstLoaded, true) + t.equal(secondLoaded, true) + + await app.use(async () => { + thirdLoaded = true + }) + + t.equal(thirdLoaded, true) + + await app.ready() +}) + +test('without autostart and with override', async (t) => { + const app = {} + const _ = boot(app, { autostart: false }) + let count = 0 + + _.override = function (s) { + const res = Object.create(s) + res.count = ++count + + return res + } + + app.use(async function first (app) { + t.equal(app.count, 1) + app.use(async (app) => { + t.equal(app.count, 2) + await app.after() + }) + }) + + await app.after() + + await app.use(async (app) => { + t.equal(app.count, 3) + }) + + await app.ready() +}) + +test('stop processing after errors', async (t) => { + t.plan(2) + + const app = boot() + + try { + await app.use(async function first (app) { + t.pass('first should be loaded') + throw new Error('kaboom') + }) + } catch (e) { + t.equal(e.message, 'kaboom') + } +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/await-self.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/await-self.test.js new file mode 100644 index 0000000000000000000000000000000000000000..8d8c9908be3d5c435c0ec4cdd63eb1fb7761fc18 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/await-self.test.js @@ -0,0 +1,31 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') + +test('await self', async (t) => { + const app = {} + boot(app) + + t.equal(await app, app) +}) + +test('await self three times', async (t) => { + const app = {} + boot(app) + + t.equal(await app, app) + t.equal(await app, app) + t.equal(await app, app) +}) + +test('await self within plugin', async (t) => { + const app = {} + boot(app) + + app.use(async (f) => { + t.equal(await f, f) + }) + + t.equal(await app, app) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/await-use.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/await-use.test.js new file mode 100644 index 0000000000000000000000000000000000000000..f8adee86641d5fcd5466c7a8deed12fae85c3e7f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/await-use.test.js @@ -0,0 +1,294 @@ +'use strict' + +const { test } = require('tap') +const { promisify } = require('node:util') +const sleep = promisify(setTimeout) +const boot = require('..') + +test('await use - nested plugins with same tick callbacks', async (t) => { + const app = {} + boot(app) + + t.plan(4) + + await app.use((f, opts, cb) => { + t.pass('plugin init') + app.use((f, opts, cb) => { + t.pass('plugin2 init') + cb() + }) + cb() + }) + t.pass('reachable') + + await app.ready() + t.pass('reachable') +}) + +test('await use - nested plugins with future tick callbacks', async (t) => { + const app = {} + boot(app) + + t.plan(4) + + await app.use((f, opts, cb) => { + t.pass('plugin init') + app.use((f, opts, cb) => { + t.pass('plugin2 init') + setImmediate(cb) + }) + setImmediate(cb) + }) + t.pass('reachable') + + await app.ready() + t.pass('reachable') +}) + +test('await use - nested async function plugins', async (t) => { + const app = {} + boot(app) + + t.plan(5) + + await app.use(async (f, opts) => { + t.pass('plugin init') + await app.use(async (f, opts) => { + t.pass('plugin2 init') + }) + t.pass('reachable') + }) + t.pass('reachable') + + await app.ready() + t.pass('reachable') +}) + +test('await use - promise returning function plugins + promise chaining', async (t) => { + const app = {} + boot(app) + + t.plan(6) + + await app.use((f, opts) => { + t.pass('plugin init') + return app.use((f, opts) => { + t.pass('plugin2 init') + return Promise.resolve() + }).then(() => { + t.pass('reachable') + return 'test' + }).then((val) => { + t.equal(val, 'test') + }) + }) + t.pass('reachable') + + await app.ready() + t.pass('reachable') +}) + +test('await use - await and use chaining', async (t) => { + const app = {} + boot(app) + + t.plan(3) + + app.use(async (f, opts, cb) => { + await app.use(async (f, opts) => { + t.pass('plugin init') + }).use(async (f, opts) => { + t.pass('plugin2 init') + }) + }) + + await app.ready() + t.pass('reachable') +}) + +function thenableRejects (t, thenable, err, msg) { + return t.rejects(async () => { await thenable }, err, msg) +} + +test('await use - error handling, async throw', async (t) => { + const app = {} + boot(app) + + t.plan(2) + + await thenableRejects(t, app.use(async (f, opts) => { + throw Error('kaboom') + }), Error('kaboom')) + + await t.rejects(app.ready(), Error('kaboom')) +}) + +test('await use - error handling, async throw, nested', async (t) => { + const app = {} + boot(app) + + t.plan(2) + + await thenableRejects(t, app.use(async function a (f, opts) { + await app.use(async function b (f, opts) { + throw Error('kaboom') + }) + }, Error('kaboom')), 'b') + + t.rejects(() => app.ready(), Error('kaboom')) +}) + +test('await use - error handling, same tick cb err', async (t) => { + const app = {} + boot(app) + + t.plan(2) + + await thenableRejects(t, app.use((f, opts, cb) => { + cb(Error('kaboom')) + }), Error('kaboom')) + + t.rejects(() => app.ready(), Error('kaboom')) +}) + +test('await use - error handling, same tick cb err, nested', async (t) => { + const app = {} + boot(app) + + t.plan(2) + + await thenableRejects(t, app.use((f, opts, cb) => { + app.use((f, opts, cb) => { + cb(Error('kaboom')) + }) + cb() + }), Error('kaboom')) + + t.rejects(() => app.ready(), Error('kaboom')) +}) + +test('await use - error handling, future tick cb err', async (t) => { + const app = {} + boot(app) + + t.plan(2) + + await thenableRejects(t, app.use((f, opts, cb) => { + setImmediate(() => { cb(Error('kaboom')) }) + }), Error('kaboom')) + + t.rejects(() => app.ready(), Error('kaboom')) +}) + +test('await use - error handling, future tick cb err, nested', async (t) => { + const app = {} + boot(app) + + t.plan(2) + + await thenableRejects(t, app.use((f, opts, cb) => { + app.use((f, opts, cb) => { + setImmediate(() => { cb(Error('kaboom')) }) + }) + cb() + }), Error('kaboom')) + + t.rejects(() => app.ready(), Error('kaboom')) +}) + +test('mixed await use and non-awaited use ', async (t) => { + const app = {} + boot(app) + t.plan(16) + + let firstLoaded = false + let secondLoaded = false + let thirdLoaded = false + let fourthLoaded = false + + await app.use(first) + t.ok(firstLoaded, 'first is loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + t.notOk(fourthLoaded, 'fourth is not loaded') + app.use(second) + t.ok(firstLoaded, 'first is loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + t.notOk(fourthLoaded, 'fourth is not loaded') + await app.use(third) + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.ok(fourthLoaded, 'fourth is loaded') + await app.ready() + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.ok(fourthLoaded, 'fourth is loaded') + + async function first () { + firstLoaded = true + } + + async function second () { + secondLoaded = true + } + + async function third (app) { + thirdLoaded = true + app.use(fourth) + } + + async function fourth () { + fourthLoaded = true + } +}) + +test('await use - mix of same and future tick callbacks', async (t) => { + const app = {} + boot(app, { autostart: false }) + let record = '' + + t.plan(4) + + await app.use(async function plugin0 () { + t.pass('plugin0 init') + record += 'plugin0|' + }) + await app.use(async function plugin1 () { + t.pass('plugin1 init') + await sleep(500) + record += 'plugin1|' + }) + await sleep(1) + await app.use(async function plugin2 () { + t.pass('plugin2 init') + await sleep(500) + record += 'plugin2|' + }) + record += 'ready' + t.equal(record, 'plugin0|plugin1|plugin2|ready') +}) + +test('await use - fork the promise chain', (t) => { + t.plan(3) + const app = {} + boot(app, { autostart: false }) + + async function setup () { + let set = false + await app.use(async function plugin0 () { + t.pass('plugin0 init') + await sleep(500) + set = true + }) + t.equal(set, true) + } + setup() + + app.ready((err, done) => { + t.error(err) + done() + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/basic.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/basic.test.js new file mode 100644 index 0000000000000000000000000000000000000000..05a4810b7e78d9bfda32959fa00e36cf047cfc29 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/basic.test.js @@ -0,0 +1,439 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') + +test('boot an empty app', (t) => { + t.plan(1) + const app = boot() + app.on('start', () => { + t.pass('booted') + }) +}) + +test('start returns app', (t) => { + t.plan(1) + const app = boot({}, { autostart: false }) + app + .start() + .ready((err) => { + t.error(err) + }) +}) + +test('boot an app with a plugin', (t) => { + t.plan(4) + + const app = boot() + let after = false + + app.use(function (server, opts, done) { + t.equal(server, app, 'the first argument is the server') + t.same(opts, {}, 'no options') + t.ok(after, 'delayed execution') + done() + }) + + after = true + + app.on('start', () => { + t.pass('booted') + }) +}) + +test('boot an app with a promisified plugin', (t) => { + t.plan(4) + + const app = boot() + let after = false + + app.use(function (server, opts) { + t.equal(server, app, 'the first argument is the server') + t.same(opts, {}, 'no options') + t.ok(after, 'delayed execution') + return Promise.resolve() + }) + + after = true + + app.on('start', () => { + t.pass('booted') + }) +}) + +test('boot an app with a plugin and a callback /1', (t) => { + t.plan(2) + + const app = boot(() => { + t.pass('booted') + }) + + app.use(function (server, opts, done) { + t.pass('plugin loaded') + done() + }) +}) + +test('boot an app with a plugin and a callback /2', (t) => { + t.plan(2) + + const app = boot({}, () => { + t.pass('booted') + }) + + app.use(function (server, opts, done) { + t.pass('plugin loaded') + done() + }) +}) + +test('boot a plugin with a custom server', (t) => { + t.plan(4) + + const server = {} + const app = boot(server) + + app.use(function (s, opts, done) { + t.equal(s, server, 'the first argument is the server') + t.same(opts, {}, 'no options') + done() + }) + + app.onClose(() => { + t.ok('onClose called') + }) + + app.on('start', () => { + app.close(() => { + t.pass('booted') + }) + }) +}) + +test('custom instance should inherits avvio methods /1', (t) => { + t.plan(6) + + const server = {} + const app = boot(server, {}) + + server.use(function (s, opts, done) { + t.equal(s, server, 'the first argument is the server') + t.same(opts, {}, 'no options') + done() + }).after(() => { + t.ok('after called') + }) + + server.onClose(() => { + t.ok('onClose called') + }) + + server.ready(() => { + t.ok('ready called') + }) + + app.on('start', () => { + server.close(() => { + t.pass('booted') + }) + }) +}) + +test('custom instance should inherits avvio methods /2', (t) => { + t.plan(6) + + const server = {} + const app = new boot(server, {}) // eslint-disable-line new-cap + + server.use(function (s, opts, done) { + t.equal(s, server, 'the first argument is the server') + t.same(opts, {}, 'no options') + done() + }).after(() => { + t.ok('after called') + }) + + server.onClose(() => { + t.ok('onClose called') + }) + + server.ready(() => { + t.ok('ready called') + }) + + app.on('start', () => { + server.close(() => { + t.pass('booted') + }) + }) +}) + +test('boot a plugin with options', (t) => { + t.plan(3) + + const server = {} + const app = boot(server) + const myOpts = { + hello: 'world' + } + + app.use(function (s, opts, done) { + t.equal(s, server, 'the first argument is the server') + t.same(opts, myOpts, 'passed options') + done() + }, myOpts) + + app.on('start', () => { + t.pass('booted') + }) +}) + +test('boot a plugin with a function that returns the options', (t) => { + t.plan(4) + + const server = {} + const app = boot(server) + const myOpts = { + hello: 'world' + } + const myOptsAsFunc = parent => { + t.equal(parent, server) + return parent.myOpts + } + + app.use(function (s, opts, done) { + s.myOpts = opts + done() + }, myOpts) + + app.use(function (s, opts, done) { + t.equal(s, server, 'the first argument is the server') + t.same(opts, myOpts, 'passed options via function accessing parent injected variable') + done() + }, myOptsAsFunc) + + app.on('start', () => { + t.pass('booted') + }) +}) + +test('throw on non-function use', (t) => { + t.plan(1) + const app = boot() + t.throws(() => { + app.use({}) + }) +}) + +// https://github.com/mcollina/avvio/issues/20 +test('ready and nextTick', (t) => { + const app = boot() + process.nextTick(() => { + app.ready(() => { + t.end() + }) + }) +}) + +// https://github.com/mcollina/avvio/issues/20 +test('promises and microtask', (t) => { + const app = boot() + Promise.resolve() + .then(() => { + app.ready(function () { + t.end() + }) + }) +}) + +test('always loads nested plugins after the current one', (t) => { + t.plan(2) + + const server = {} + const app = boot(server) + + let second = false + + app.use(function (s, opts, done) { + app.use(function (s, opts, done) { + second = true + done() + }) + t.notOk(second) + + done() + }) + + app.on('start', () => { + t.ok(second) + }) +}) + +test('promise long resolve', (t) => { + t.plan(2) + + const app = boot() + + setTimeout(function () { + t.throws(() => { + app.use((s, opts, done) => { + done() + }) + }, 'root plugin has already booted') + }) + + app.ready(function (err) { + t.notOk(err) + }) +}) + +test('do not autostart', (t) => { + const app = boot(null, { + autostart: false + }) + app.on('start', () => { + t.fail() + }) + t.end() +}) + +test('start with ready', (t) => { + t.plan(2) + + const app = boot(null, { + autostart: false + }) + + app.on('start', () => { + t.pass() + }) + + app.ready(function (err) { + t.error(err) + }) +}) + +test('load a plugin after start()', (t) => { + t.plan(1) + + let startCalled = false + const app = boot(null, { + autostart: false + }) + + app.use((s, opts, done) => { + t.ok(startCalled) + done() + }) + + // we use a timer because + // it is more reliable than + // nextTick and setImmediate + // this almost always will come + // after those are completed + setTimeout(() => { + app.start() + startCalled = true + }, 2) +}) + +test('booted should be set before ready', (t) => { + t.plan(2) + + const app = boot() + + app.ready(function (err) { + t.error(err) + t.equal(app.booted, true) + }) +}) + +test('start should be emitted after ready resolves', (t) => { + t.plan(1) + + const app = boot() + let ready = false + + app.ready().then(function () { + ready = true + }) + + app.on('start', function () { + t.equal(ready, true) + }) +}) + +test('throws correctly if registering after ready', (t) => { + t.plan(1) + + const app = boot() + + app.ready(function () { + t.throws(() => { + app.use((a, b, done) => done()) + }, 'root plugin has already booted') + }) +}) + +test('preReady errors must be managed', (t) => { + t.plan(2) + + const app = boot() + + app.use((f, opts, cb) => { + cb() + }) + + app.on('preReady', () => { + throw new Error('boom') + }) + + app.ready(err => { + t.pass('ready function is called') + t.equal(err.message, 'boom') + }) +}) + +test('preReady errors do not override plugin\'s errors', (t) => { + t.plan(3) + + const app = boot() + + app.use((f, opts, cb) => { + cb(new Error('baam')) + }) + + app.on('preReady', () => { + t.pass('preReady is executed') + throw new Error('boom') + }) + + app.ready(err => { + t.pass('ready function is called') + t.equal(err.message, 'baam') + }) +}) + +test('support faux modules', (t) => { + t.plan(4) + + const app = boot() + let after = false + + // Faux modules are modules built with TypeScript + // or Babel that they export a .default property. + app.use({ + default: function (server, opts, done) { + t.equal(server, app, 'the first argument is the server') + t.same(opts, {}, 'no options') + t.ok(after, 'delayed execution') + done() + } + }) + + after = true + + app.on('start', () => { + t.pass('booted') + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/callbacks.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/callbacks.test.js new file mode 100644 index 0000000000000000000000000000000000000000..2e7ac1c2d46876b72d835a607f45fae251cbbe7a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/callbacks.test.js @@ -0,0 +1,113 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') + +test('reentrant', (t) => { + t.plan(7) + + const app = boot() + let firstLoaded = false + let secondLoaded = false + + app + .use(first) + .after(() => { + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.pass('booted') + }) + + function first (s, opts, done) { + t.notOk(firstLoaded, 'first is not loaded') + t.notOk(secondLoaded, 'second is not loaded') + firstLoaded = true + s.use(second) + done() + } + + function second (s, opts, done) { + t.ok(firstLoaded, 'first is loaded') + t.notOk(secondLoaded, 'second is not loaded') + secondLoaded = true + done() + } +}) + +test('reentrant with callbacks deferred', (t) => { + t.plan(11) + + const app = boot() + let firstLoaded = false + let secondLoaded = false + let thirdLoaded = false + + app.use(first) + + function first (s, opts, done) { + t.notOk(firstLoaded, 'first is not loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + firstLoaded = true + s.use(second) + setTimeout(() => { + try { + s.use(third) + } catch (err) { + t.equal(err.message, 'Root plugin has already booted') + } + }, 500) + done() + } + + function second (s, opts, done) { + t.ok(firstLoaded, 'first is loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + secondLoaded = true + done() + } + + function third (s, opts, done) { + thirdLoaded = true + done() + } + + app.on('start', () => { + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.notOk(thirdLoaded, 'third is not loaded') + t.pass('booted') + }) +}) + +test('multiple loading time', t => { + t.plan(1) + const app = boot() + + function a (instance, opts, done) { + (opts.use || []).forEach(_ => { instance.use(_, { use: opts.subUse || [] }) }) + setTimeout(done, 10) + } + const pointer = a + + function b (instance, opts, done) { + (opts.use || []).forEach(_ => { instance.use(_, { use: opts.subUse || [] }) }) + setTimeout(done, 20) + } + + function c (instance, opts, done) { + (opts.use || []).forEach(_ => { instance.use(_, { use: opts.subUse || [] }) }) + setTimeout(done, 30) + } + + app + .use(function a (instance, opts, done) { + instance.use(pointer, { use: [b], subUse: [c] }) + .use(b) + setTimeout(done, 0) + }) + .after(() => { + t.pass('booted') + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/catch-override-exception.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/catch-override-exception.test.js new file mode 100644 index 0000000000000000000000000000000000000000..fdcd58aa1d239b47255782c4ff7141a053baa62d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/catch-override-exception.test.js @@ -0,0 +1,26 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') + +test('catch exceptions in parent.override', (t) => { + t.plan(2) + + const server = {} + + const app = boot(server, { + autostart: false + }) + app.override = function () { + throw Error('catch it') + } + + app + .use(function () {}) + .start() + + app.ready(function (err) { + t.type(err, Error) + t.match(err, /catch it/) + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/chainable.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/chainable.test.js new file mode 100644 index 0000000000000000000000000000000000000000..d07a7ac0ddde64bd8d82e5b0d639de99b3309369 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/chainable.test.js @@ -0,0 +1,67 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') + +test('chainable standalone', (t) => { + t.plan(5) + + const readyResult = boot() + .use(function (ctx, opts, done) { + t.pass('1st plugin') + done() + }).after(function (err, done) { + t.error(err) + t.pass('2nd after') + done() + }).ready(function () { + t.pass('we are ready') + }) + t.equal(readyResult, undefined) +}) + +test('chainable automatically binded', (t) => { + t.plan(5) + + const app = {} + boot(app) + + const readyResult = app + .use(function (ctx, opts, done) { + t.pass('1st plugin') + done() + }).after(function (err, done) { + t.error(err) + t.pass('2nd after') + done() + }).ready(function () { + t.pass('we are ready') + }) + t.equal(readyResult, undefined) +}) + +test('chainable standalone with server', (t) => { + t.plan(6) + + const server = {} + boot(server, { + expose: { + use: 'register' + } + }) + + const readyResult = server.register(function (ctx, opts, done) { + t.pass('1st plugin') + done() + }).after(function (err, done) { + t.error(err) + t.pass('2nd after') + done() + }).register(function (ctx, opts, done) { + t.pass('3rd plugin') + done() + }).ready(function () { + t.pass('we are ready') + }) + t.equal(readyResult, undefined) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/close.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/close.test.js new file mode 100644 index 0000000000000000000000000000000000000000..a02914b8ed4c5f14ff0059251779e6b645c049fc --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/close.test.js @@ -0,0 +1,544 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') +const { AVV_ERR_CALLBACK_NOT_FN } = require('../lib/errors') + +test('boot an app with a plugin', (t) => { + t.plan(4) + + const app = boot() + let last = false + + app.use(function (server, opts, done) { + app.onClose(() => { + t.ok('onClose called') + t.notOk(last) + last = true + }) + done() + }) + + app.on('start', () => { + app.close(() => { + t.ok(last) + t.pass('Closed in the correct order') + }) + }) +}) + +test('onClose arguments', (t) => { + t.plan(5) + + const app = boot() + + app.use(function (server, opts, next) { + server.onClose((instance, done) => { + t.ok('called') + t.equal(server, instance) + done() + }) + next() + }) + + app.use(function (server, opts, next) { + server.onClose((instance) => { + t.ok('called') + t.equal(server, instance) + }) + next() + }) + + app.on('start', () => { + app.close(() => { + t.pass('Closed in the correct order') + }) + }) +}) + +test('onClose arguments - fastify encapsulation test case', (t) => { + t.plan(5) + + const server = { my: 'server' } + const app = boot(server) + + app.override = function (s, fn, opts) { + s = Object.create(s) + return s + } + + app.use(function (instance, opts, next) { + instance.test = true + instance.onClose((i, done) => { + t.ok(i.test) + done() + }) + next() + }) + + app.use(function (instance, opts, next) { + t.notOk(instance.test) + instance.onClose((i, done) => { + t.notOk(i.test) + done() + }) + next() + }) + + app.on('start', () => { + t.notOk(app.test) + app.close(() => { + t.pass('Closed in the correct order') + }) + }) +}) + +test('onClose arguments - fastify encapsulation test case / 2', (t) => { + t.plan(5) + + const server = { my: 'server' } + const app = boot(server) + + app.override = function (s, fn, opts) { + s = Object.create(s) + return s + } + + server.use(function (instance, opts, next) { + instance.test = true + instance.onClose((i, done) => { + t.ok(i.test) + done() + }) + next() + }) + + server.use(function (instance, opts, next) { + t.notOk(instance.test) + instance.onClose((i, done) => { + t.notOk(i.test) + done() + }) + next() + }) + + app.on('start', () => { + t.notOk(server.test) + try { + server.close() + t.pass() + } catch (err) { + t.fail(err) + } + }) +}) + +test('onClose arguments - encapsulation test case no server', (t) => { + t.plan(5) + + const app = boot() + + app.override = function (s, fn, opts) { + s = Object.create(s) + return s + } + + app.use(function (instance, opts, next) { + instance.test = true + instance.onClose((i, done) => { + t.notOk(i.test) + done() + }) + next() + }) + + app.use(function (instance, opts, next) { + t.notOk(instance.test) + instance.onClose((i) => { + t.notOk(i.test) + }) + next() + }) + + app.on('start', () => { + t.notOk(app.test) + app.close(() => { + t.pass('Closed in the correct order') + }) + }) +}) + +test('onClose should handle errors', (t) => { + t.plan(3) + + const app = boot() + + app.use(function (server, opts, done) { + app.onClose((instance, done) => { + t.ok('called') + done(new Error('some error')) + }) + done() + }) + + app.on('start', () => { + app.close(err => { + t.equal(err.message, 'some error') + t.pass('Closed in the correct order') + }) + }) +}) + +test('#54 close handlers should receive same parameters when queue is not empty', (t) => { + t.plan(6) + + const context = { test: true } + const app = boot(context) + + app.use(function (server, opts, done) { + done() + }) + app.on('start', () => { + app.close((err, done) => { + t.equal(err, null) + t.pass('Closed in the correct order') + setImmediate(done) + }) + app.close(err => { + t.equal(err, null) + t.pass('Closed in the correct order') + }) + app.close(err => { + t.equal(err, null) + t.pass('Closed in the correct order') + }) + }) +}) + +test('onClose should handle errors / 2', (t) => { + t.plan(4) + + const app = boot() + + app.onClose((instance, done) => { + t.ok('called') + done(new Error('some error')) + }) + + app.use(function (server, opts, done) { + app.onClose((instance, done) => { + t.ok('called') + done() + }) + done() + }) + + app.on('start', () => { + app.close(err => { + t.equal(err.message, 'some error') + t.pass('Closed in the correct order') + }) + }) +}) + +test('close arguments', (t) => { + t.plan(4) + + const app = boot() + + app.use(function (server, opts, done) { + app.onClose((instance, done) => { + t.ok('called') + done() + }) + done() + }) + + app.on('start', () => { + app.close((err, instance, done) => { + t.error(err) + t.equal(instance, app) + done() + t.pass('Closed in the correct order') + }) + }) +}) + +test('close event', (t) => { + t.plan(3) + + const app = boot() + let last = false + + app.on('start', () => { + app.close(() => { + t.notOk(last) + last = true + }) + }) + + app.on('close', () => { + t.ok(last) + t.pass('event fired') + }) +}) + +test('close order', (t) => { + t.plan(5) + + const app = boot() + const order = [1, 2, 3, 4] + + app.use(function (server, opts, done) { + app.onClose(() => { + t.equal(order.shift(), 3) + }) + + app.use(function (server, opts, done) { + app.onClose(() => { + t.equal(order.shift(), 2) + }) + done() + }) + done() + }) + + app.use(function (server, opts, done) { + app.onClose(() => { + t.equal(order.shift(), 1) + }) + done() + }) + + app.on('start', () => { + app.close(() => { + t.equal(order.shift(), 4) + t.pass('Closed in the correct order') + }) + }) +}) + +test('close without a cb', (t) => { + t.plan(1) + + const app = boot() + + app.onClose((instance, done) => { + t.ok('called') + done() + }) + + app.close() +}) + +test('onClose with 0 parameters', (t) => { + t.plan(4) + + const server = { my: 'server' } + const app = boot(server) + + app.use(function (instance, opts, next) { + instance.onClose(function () { + t.ok('called') + t.equal(arguments.length, 0) + }) + next() + }) + + app.close(err => { + t.error(err) + t.pass('Closed') + }) +}) + +test('onClose with 1 parameter', (t) => { + t.plan(3) + + const server = { my: 'server' } + const app = boot(server) + + app.use(function (instance, opts, next) { + instance.onClose(function (context) { + t.equal(arguments.length, 1) + }) + next() + }) + + app.close(err => { + t.error(err) + t.pass('Closed') + }) +}) + +test('close passing not a function', (t) => { + t.plan(1) + + const app = boot() + + app.onClose((instance, done) => { + t.ok('called') + done() + }) + + t.throws(() => app.close({}), { message: 'not a function' }) +}) + +test('close passing not a function', (t) => { + t.plan(1) + + const app = boot() + + app.onClose((instance, done) => { + t.ok('called') + done() + }) + + t.throws(() => app.close({}), { message: 'not a function' }) +}) + +test('close passing not a function when wrapping', (t) => { + t.plan(1) + + const app = {} + boot(app) + + app.onClose((instance, done) => { + t.ok('called') + done() + }) + + t.throws(() => app.close({}), { message: 'not a function' }) +}) + +test('close should trigger ready()', (t) => { + t.plan(2) + + const app = boot(null, { + autostart: false + }) + + app.on('start', () => { + // this will be emitted after the + // callback in close() is fired + t.pass('started') + }) + + app.close(() => { + t.pass('closed') + }) +}) + +test('close without a cb returns a promise', (t) => { + t.plan(1) + + const app = boot() + app.close().then(() => { + t.pass('promise resolves') + }) +}) + +test('close without a cb returns a promise when attaching to a server', (t) => { + t.plan(1) + + const server = {} + boot(server) + server.close().then(() => { + t.pass('promise resolves') + }) +}) + +test('close with async onClose handlers', t => { + t.plan(7) + + const app = boot() + const order = [1, 2, 3, 4, 5, 6] + + app.onClose(() => { + return new Promise(resolve => setTimeout(resolve, 500)).then(() => { + t.equal(order.shift(), 5) + }) + }) + + app.onClose(() => { + t.equal(order.shift(), 4) + }) + + app.onClose(instance => { + return new Promise(resolve => setTimeout(resolve, 500)).then(() => { + t.equal(order.shift(), 3) + }) + }) + + app.onClose(async instance => { + return new Promise(resolve => setTimeout(resolve, 500)).then(() => { + t.equal(order.shift(), 2) + }) + }) + + app.onClose(async () => { + return new Promise(resolve => setTimeout(resolve, 500)).then(() => { + t.equal(order.shift(), 1) + }) + }) + + app.on('start', () => { + app.close(() => { + t.equal(order.shift(), 6) + t.pass('Closed in the correct order') + }) + }) +}) + +test('onClose callback must be a function', (t) => { + t.plan(1) + + const app = boot() + + app.use(function (server, opts, done) { + t.throws(() => app.onClose({}), new AVV_ERR_CALLBACK_NOT_FN('onClose', 'object')) + done() + }) +}) + +test('close custom server with async onClose handlers', t => { + t.plan(7) + + const server = {} + const app = boot(server) + const order = [1, 2, 3, 4, 5, 6] + + server.onClose(() => { + return new Promise(resolve => setTimeout(resolve, 500)).then(() => { + t.equal(order.shift(), 5) + }) + }) + + server.onClose(() => { + t.equal(order.shift(), 4) + }) + + server.onClose(instance => { + return new Promise(resolve => setTimeout(resolve, 500)).then(() => { + t.equal(order.shift(), 3) + }) + }) + + server.onClose(async instance => { + return new Promise(resolve => setTimeout(resolve, 500)).then(() => { + t.equal(order.shift(), 2) + }) + }) + + server.onClose(async () => { + return new Promise(resolve => setTimeout(resolve, 500)).then(() => { + t.equal(order.shift(), 1) + }) + }) + + app.on('start', () => { + app.close(() => { + t.equal(order.shift(), 6) + t.pass('Closed in the correct order') + }) + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/errors.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/errors.test.js new file mode 100644 index 0000000000000000000000000000000000000000..e18138259bf1224ed6eac0a9300ed5c8ecd2a43d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/errors.test.js @@ -0,0 +1,26 @@ +'use strict' + +const { test } = require('tap') +const errors = require('../lib/errors') + +test('Correct codes of AvvioErrors', t => { + const testcases = [ + 'AVV_ERR_EXPOSE_ALREADY_DEFINED', + 'AVV_ERR_ATTRIBUTE_ALREADY_DEFINED', + 'AVV_ERR_CALLBACK_NOT_FN', + 'AVV_ERR_PLUGIN_NOT_VALID', + 'AVV_ERR_ROOT_PLG_BOOTED', + 'AVV_ERR_PARENT_PLG_LOADED', + 'AVV_ERR_READY_TIMEOUT', + 'AVV_ERR_PLUGIN_EXEC_TIMEOUT' + ] + + t.plan(testcases.length + 1) + // errors.js exposes errors and the createError fn + t.equal(testcases.length, Object.keys(errors).length) + + for (const testcase of testcases) { + const error = new errors[testcase]() + t.equal(error.code, testcase) + } +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/esm.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/esm.mjs new file mode 100644 index 0000000000000000000000000000000000000000..df53d64683658ec10df29bf15b22f34c2d6c4608 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/esm.mjs @@ -0,0 +1,12 @@ +import { test } from 'tap' +import boot from '../boot.js' + +test('support import', async (t) => { + const app = boot() + + app.use(import('./fixtures/esm.mjs')) + + await app.ready() + + t.equal(app.loaded, true) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/esm.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/esm.test.js new file mode 100644 index 0000000000000000000000000000000000000000..d930881ea070ec7830f28efee73f308ceab8b7b4 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/esm.test.js @@ -0,0 +1,14 @@ +'use strict' + +const { test } = require('tap') + +test('support esm import', (t) => { + import('./esm.mjs').then(() => { + t.pass('esm is supported') + t.end() + }).catch((err) => { + process.nextTick(() => { + throw err + }) + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/events-listeners.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/events-listeners.test.js new file mode 100644 index 0000000000000000000000000000000000000000..810d43b59c8fe9fb9621743241fc1241363d34dd --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/events-listeners.test.js @@ -0,0 +1,23 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') +const noop = () => {} + +test('boot a plugin and then execute a call after that', (t) => { + t.plan(1) + + process.on('warning', (warning) => { + t.fail('we should not get a warning', warning) + }) + + const app = boot() + // eslint-disable-next-line no-var + for (var i = 0; i < 12; i++) { + app.on('preReady', noop) + } + + setTimeout(() => { + t.pass('Everything ok') + }, 500) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/expose.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/expose.test.js new file mode 100644 index 0000000000000000000000000000000000000000..422524e5e2ced2489c0cd9903bb809e2fa8eca77 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/expose.test.js @@ -0,0 +1,80 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') +const { AVV_ERR_EXPOSE_ALREADY_DEFINED, AVV_ERR_ATTRIBUTE_ALREADY_DEFINED } = require('../lib/errors') +const { kAvvio } = require('../lib/symbols') + +for (const key of ['use', 'after', 'ready', 'onClose', 'close']) { + test('throws if ' + key + ' is by default already there', (t) => { + t.plan(1) + + const app = {} + app[key] = () => { } + + t.throws(() => boot(app), new AVV_ERR_EXPOSE_ALREADY_DEFINED(key, key)) + }) + + test('throws if ' + key + ' is already there', (t) => { + t.plan(1) + + const app = {} + app['cust' + key] = () => { } + + t.throws(() => boot(app, { expose: { [key]: 'cust' + key } }), new AVV_ERR_EXPOSE_ALREADY_DEFINED('cust' + key, key)) + }) + + test('support expose for ' + key, (t) => { + const app = {} + app[key] = () => { } + + const expose = {} + expose[key] = 'muahah' + + boot(app, { + expose + }) + + t.end() + }) +} + +test('set the kAvvio to true on the server', (t) => { + t.plan(1) + + const server = {} + boot(server) + + t.ok(server[kAvvio]) +}) + +test('.then()', t => { + t.plan(3) + + t.test('.then() can not be overwritten', (t) => { + t.plan(1) + + const server = { + then: () => {} + } + t.throws(() => boot(server), AVV_ERR_ATTRIBUTE_ALREADY_DEFINED('then')) + }) + + t.test('.then() is a function', (t) => { + t.plan(1) + + const server = {} + boot(server) + + t.type(server.then, 'function') + }) + + t.test('.then() can not be overwritten', (t) => { + t.plan(1) + + const server = {} + boot(server) + + t.throws(() => { server.then = 'invalid' }, TypeError('Cannot set property then of # which has only a getter')) + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/fixtures/dummy.txt b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/fixtures/dummy.txt new file mode 100644 index 0000000000000000000000000000000000000000..30f51a3fba5274d53522d0f19748456974647b4f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/fixtures/dummy.txt @@ -0,0 +1 @@ +hello, world! \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/fixtures/esm.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/fixtures/esm.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ae3574db370a4ff4c105641c7b94172cc153a2ea --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/fixtures/esm.mjs @@ -0,0 +1,3 @@ +export default async function (app) { + app.loaded = true +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/fixtures/plugin-no-next.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/fixtures/plugin-no-next.js new file mode 100644 index 0000000000000000000000000000000000000000..cc19b0652658499ffa659889f482d677c9739b9f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/fixtures/plugin-no-next.js @@ -0,0 +1,5 @@ +'use strict' + +module.exports = function noNext (app, opts, next) { + // no call to next +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/gh-issues/bug-205.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/gh-issues/bug-205.test.js new file mode 100644 index 0000000000000000000000000000000000000000..1dbd4dfb128c228f3cc7145c15c8e7c2db14a7dc --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/gh-issues/bug-205.test.js @@ -0,0 +1,16 @@ +'use strict' + +const { test } = require('tap') +const boot = require('../..') + +test('should print the time tree', (t) => { + t.plan(2) + const app = boot() + + app.use(function first (instance, opts, cb) { + const out = instance.prettyPrint().split('\n') + t.equal(out[0], 'root -1 ms') + t.equal(out[1], '└── first -1 ms') + cb() + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/lib/create-promise.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/lib/create-promise.test.js new file mode 100644 index 0000000000000000000000000000000000000000..99ed5c69887f61955c78b9236029f2bc11a277d7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/lib/create-promise.test.js @@ -0,0 +1,55 @@ +'use strict' + +const { test } = require('tap') +const { createPromise } = require('../../lib/create-promise') + +test('createPromise() returns an object', (t) => { + t.plan(3) + t.type(createPromise(), 'object') + t.equal(Array.isArray(createPromise()), false) + t.notOk(Array.isArray(createPromise() !== null)) +}) + +test('createPromise() returns an attribute with attribute resolve', (t) => { + t.plan(1) + t.ok('resolve' in createPromise()) +}) + +test('createPromise() returns an attribute with attribute reject', (t) => { + t.plan(1) + t.ok('reject' in createPromise()) +}) + +test('createPromise() returns an attribute with attribute createPromise', (t) => { + t.plan(1) + t.ok('promise' in createPromise()) +}) + +test('when resolve is called, createPromise attribute is resolved', (t) => { + t.plan(1) + const p = createPromise() + + p.promise + .then(() => { + t.pass() + }) + .catch(() => { + t.fail() + }) + p.resolve() +}) + +test('when reject is called, createPromise attribute is rejected', (t) => { + t.plan(1) + const p = createPromise() + + p.promise + .then(() => { + t.fail() + }) + .catch(() => { + t.pass() + }) + + p.reject() +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/lib/execute-with-thenable.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/lib/execute-with-thenable.test.js new file mode 100644 index 0000000000000000000000000000000000000000..f51ac4ec22f3755c850bbf627ae3ecafa3c76e7d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/lib/execute-with-thenable.test.js @@ -0,0 +1,82 @@ +'use strict' + +const { test } = require('tap') +const { executeWithThenable } = require('../../lib/execute-with-thenable') +const { kAvvio } = require('../../lib/symbols') + +test('executeWithThenable', (t) => { + t.plan(6) + + t.test('passes the arguments to the function', (t) => { + t.plan(5) + + executeWithThenable((...args) => { + t.equal(args.length, 3) + t.equal(args[0], 1) + t.equal(args[1], 2) + t.equal(args[2], 3) + }, [1, 2, 3], (err) => { + t.error(err) + }) + }) + + t.test('function references this to itself', (t) => { + t.plan(2) + + const func = function () { + t.equal(this, func) + } + executeWithThenable(func, [], (err) => { + t.error(err) + }) + }) + + t.test('handle resolving Promise of func', (t) => { + t.plan(1) + + const fn = function () { + return Promise.resolve(42) + } + + executeWithThenable(fn, [], (err) => { + t.error(err) + }) + }) + + t.test('handle rejecting Promise of func', (t) => { + t.plan(1) + + const fn = function () { + return Promise.reject(new Error('Arbitrary Error')) + } + + executeWithThenable(fn, [], (err) => { + t.equal(err.message, 'Arbitrary Error') + }) + }) + + t.test('dont handle avvio mocks PromiseLike results but use callback if provided', (t) => { + t.plan(1) + + const fn = function () { + const result = Promise.resolve(42) + result[kAvvio] = true + } + + executeWithThenable(fn, [], (err) => { + t.error(err) + }) + }) + + t.test('dont handle avvio mocks Promises and if no callback is provided', (t) => { + t.plan(1) + + const fn = function () { + t.pass(1) + const result = Promise.resolve(42) + result[kAvvio] = true + } + + executeWithThenable(fn, []) + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/lib/get-plugin-name.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/lib/get-plugin-name.test.js new file mode 100644 index 0000000000000000000000000000000000000000..2cb385397c9e35c44f3d67daf2ae613152561495 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/lib/get-plugin-name.test.js @@ -0,0 +1,67 @@ +'use strict' + +const { test } = require('tap') +const { getPluginName } = require('../../lib/get-plugin-name') +const { kPluginMeta } = require('../../lib/symbols') + +test('getPluginName of function', (t) => { + t.plan(1) + + t.equal(getPluginName(function aPlugin () { }), 'aPlugin') +}) + +test('getPluginName of async function', (t) => { + t.plan(1) + + t.equal(getPluginName(async function aPlugin () { }), 'aPlugin') +}) + +test('getPluginName of arrow function without name', (t) => { + t.plan(2) + + t.equal(getPluginName(() => { }), '() => { }') + t.equal(getPluginName(() => { return 'random' }), '() => { return \'random\' }') +}) + +test('getPluginName of arrow function assigned to variable', (t) => { + t.plan(1) + + const namedArrowFunction = () => { } + t.equal(getPluginName(namedArrowFunction), 'namedArrowFunction') +}) + +test("getPluginName based on Symbol 'plugin-meta' /1", (t) => { + t.plan(1) + + function plugin () { + + } + + plugin[kPluginMeta] = {} + t.equal(getPluginName(plugin), 'plugin') +}) + +test("getPluginName based on Symbol 'plugin-meta' /2", (t) => { + t.plan(1) + + function plugin () { + + } + + plugin[kPluginMeta] = { + name: 'fastify-non-existent' + } + t.equal(getPluginName(plugin), 'fastify-non-existent') +}) + +test('getPluginName if null is provided as options', (t) => { + t.plan(1) + + t.equal(getPluginName(function a () {}, null), 'a') +}) + +test('getPluginName if name is provided in options', (t) => { + t.plan(1) + + t.equal(getPluginName(function defaultName () {}, { name: 'providedName' }), 'providedName') +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/lib/is-bundled-or-typescript-plugin.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/lib/is-bundled-or-typescript-plugin.test.js new file mode 100644 index 0000000000000000000000000000000000000000..b81029b714686af47469dab3ca1100448543992f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/lib/is-bundled-or-typescript-plugin.test.js @@ -0,0 +1,20 @@ +'use strict' + +const { test } = require('tap') +const { isBundledOrTypescriptPlugin } = require('../../lib/is-bundled-or-typescript-plugin') + +test('isBundledOrTypescriptPlugin', (t) => { + t.plan(9) + + t.equal(isBundledOrTypescriptPlugin(1), false) + t.equal(isBundledOrTypescriptPlugin('function'), false) + t.equal(isBundledOrTypescriptPlugin({}), false) + t.equal(isBundledOrTypescriptPlugin([]), false) + t.equal(isBundledOrTypescriptPlugin(null), false) + + t.equal(isBundledOrTypescriptPlugin(function () {}), false) + t.equal(isBundledOrTypescriptPlugin(new Promise((resolve) => resolve)), false) + t.equal(isBundledOrTypescriptPlugin(Promise.resolve()), false) + + t.equal(isBundledOrTypescriptPlugin({ default: () => {} }), true) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/lib/is-promise-like.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/lib/is-promise-like.test.js new file mode 100644 index 0000000000000000000000000000000000000000..f1407661f3447d386054332ed4105ccc4a506250 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/lib/is-promise-like.test.js @@ -0,0 +1,20 @@ +'use strict' + +const { test } = require('tap') +const { isPromiseLike } = require('../../lib/is-promise-like') + +test('isPromiseLike', (t) => { + t.plan(9) + + t.equal(isPromiseLike(1), false) + t.equal(isPromiseLike('function'), false) + t.equal(isPromiseLike({}), false) + t.equal(isPromiseLike([]), false) + t.equal(isPromiseLike(null), false) + + t.equal(isPromiseLike(function () {}), false) + t.equal(isPromiseLike(new Promise((resolve) => resolve)), true) + t.equal(isPromiseLike(Promise.resolve()), true) + + t.equal(isPromiseLike({ then: () => {} }), true) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/lib/thenify.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/lib/thenify.test.js new file mode 100644 index 0000000000000000000000000000000000000000..2004a0a40f3ce8c5208d824daaea95a02dd3f450 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/lib/thenify.test.js @@ -0,0 +1,123 @@ +'use strict' + +const { test, mockRequire } = require('tap') +const { kThenifyDoNotWrap } = require('../../lib/symbols') + +test('thenify', (t) => { + t.plan(7) + + t.test('return undefined if booted', (t) => { + t.plan(2) + + const { thenify } = mockRequire('../../lib/thenify', { + '../../lib/debug': { + debug: (message) => { t.equal(message, 'thenify returning undefined because we are already booted') } + } + }) + const result = thenify.call({ + booted: true + }) + t.equal(result, undefined) + }) + + t.test('return undefined if kThenifyDoNotWrap is true', (t) => { + t.plan(1) + + const { thenify } = require('../../lib/thenify') + const result = thenify.call({ + [kThenifyDoNotWrap]: true + }) + t.equal(result, undefined) + }) + + t.test('return PromiseConstructorLike if kThenifyDoNotWrap is false', (t) => { + t.plan(3) + + const { thenify } = mockRequire('../../lib/thenify', { + '../../lib/debug': { + debug: (message) => { t.equal(message, 'thenify') } + } + }) + const promiseContructorLike = thenify.call({ + [kThenifyDoNotWrap]: false + }) + + t.type(promiseContructorLike, 'function') + t.equal(promiseContructorLike.length, 2) + }) + + t.test('return PromiseConstructorLike', (t) => { + t.plan(3) + + const { thenify } = mockRequire('../../lib/thenify', { + '../../lib/debug': { + debug: (message) => { t.equal(message, 'thenify') } + } + }) + const promiseContructorLike = thenify.call({}) + + t.type(promiseContructorLike, 'function') + t.equal(promiseContructorLike.length, 2) + }) + + t.test('resolve should return _server', async (t) => { + t.plan(1) + + const { thenify } = require('../../lib/thenify') + + const server = { + _loadRegistered: () => { + return Promise.resolve() + }, + _server: 'server' + } + const promiseContructorLike = thenify.call(server) + + promiseContructorLike(function (value) { + t.equal(value, 'server') + }, function (reason) { + t.error(reason) + }) + }) + + t.test('resolving should set kThenifyDoNotWrap to true', async (t) => { + t.plan(1) + + const { thenify } = require('../../lib/thenify') + + const server = { + _loadRegistered: () => { + return Promise.resolve() + }, + [kThenifyDoNotWrap]: false, + _server: 'server' + } + const promiseContructorLike = thenify.call(server) + + promiseContructorLike(function (value) { + t.equal(server[kThenifyDoNotWrap], true) + }, function (reason) { + t.error(reason) + }) + }) + + t.test('rejection should pass through to reject', async (t) => { + t.plan(1) + + const { thenify } = require('../../lib/thenify') + + const server = { + _loadRegistered: () => { + return Promise.reject(new Error('Arbitrary rejection')) + }, + _server: 'server' + } + const promiseContructorLike = thenify.call(server) + + promiseContructorLike(function (value) { + t.error(value) + }, function (reason) { + t.equal(reason.message, 'Arbitrary rejection') + }) + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/lib/time-tree.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/lib/time-tree.test.js new file mode 100644 index 0000000000000000000000000000000000000000..8bef526c263e97af12d9d36fc488c077bdc26165 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/lib/time-tree.test.js @@ -0,0 +1,391 @@ +'use strict' + +const { test } = require('tap') +const { TimeTree } = require('../../lib/time-tree') + +test('TimeTree is constructed with a root attribute, set to null', t => { + t.plan(1) + + const tree = new TimeTree() + t.equal(tree.root, null) +}) + +test('TimeTree is constructed with an empty tableId-Map', t => { + t.plan(2) + + const tree = new TimeTree() + t.ok(tree.tableId instanceof Map) + t.equal(tree.tableId.size, 0) +}) + +test('TimeTree is constructed with an empty tableLabel-Map', t => { + t.plan(2) + + const tree = new TimeTree() + t.ok(tree.tableLabel instanceof Map) + t.equal(tree.tableLabel.size, 0) +}) + +test('TimeTree#toJSON dumps the content of the TimeTree', t => { + t.plan(1) + + const tree = new TimeTree() + t.same(tree.toJSON(), {}) +}) + +test('TimeTree#toJSON is creating new instances of its content, ensuring being immutable', t => { + t.plan(1) + + const tree = new TimeTree() + t.not(tree.toJSON(), tree.toJSON()) +}) + +test('TimeTree#start is adding a node with correct shape, root-node', t => { + t.plan(15) + + const tree = new TimeTree() + tree.start(null, 'root') + + const rootNode = tree.root + + t.equal(Object.keys(rootNode).length, 7) + t.ok('parent' in rootNode) + t.equal(rootNode.parent, null) + t.ok('id' in rootNode) + t.type(rootNode.id, 'string') + t.ok('label' in rootNode) + t.type(rootNode.label, 'string') + t.ok('nodes' in rootNode) + t.ok(Array.isArray(rootNode.nodes)) + t.ok('start' in rootNode) + t.ok(Number.isInteger(rootNode.start)) + t.ok('stop' in rootNode) + t.type(rootNode.stop, 'null') + t.ok('diff' in rootNode) + t.type(rootNode.diff, 'number') +}) + +test('TimeTree#start is adding a node with correct shape, child-node', t => { + t.plan(16) + + const tree = new TimeTree() + tree.start(null, 'root') + tree.start('root', 'child') + + const rootNode = tree.root + + t.equal(rootNode.nodes.length, 1) + + const childNode = rootNode.nodes[0] + + t.equal(Object.keys(childNode).length, 7) + t.ok('parent' in childNode) + t.type(childNode.parent, 'string') + t.ok('id' in childNode) + t.type(childNode.id, 'string') + t.ok('label' in childNode) + t.type(childNode.label, 'string') + t.ok('nodes' in childNode) + t.ok(Array.isArray(childNode.nodes)) + t.ok('start' in childNode) + t.ok(Number.isInteger(childNode.start)) + t.ok('stop' in childNode) + t.type(childNode.stop, 'null') + t.ok('diff' in childNode) + t.type(childNode.diff, 'number') +}) + +test('TimeTree#start is adding a root element when parent is null', t => { + t.plan(9) + + const tree = new TimeTree() + tree.start(null, 'root') + + const rootNode = tree.root + + t.type(rootNode, 'object') + t.equal(Object.keys(rootNode).length, 7) + t.equal(rootNode.parent, null) + t.equal(rootNode.id, 'root') + t.equal(rootNode.label, 'root') + t.ok(Array.isArray(rootNode.nodes)) + t.equal(rootNode.nodes.length, 0) + t.ok(Number.isInteger(rootNode.start)) + t.type(rootNode.diff, 'number') +}) + +test('TimeTree#start is adding a root element when parent does not exist', t => { + t.plan(9) + + const tree = new TimeTree() + tree.start('invalid', 'root') + + const rootNode = tree.root + + t.type(rootNode, 'object') + t.equal(Object.keys(rootNode).length, 7) + t.equal(rootNode.parent, null) + t.equal(rootNode.id, 'root') + t.equal(rootNode.label, 'root') + t.ok(Array.isArray(rootNode.nodes)) + t.equal(rootNode.nodes.length, 0) + t.ok(Number.isInteger(rootNode.start)) + t.type(rootNode.diff, 'number') +}) + +test('TimeTree#start parameter start can override automatically generated start time', t => { + t.plan(1) + + const tree = new TimeTree() + tree.start(null, 'root', 1337) + + t.ok(tree.root.start, 1337) +}) + +test('TimeTree#start returns id of root, when adding a root node /1', t => { + t.plan(1) + + const tree = new TimeTree() + t.equal(tree.start(null, 'root'), 'root') +}) + +test('TimeTree#start returns id of root, when adding a root node /2', t => { + t.plan(1) + + const tree = new TimeTree() + t.equal(tree.start(null, '/'), 'root') +}) + +test('TimeTree#start returns id of child, when adding a child node', t => { + t.plan(1) + + const tree = new TimeTree() + tree.start(null, 'root') + t.match(tree.start('root', 'child'), /^child-[0-9.]+$/) +}) + +test('TimeTree tracks node ids /1', t => { + t.plan(3) + + const tree = new TimeTree() + tree.start(null, 'root') + tree.start('root', 'child') + + t.equal(tree.tableId.size, 2) + t.ok(tree.tableId.has('root')) + t.ok(tree.tableId.has(tree.root.nodes[0].id)) +}) + +test('TimeTree tracks node ids /2', t => { + t.plan(4) + + const tree = new TimeTree() + tree.start(null, 'root') + tree.start('root', 'child') + tree.start('child', 'grandchild') + + t.equal(tree.tableId.size, 3) + t.ok(tree.tableId.has('root')) + t.ok(tree.tableId.has(tree.root.nodes[0].id)) + t.ok(tree.tableId.has(tree.root.nodes[0].nodes[0].id)) +}) + +test('TimeTree tracks node ids /3', t => { + t.plan(4) + + const tree = new TimeTree() + tree.start(null, 'root') + tree.start('root', 'child') + tree.start('root', 'child') + + t.equal(tree.tableId.size, 3) + t.ok(tree.tableId.has('root')) + t.ok(tree.tableId.has(tree.root.nodes[0].id)) + t.ok(tree.tableId.has(tree.root.nodes[1].id)) +}) + +test('TimeTree tracks node labels /1', t => { + t.plan(4) + + const tree = new TimeTree() + tree.start(null, 'root') + tree.start('root', 'child') + tree.start('root', 'sibling') + + t.equal(tree.tableLabel.size, 3) + t.ok(tree.tableLabel.has('root')) + t.ok(tree.tableLabel.has('child')) + t.ok(tree.tableLabel.has('sibling')) +}) + +test('TimeTree tracks node labels /2', t => { + t.plan(3) + + const tree = new TimeTree() + tree.start(null, 'root') + tree.start('root', 'child') + tree.start('root', 'child') + + t.equal(tree.tableLabel.size, 2) + t.ok(tree.tableLabel.has('root')) + t.ok(tree.tableLabel.has('child')) +}) + +test('TimeTree#stop returns undefined', t => { + t.plan(1) + + const tree = new TimeTree() + tree.start(null, 'root') + + t.type(tree.stop('root'), 'undefined') +}) + +test('TimeTree#stop sets stop value of node', t => { + t.plan(3) + + const tree = new TimeTree() + tree.start(null, 'root') + t.type(tree.root.stop, 'null') + + tree.stop('root') + t.type(tree.root.stop, 'number') + t.ok(Number.isInteger(tree.root.stop)) +}) + +test('TimeTree#stop parameter stop is used as stop value of node', t => { + t.plan(3) + + const tree = new TimeTree() + tree.start(null, 'root') + t.type(tree.root.stop, 'null') + + tree.stop('root', 1337) + t.type(tree.root.stop, 'number') + t.equal(tree.root.stop, 1337) +}) + +test('TimeTree#stop calculates the diff', t => { + t.plan(4) + + const tree = new TimeTree() + tree.start(null, 'root', 1) + t.type(tree.root.diff, 'number') + t.equal(tree.root.diff, -1) + tree.stop('root', 5) + + t.type(tree.root.diff, 'number') + t.equal(tree.root.diff, 4) +}) + +test('TimeTree#stop does nothing when node is not found', t => { + t.plan(2) + + const tree = new TimeTree() + tree.start(null, 'root') + t.type(tree.root.stop, 'null') + + tree.stop('invalid') + t.type(tree.root.stop, 'null') +}) + +test('TimeTree untracks node ids /1', t => { + t.plan(2) + + const tree = new TimeTree() + tree.start(null, 'root') + tree.start('root', 'child') + + tree.stop(tree.root.nodes[0].id) + t.equal(tree.tableId.size, 1) + t.ok(tree.tableId.has('root')) +}) + +test('TimeTree untracks node ids /2', t => { + t.plan(3) + + const tree = new TimeTree() + tree.start(null, 'root') + tree.start('root', 'child') + tree.start('child', 'grandchild') + + tree.stop(tree.root.nodes[0].nodes[0].id) + + t.equal(tree.tableId.size, 2) + t.ok(tree.tableId.has('root')) + t.ok(tree.tableId.has(tree.root.nodes[0].id)) +}) + +test('TimeTree untracks node ids /3', t => { + t.plan(3) + + const tree = new TimeTree() + tree.start(null, 'root') + tree.start('root', 'child') + tree.start('root', 'child') + + tree.stop(tree.root.nodes[0].id) + + t.equal(tree.tableId.size, 2) + t.ok(tree.tableId.has('root')) + t.ok(tree.tableId.has(tree.root.nodes[1].id)) +}) + +test('TimeTree untracks node ids /4', t => { + t.plan(3) + + const tree = new TimeTree() + tree.start(null, 'root') + tree.start('root', 'child') + tree.start('root', 'child') + + tree.stop(tree.root.nodes[1].id) + + t.equal(tree.tableId.size, 2) + t.ok(tree.tableId.has('root')) + t.ok(tree.tableId.has(tree.root.nodes[0].id)) +}) + +test('TimeTree untracks node labels /1', t => { + t.plan(3) + + const tree = new TimeTree() + tree.start(null, 'root') + tree.start('root', 'child') + tree.start('root', 'sibling') + + tree.stop(tree.root.nodes[1].id) + + t.equal(tree.tableLabel.size, 2) + t.ok(tree.tableLabel.has('root')) + t.ok(tree.tableLabel.has('child')) +}) + +test('TimeTree untracks node labels /2', t => { + t.plan(3) + + const tree = new TimeTree() + tree.start(null, 'root') + tree.start('root', 'child') + tree.start('root', 'sibling') + + tree.stop(tree.root.nodes[0].id) + + t.equal(tree.tableLabel.size, 2) + t.ok(tree.tableLabel.has('root')) + t.ok(tree.tableLabel.has('sibling')) +}) + +test('TimeTree does not untrack label if used by other node', t => { + t.plan(3) + + const tree = new TimeTree() + tree.start(null, 'root') + tree.start('root', 'child') + tree.start('root', 'child') + + tree.stop(tree.root.nodes[0].id) + + t.equal(tree.tableLabel.size, 2) + t.ok(tree.tableLabel.has('root')) + t.ok(tree.tableLabel.has('child')) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/lib/validate-plugin.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/lib/validate-plugin.test.js new file mode 100644 index 0000000000000000000000000000000000000000..a3aa956ec0be48cd294b0fa9f99ea906028be412 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/lib/validate-plugin.test.js @@ -0,0 +1,19 @@ +'use strict' + +const { test } = require('tap') +const { validatePlugin } = require('../../lib/validate-plugin') +const { AVV_ERR_PLUGIN_NOT_VALID } = require('../../lib/errors') + +test('validatePlugin', (t) => { + t.plan(8) + + t.throws(() => validatePlugin(1), new AVV_ERR_PLUGIN_NOT_VALID('number')) + t.throws(() => validatePlugin('function'), new AVV_ERR_PLUGIN_NOT_VALID('string')) + t.throws(() => validatePlugin({}), new AVV_ERR_PLUGIN_NOT_VALID('object')) + t.throws(() => validatePlugin([]), new AVV_ERR_PLUGIN_NOT_VALID('array')) + t.throws(() => validatePlugin(null), new AVV_ERR_PLUGIN_NOT_VALID('null')) + + t.doesNotThrow(() => validatePlugin(function () {})) + t.doesNotThrow(() => validatePlugin(new Promise((resolve) => resolve))) + t.doesNotThrow(() => validatePlugin(Promise.resolve())) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/load-plugin.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/load-plugin.test.js new file mode 100644 index 0000000000000000000000000000000000000000..e1400edf5da8e8becacecce95fcf678274404753 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/load-plugin.test.js @@ -0,0 +1,123 @@ +'use strict' + +const fastq = require('fastq') +const boot = require('..') +const { test } = require('tap') +const { Plugin } = require('../lib/plugin') + +test('successfully load a plugin with sync function', (t) => { + t.plan(1) + const app = boot({}) + + const plugin = new Plugin(fastq(app, app._loadPluginNextTick, 1), function (instance, opts, done) { + done() + }, false, 0) + + app._loadPlugin(plugin, function (err) { + t.equal(err, undefined) + }) +}) + +test('catch an error when loading a plugin with sync function', (t) => { + t.plan(1) + const app = boot({}) + + const plugin = new Plugin(fastq(app, app._loadPluginNextTick, 1), function (instance, opts, done) { + done(Error('ArbitraryError')) + }, false, 0) + + app._loadPlugin(plugin, function (err) { + t.equal(err.message, 'ArbitraryError') + }) +}) + +test('successfully load a plugin with sync function without done as a parameter', (t) => { + t.plan(1) + const app = boot({}) + + const plugin = new Plugin(fastq(app, app._loadPluginNextTick, 1), function (instance, opts) { }, false, 0) + + app._loadPlugin(plugin, function (err) { + t.equal(err, undefined) + }) +}) + +test('successfully load a plugin with async function', (t) => { + t.plan(1) + const app = boot({}) + + const plugin = new Plugin(fastq(app, app._loadPluginNextTick, 1), async function (instance, opts) { }, false, 0) + + app._loadPlugin(plugin, function (err) { + t.equal(err, undefined) + }) +}) + +test('catch an error when loading a plugin with async function', (t) => { + t.plan(1) + const app = boot({}) + + const plugin = new Plugin(fastq(app, app._loadPluginNextTick, 1), async function (instance, opts) { + throw Error('ArbitraryError') + }, false, 0) + + app._loadPlugin(plugin, function (err) { + t.equal(err.message, 'ArbitraryError') + }) +}) + +test('successfully load a plugin when function is a Promise, which resolves to a function', (t) => { + t.plan(1) + const app = boot({}) + + const plugin = new Plugin(fastq(app, app._loadPluginNextTick, 1), new Promise(resolve => resolve(function (instance, opts, done) { + done() + })), false, 0) + + app._loadPlugin(plugin, function (err) { + t.equal(err, undefined) + }) +}) + +test('catch an error when loading a plugin when function is a Promise, which resolves to a function', (t) => { + t.plan(1) + const app = boot({}) + + const plugin = new Plugin(fastq(app, app._loadPluginNextTick, 1), new Promise(resolve => resolve(function (instance, opts, done) { + done(Error('ArbitraryError')) + })), false, 0) + + app._loadPlugin(plugin, function (err) { + t.equal(err.message, 'ArbitraryError') + }) +}) + +test('successfully load a plugin when function is a Promise, which resolves to a function, which is wrapped in default', (t) => { + t.plan(1) + const app = boot({}) + + const plugin = new Plugin(fastq(app, app._loadPluginNextTick, 1), new Promise(resolve => resolve({ + default: function (instance, opts, done) { + done() + } + })), false, 0) + + app._loadPlugin(plugin, function (err) { + t.equal(err, undefined) + }) +}) + +test('catch an error when loading a plugin when function is a Promise, which resolves to a function, which is wrapped in default', (t) => { + t.plan(1) + const app = boot({}) + + const plugin = new Plugin(fastq(app, app._loadPluginNextTick, 1), new Promise(resolve => resolve({ + default: function (instance, opts, done) { + done(Error('ArbitraryError')) + } + })), false, 0) + + app._loadPlugin(plugin, function (err) { + t.equal(err.message, 'ArbitraryError') + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/no-done.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/no-done.test.js new file mode 100644 index 0000000000000000000000000000000000000000..0270545d54e90906789d0150b42db6fc699af6c4 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/no-done.test.js @@ -0,0 +1,18 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') + +test('not taking done does not throw error.', (t) => { + t.plan(2) + + const app = boot() + + app.use(noDone).ready((err) => { + t.notOk(err, 'no error') + }) + + function noDone (s, opts) { + t.pass('did not throw') + } +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/on-ready-timeout-await.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/on-ready-timeout-await.test.js new file mode 100644 index 0000000000000000000000000000000000000000..9593935aa40a05d9f0b7d63820308e07e67975cf --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/on-ready-timeout-await.test.js @@ -0,0 +1,33 @@ +'use strict' + +/* eslint no-prototype-builtins: off */ + +const { test } = require('tap') +const boot = require('../boot') + +test('onReadyTimeout', async (t) => { + const app = boot({}, { + timeout: 10, // 10 ms + autostart: false + }) + + app.use(function one (innerApp, opts, next) { + t.pass('loaded') + innerApp.ready(function readyNoResolve (err, done) { + t.notOk(err) + t.pass('first ready called') + // Do not call done() to timeout + }) + next() + }) + + await app.start() + + try { + await app.ready() + t.fail('should throw') + } catch (err) { + t.equal(err.message, 'Plugin did not start in time: \'readyNoResolve\'. You may have forgotten to call \'done\' function or to resolve a Promise') + // And not Plugin did not start in time: 'bound _encapsulateThreeParam'. You may have forgotten to call 'done' function or to resolve a Promise + } +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/override.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/override.test.js new file mode 100644 index 0000000000000000000000000000000000000000..674daaa7d0dc1e0afa137f73286d3f79f6020f7e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/override.test.js @@ -0,0 +1,374 @@ +'use strict' + +/* eslint no-prototype-builtins: off */ + +const { test } = require('tap') +const boot = require('..') + +test('custom inheritance', (t) => { + t.plan(3) + + const server = { my: 'server' } + const app = boot(server) + + app.override = function (s) { + t.equal(s, server) + + const res = Object.create(s) + res.b = 42 + + return res + } + + app.use(function first (s, opts, cb) { + t.not(s, server) + t.ok(Object.prototype.isPrototypeOf.call(server, s)) + cb() + }) +}) + +test('custom inheritance multiple levels', (t) => { + t.plan(6) + + const server = { count: 0 } + const app = boot(server) + + app.override = function (s) { + const res = Object.create(s) + res.count = res.count + 1 + + return res + } + + app.use(function first (s1, opts, cb) { + t.not(s1, server) + t.ok(Object.prototype.isPrototypeOf.call(server, s1)) + t.equal(s1.count, 1) + s1.use(second) + + cb() + + function second (s2, opts, cb) { + t.not(s2, s1) + t.ok(Object.prototype.isPrototypeOf.call(s1, s2)) + t.equal(s2.count, 2) + cb() + } + }) +}) + +test('custom inheritance multiple levels twice', (t) => { + t.plan(10) + + const server = { count: 0 } + const app = boot(server) + + app.override = function (s) { + const res = Object.create(s) + res.count = res.count + 1 + + return res + } + + app.use(function first (s1, opts, cb) { + t.not(s1, server) + t.ok(Object.prototype.isPrototypeOf.call(server, s1)) + t.equal(s1.count, 1) + s1.use(second) + s1.use(third) + let prev + + cb() + + function second (s2, opts, cb) { + prev = s2 + t.not(s2, s1) + t.ok(Object.prototype.isPrototypeOf.call(s1, s2)) + t.equal(s2.count, 2) + cb() + } + + function third (s3, opts, cb) { + t.not(s3, s1) + t.ok(Object.prototype.isPrototypeOf.call(s1, s3)) + t.notOk(Object.prototype.isPrototypeOf.call(prev, s3)) + t.equal(s3.count, 2) + cb() + } + }) +}) + +test('custom inheritance multiple levels with multiple heads', (t) => { + t.plan(13) + + const server = { count: 0 } + const app = boot(server) + + app.override = function (s) { + const res = Object.create(s) + res.count = res.count + 1 + + return res + } + + app.use(function first (s1, opts, cb) { + t.not(s1, server) + t.ok(Object.prototype.isPrototypeOf.call(server, s1)) + t.equal(s1.count, 1) + s1.use(second) + + cb() + + function second (s2, opts, cb) { + t.not(s2, s1) + t.ok(Object.prototype.isPrototypeOf.call(s1, s2)) + t.equal(s2.count, 2) + cb() + } + }) + + app.use(function third (s1, opts, cb) { + t.not(s1, server) + t.ok(Object.prototype.isPrototypeOf.call(server, s1)) + t.equal(s1.count, 1) + s1.use(fourth) + + cb() + + function fourth (s2, opts, cb) { + t.not(s2, s1) + t.ok(Object.prototype.isPrototypeOf.call(s1, s2)) + t.equal(s2.count, 2) + cb() + } + }) + + app.ready(function () { + t.equal(server.count, 0) + }) +}) + +test('fastify test case', (t) => { + t.plan(7) + + const noop = () => {} + + function build () { + const app = boot(server, {}) + app.override = function (s) { + return Object.create(s) + } + + server.add = function (name, fn, cb) { + if (this[name]) return cb(new Error('already existent')) + this[name] = fn + cb() + } + + return server + + function server (req, res) {} + } + + const instance = build() + t.ok(instance.add) + t.ok(instance.use) + + instance.use((i, opts, cb) => { + t.not(i, instance) + t.ok(Object.prototype.isPrototypeOf.call(instance, i)) + + i.add('test', noop, (err) => { + t.error(err) + t.ok(i.test) + cb() + }) + }) + + instance.ready(() => { + t.notOk(instance.test) + }) +}) + +test('override should pass also the plugin function', (t) => { + t.plan(3) + + const server = { my: 'server' } + const app = boot(server) + + app.override = function (s, fn) { + t.type(fn, 'function') + t.equal(fn, first) + return s + } + + app.use(first) + + function first (s, opts, cb) { + t.equal(s, server) + cb() + } +}) + +test('skip override - fastify test case', (t) => { + t.plan(2) + + const server = { my: 'server' } + const app = boot(server) + + app.override = function (s, func) { + if (func[Symbol.for('skip-override')]) { + return s + } + return Object.create(s) + } + + first[Symbol.for('skip-override')] = true + app.use(first) + + function first (s, opts, cb) { + t.equal(s, server) + t.notOk(Object.prototype.isPrototypeOf.call(server, s)) + cb() + } +}) + +test('override can receive options object', (t) => { + t.plan(4) + + const server = { my: 'server' } + const options = { hello: 'world' } + const app = boot(server) + + app.override = function (s, fn, opts) { + t.equal(s, server) + t.same(opts, options) + + const res = Object.create(s) + res.b = 42 + + return res + } + + app.use(function first (s, opts, cb) { + t.not(s, server) + t.ok(Object.prototype.isPrototypeOf.call(server, s)) + cb() + }, options) +}) + +test('override can receive options function', (t) => { + t.plan(8) + + const server = { my: 'server' } + const options = { hello: 'world' } + const app = boot(server) + + app.override = function (s, fn, opts) { + t.equal(s, server) + if (typeof opts !== 'function') { + t.same(opts, options) + } + + const res = Object.create(s) + res.b = 42 + res.bar = 'world' + + return res + } + + app.use(function first (s, opts, cb) { + t.not(s, server) + t.ok(Object.prototype.isPrototypeOf.call(server, s)) + s.foo = 'bar' + cb() + }, options) + + app.use(function second (s, opts, cb) { + t.notOk(s.foo) + t.same(opts, { hello: 'world' }) + t.ok(Object.prototype.isPrototypeOf.call(server, s)) + cb() + }, p => ({ hello: p.bar })) +}) + +test('after trigger override', t => { + t.plan(8) + + const server = { count: 0 } + const app = boot(server) + + let overrideCalls = 0 + app.override = function (s, fn, opts) { + overrideCalls++ + const res = Object.create(s) + res.count = res.count + 1 + return res + } + + app + .use(function first (s, opts, cb) { + t.equal(s.count, 1, 'should trigger override') + cb() + }) + .after(function () { + t.equal(overrideCalls, 1, 'after with 0 parameter should not trigger override') + }) + .after(function (err) { + if (err) throw err + t.equal(overrideCalls, 1, 'after with 1 parameter should not trigger override') + }) + .after(function (err, done) { + if (err) throw err + t.equal(overrideCalls, 1, 'after with 2 parameters should not trigger override') + done() + }) + .after(function (err, context, done) { + if (err) throw err + t.equal(overrideCalls, 1, 'after with 3 parameters should not trigger override') + done() + }) + .after(async function () { + t.equal(overrideCalls, 1, 'async after with 0 parameter should not trigger override') + }) + .after(async function (err) { + if (err) throw err + t.equal(overrideCalls, 1, 'async after with 1 parameter should not trigger override') + }) + .after(async function (err, context) { + if (err) throw err + t.equal(overrideCalls, 1, 'async after with 2 parameters should not trigger override') + }) +}) + +test('custom inheritance override in after', (t) => { + t.plan(6) + + const server = { count: 0 } + const app = boot(server) + + app.override = function (s) { + const res = Object.create(s) + res.count = res.count + 1 + + return res + } + + app.use(function first (s1, opts, cb) { + t.not(s1, server) + t.ok(Object.prototype.isPrototypeOf.call(server, s1)) + t.equal(s1.count, 1) + s1.after(() => { + s1.use(second) + }) + + cb() + + function second (s2, opts, cb) { + t.not(s2, s1) + t.ok(Object.prototype.isPrototypeOf.call(s1, s2)) + t.equal(s2.count, 2) + cb() + } + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/plugin-loaded-so-far.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/plugin-loaded-so-far.test.js new file mode 100644 index 0000000000000000000000000000000000000000..bdad133a4f59884292ab532dd105f8aac9615b01 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/plugin-loaded-so-far.test.js @@ -0,0 +1,84 @@ +'use strict' + +const { test } = require('tap') +const fastq = require('fastq') +const boot = require('..') +const { Plugin } = require('../lib/plugin') + +test('loadedSoFar resolves a Promise, if plugin.loaded is set to true', async (t) => { + t.plan(1) + const app = boot({}) + + const plugin = new Plugin(fastq(app, app._loadPluginNextTick, 1), function (instance, opts, done) { + done() + }, false, 0) + + plugin.loaded = true + + await t.resolves(plugin.loadedSoFar()) +}) + +test('loadedSoFar resolves a Promise, if plugin was loaded by avvio', async (t) => { + t.plan(2) + const app = boot({}) + + const plugin = new Plugin(fastq(app, app._loadPluginNextTick, 1), function (instance, opts, done) { + done() + }, false, 0) + + app._loadPlugin(plugin, function (err) { + t.equal(err, undefined) + }) + + await app.ready() + + await t.resolves(plugin.loadedSoFar()) +}) + +test('loadedSoFar resolves a Promise, if .after() has no error', async t => { + t.plan(1) + const app = boot() + + app.after = function (callback) { + callback(null, () => {}) + } + + const plugin = new Plugin(fastq(app, app._loadPluginNextTick, 1), function (instance, opts, done) { + done() + }, false, 0) + + app._loadPlugin(plugin, function () {}) + + await t.resolves(plugin.loadedSoFar()) +}) + +test('loadedSoFar rejects a Promise, if .after() has an error', async t => { + t.plan(1) + const app = boot() + + app.after = function (fn) { + fn(new Error('ArbitraryError'), () => {}) + } + + const plugin = new Plugin(fastq(app, app._loadPluginNextTick, 1), function (instance, opts, done) { + done() + }, false, 0) + + app._loadPlugin(plugin, function () {}) + + await t.rejects(plugin.loadedSoFar(), new Error('ArbitraryError')) +}) + +test('loadedSoFar resolves a Promise, if Plugin is attached to avvio after it the Plugin was instantiated', async t => { + t.plan(1) + + const plugin = new Plugin(fastq(null, null, 1), function (instance, opts, done) { + done() + }, false, 0) + + const promise = plugin.loadedSoFar() + + plugin.server = boot() + plugin.emit('start') + await t.resolves(promise) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/plugin-name.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/plugin-name.test.js new file mode 100644 index 0000000000000000000000000000000000000000..fa129a51c574ed05e1ac4e718790466af64f9f81 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/plugin-name.test.js @@ -0,0 +1,69 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') +const { kPluginMeta } = require('../lib/symbols') + +test('plugins get a name from the plugin metadata if it is set', async (t) => { + t.plan(1) + const app = boot() + + const func = (app, opts, next) => next() + func[kPluginMeta] = { name: 'a-test-plugin' } + app.use(func) + await app.ready() + + t.match(app.toJSON(), { + label: 'root', + nodes: [ + { label: 'a-test-plugin' } + ] + }) +}) + +test('plugins get a name from the options if theres no metadata', async (t) => { + t.plan(1) + const app = boot() + + function testPlugin (app, opts, next) { next() } + app.use(testPlugin, { name: 'test registration options name' }) + await app.ready() + + t.match(app.toJSON(), { + label: 'root', + nodes: [ + { label: 'test registration options name' } + ] + }) +}) + +test('plugins get a name from the function name if theres no name in the options and no metadata', async (t) => { + t.plan(1) + const app = boot() + + function testPlugin (app, opts, next) { next() } + app.use(testPlugin) + await app.ready() + + t.match(app.toJSON(), { + label: 'root', + nodes: [ + { label: 'testPlugin' } + ] + }) +}) + +test('plugins get a name from the function source if theres no other option', async (t) => { + t.plan(1) + const app = boot() + + app.use((app, opts, next) => next()) + await app.ready() + + t.match(app.toJSON(), { + label: 'root', + nodes: [ + { label: '(app, opts, next) => next()' } + ] + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/plugin-timeout-await.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/plugin-timeout-await.test.js new file mode 100644 index 0000000000000000000000000000000000000000..13ecdd8f5968c2ffb15aa6cede9b1b62f17eb4ba --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/plugin-timeout-await.test.js @@ -0,0 +1,33 @@ +'use strict' + +/* eslint no-prototype-builtins: off */ + +const { test } = require('tap') +const boot = require('..') + +test('do not load', async (t) => { + const app = boot({}, { timeout: 10 }) + + app.use(first) + + async function first (s, opts) { + await s.use(second) + } + + async function second (s, opts) { + await s.use(third) + } + + function third (s, opts) { + return new Promise((resolve, reject) => { + // no resolve + }) + } + + try { + await app.start() + t.fail('should throw') + } catch (err) { + t.equal(err.message, 'Plugin did not start in time: \'third\'. You may have forgotten to call \'done\' function or to resolve a Promise') + } +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/plugin-timeout.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/plugin-timeout.test.js new file mode 100644 index 0000000000000000000000000000000000000000..22b97ca05cd85376da6cc3c90a3c52e0b08addf7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/plugin-timeout.test.js @@ -0,0 +1,218 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') + +const message = (name) => `Plugin did not start in time: '${name}'. You may have forgotten to call 'done' function or to resolve a Promise` + +test('timeout without calling next - callbacks', (t) => { + t.plan(4) + const app = boot({}, { + timeout: 10 // 10 ms + }) + app.use(one) + function one (app, opts, next) { + // do not call next on purpose + } + app.ready((err) => { + t.ok(err) + t.equal(err.fn, one) + t.equal(err.message, message('one')) + t.equal(err.code, 'AVV_ERR_PLUGIN_EXEC_TIMEOUT') + }) +}) + +test('timeout without calling next - promises', (t) => { + t.plan(4) + const app = boot({}, { + timeout: 10 // 10 ms + }) + app.use(two) + function two (app, opts) { + return new Promise(function (resolve) { + // do not call resolve on purpose + }) + } + app.ready((err) => { + t.ok(err) + t.equal(err.fn, two) + t.equal(err.message, message('two')) + t.equal(err.code, 'AVV_ERR_PLUGIN_EXEC_TIMEOUT') + }) +}) + +test('timeout without calling next - use file as name', (t) => { + t.plan(3) + const app = boot({}, { + timeout: 10 // 10 ms + }) + app.use(require('./fixtures/plugin-no-next')) + app.ready((err) => { + t.ok(err) + t.equal(err.message, message('noNext')) + t.equal(err.code, 'AVV_ERR_PLUGIN_EXEC_TIMEOUT') + }) +}) + +test('timeout without calling next - use code as name', (t) => { + t.plan(3) + const app = boot({}, { + timeout: 10 // 10 ms + }) + app.use(function (app, opts, next) { + // do not call next on purpose - code as name + }) + + app.ready((err) => { + t.ok(err) + t.equal(err.message, message('function (app, opts, next) { -- // do not call next on purpose - code as name')) + t.equal(err.code, 'AVV_ERR_PLUGIN_EXEC_TIMEOUT') + }) +}) + +test('does not keep going', (t) => { + t.plan(2) + const app = boot({}, { + timeout: 10 // 10 ms + }) + app.use(function three (app, opts, next) { + next(new Error('kaboom')) + }) + app.ready((err) => { + t.ok(err) + t.equal(err.message, 'kaboom') + }) +}) + +test('throw in override without autostart', (t) => { + t.plan(2) + + const server = { my: 'server' } + const app = boot(server, { + timeout: 10, + autostart: false + }) + + app.override = function (s) { + throw new Error('kaboom') + } + + app.use(function (s, opts, cb) { + t.fail('this is never reached') + }) + + setTimeout(function () { + app.ready((err) => { + t.ok(err) + t.equal(err.message, 'kaboom') + }) + }, 20) +}) + +test('timeout without calling next in ready and ignoring the error', (t) => { + t.plan(11) + const app = boot({}, { + timeout: 10, // 10 ms + autostart: false + }) + + let preReady = false + + app.use(function one (app, opts, next) { + t.pass('loaded') + app.ready(function readyOk (err, done) { + t.notOk(err) + t.pass('first ready called') + done() + }) + next() + }) + + app.on('preReady', () => { + t.pass('preReady should be called') + preReady = true + }) + + app.on('start', () => { + t.pass('start should be called') + }) + + app.ready(function onReadyWithoutDone (err, done) { + t.pass('wrong ready called') + t.ok(preReady, 'preReady already called') + t.notOk(err) + // done() // Don't call done + }) + + app.ready(function onReadyTwo (err) { + t.ok(err) + t.equal(err.message, message('onReadyWithoutDone')) + t.equal(err.code, 'AVV_ERR_READY_TIMEOUT') + // don't rethrow the error + }) + + app.start() +}) + +test('timeout without calling next in ready and rethrowing the error', (t) => { + t.plan(11) + const app = boot({}, { + timeout: 10, // 10 ms + autostart: true + }) + + app.use(function one (app, opts, next) { + t.pass('loaded') + app.ready(function readyOk (err, done) { + t.ok(err) + t.equal(err.message, message('onReadyWithoutDone')) + t.equal(err.code, 'AVV_ERR_READY_TIMEOUT') + done(err) + }) + next() + }) + + app.on('preReady', () => { + t.pass('preReady should be called') + }) + + app.on('start', () => { + t.pass('start should be called in any case') + }) + + app.ready(function onReadyWithoutDone (err, done) { + t.pass('wrong ready called') + t.notOk(err) + // done() // Don't call done + }) + + app.ready(function onReadyTwo (err, done) { + t.ok(err) + t.equal(err.message, message('onReadyWithoutDone')) + t.equal(err.code, 'AVV_ERR_READY_TIMEOUT') + done(err) + }) + + app.start() +}) + +test('nested timeout do not crash - await', (t) => { + t.plan(4) + const app = boot({}, { + timeout: 10 // 10 ms + }) + app.use(one) + async function one (app, opts) { + await app.use(two) + } + + function two (app, opts, next) { + // do not call next on purpose + } + app.ready((err) => { + t.ok(err) + t.equal(err.fn, two) + t.equal(err.message, message('two')) + t.equal(err.code, 'AVV_ERR_PLUGIN_EXEC_TIMEOUT') + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/pretty-print.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/pretty-print.test.js new file mode 100644 index 0000000000000000000000000000000000000000..734ab0806e8b783ea1d4525179697a1fa8d49680 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/pretty-print.test.js @@ -0,0 +1,75 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') + +test('pretty print', t => { + t.plan(19) + + const app = boot() + app + .use(first) + .use(duplicate, { count: 3 }) + .use(second).after(afterUse).after(after) + .use(duplicate, { count: 2 }) + .use(third).after(after) + .use(duplicate, { count: 1 }) + + const linesExpected = [/^root \d+ ms$/, + /^├── first \d+ ms$/, + /^├─┬ duplicate \d+ ms$/, + /^│ └─┬ duplicate \d+ ms$/, + /^│ {3}└─┬ duplicate \d+ ms$/, + /^│ {5}└── duplicate \d+ ms$/, + /^├── second \d+ ms$/, + /^├─┬ bound _after \d+ ms$/, + /^│ └── afterInsider \d+ ms$/, + /^├── bound _after \d+ ms$/, + /^├─┬ duplicate \d+ ms$/, + /^│ └─┬ duplicate \d+ ms$/, + /^│ {3}└── duplicate \d+ ms$/, + /^├── third \d+ ms$/, + /^├── bound _after \d+ ms$/, + /^└─┬ duplicate \d+ ms$/, + /^ {2}└── duplicate \d+ ms$/, + '' + ] + + app.on('preReady', function show () { + const print = app.prettyPrint() + const lines = print.split('\n') + + t.equal(lines.length, linesExpected.length) + lines.forEach((l, i) => { + t.match(l, linesExpected[i]) + }) + }) + + function first (s, opts, done) { + done() + } + function second (s, opts, done) { + done() + } + function third (s, opts, done) { + done() + } + function after (err, cb) { + cb(err) + } + function afterUse (err, cb) { + app.use(afterInsider) + cb(err) + } + + function afterInsider (s, opts, done) { + done() + } + + function duplicate (instance, opts, cb) { + if (opts.count > 0) { + instance.use(duplicate, { count: opts.count - 1 }) + } + setTimeout(cb, 20) + } +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/reentrant.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/reentrant.test.js new file mode 100644 index 0000000000000000000000000000000000000000..184be9c41c6738aac37a2d865b4b9a5f8f241981 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/reentrant.test.js @@ -0,0 +1,124 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') + +test('one level', (t) => { + t.plan(13) + + const app = boot() + let firstLoaded = false + let secondLoaded = false + let thirdLoaded = false + + app.use(first) + app.use(third) + + function first (s, opts, done) { + t.notOk(firstLoaded, 'first is not loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + firstLoaded = true + s.use(second) + done() + } + + function second (s, opts, done) { + t.ok(firstLoaded, 'first is loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + secondLoaded = true + done() + } + + function third (s, opts, done) { + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.notOk(thirdLoaded, 'third is not loaded') + thirdLoaded = true + done() + } + + app.on('start', () => { + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.pass('booted') + }) +}) + +test('multiple reentrant plugin loading', (t) => { + t.plan(31) + + const app = boot() + let firstLoaded = false + let secondLoaded = false + let thirdLoaded = false + let fourthLoaded = false + let fifthLoaded = false + + app.use(first) + app.use(fifth) + + function first (s, opts, done) { + t.notOk(firstLoaded, 'first is not loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + t.notOk(fourthLoaded, 'fourth is not loaded') + t.notOk(fifthLoaded, 'fifth is not loaded') + firstLoaded = true + s.use(second) + done() + } + + function second (s, opts, done) { + t.ok(firstLoaded, 'first is loaded') + t.notOk(secondLoaded, 'second is not loaded') + t.notOk(thirdLoaded, 'third is not loaded') + t.notOk(fourthLoaded, 'fourth is not loaded') + t.notOk(fifthLoaded, 'fifth is not loaded') + secondLoaded = true + s.use(third) + s.use(fourth) + done() + } + + function third (s, opts, done) { + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.notOk(thirdLoaded, 'third is not loaded') + t.notOk(fourthLoaded, 'fourth is not loaded') + t.notOk(fifthLoaded, 'fifth is not loaded') + thirdLoaded = true + done() + } + + function fourth (s, opts, done) { + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.notOk(fourthLoaded, 'fourth is not loaded') + t.notOk(fifthLoaded, 'fifth is not loaded') + fourthLoaded = true + done() + } + + function fifth (s, opts, done) { + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.ok(fourthLoaded, 'fourth is loaded') + t.notOk(fifthLoaded, 'fifth is not loaded') + fifthLoaded = true + done() + } + + app.on('start', () => { + t.ok(firstLoaded, 'first is loaded') + t.ok(secondLoaded, 'second is loaded') + t.ok(thirdLoaded, 'third is loaded') + t.ok(fourthLoaded, 'fourth is loaded') + t.ok(fifthLoaded, 'fifth is loaded') + t.pass('booted') + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/to-json.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/to-json.test.js new file mode 100644 index 0000000000000000000000000000000000000000..d37725acde10d401be53802f70fb587dcfa558a2 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/to-json.test.js @@ -0,0 +1,151 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') + +test('to json', (t) => { + t.plan(4) + + const app = boot() + app + .use(one) + .use(two) + .use(three) + + const outJson = { + id: 'root', + label: 'root', + start: /\d+/, + nodes: [] + } + + app.on('preReady', function show () { + const json = app.toJSON() + outJson.stop = /\d*/ + outJson.diff = /\d*/ + t.match(json, outJson) + }) + + function one (s, opts, done) { + const json = app.toJSON() + outJson.nodes.push({ + id: /.+/, + parent: outJson.label, + label: 'one', + start: /\d+/ + }) + t.match(json, outJson) + done() + } + function two (s, opts, done) { + const json = app.toJSON() + outJson.nodes.push({ + id: /.+/, + parent: outJson.label, + label: 'two', + start: /\d+/ + }) + t.match(json, outJson) + done() + } + function three (s, opts, done) { + const json = app.toJSON() + outJson.nodes.push({ + id: /.+/, + parent: outJson.label, + label: 'three', + start: /\d+/ + }) + t.match(json, outJson) + done() + } +}) + +test('to json multi-level hierarchy', (t) => { + t.plan(4) + + const server = { name: 'asd', count: 0 } + const app = boot(server) + + const outJson = { + id: 'root', + label: 'root', + start: /\d+/, + nodes: [ + { + id: /.+/, + parent: 'root', + start: /\d+/, + label: 'first', + nodes: [ + { + id: /.+/, + parent: 'first', + start: /\d+/, + label: 'second', + nodes: [], + stop: /\d+/, + diff: /\d+/ + }, + { + id: /.+/, + parent: 'first', + start: /\d+/, + label: 'third', + nodes: [ + { + id: /.+/, + parent: 'third', + start: /\d+/, + label: 'fourth', + nodes: [], + stop: /\d+/, + diff: /\d+/ + } + ], + stop: /\d+/, + diff: /\d+/ + } + ], + stop: /\d+/, + diff: /\d+/ + } + ], + stop: /\d+/, + diff: /\d+/ + } + + app.on('preReady', function show () { + const json = app.toJSON() + t.match(json, outJson) + }) + + app.override = function (s) { + const res = Object.create(s) + res.count = res.count + 1 + res.name = 'qwe' + return res + } + + app.use(function first (s1, opts, cb) { + s1.use(second) + s1.use(third) + cb() + + function second (s2, opts, cb) { + t.equal(s2.count, 2) + cb() + } + + function third (s3, opts, cb) { + s3.use(fourth) + t.equal(s3.count, 2) + cb() + } + + function fourth (s4, opts, cb) { + t.equal(s4.count, 3) + cb() + } + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/twice-done.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/twice-done.test.js new file mode 100644 index 0000000000000000000000000000000000000000..ecff9c55de53eb64a4ed6f5fbb0e9f053997fc4e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/twice-done.test.js @@ -0,0 +1,22 @@ +'use strict' + +const { test } = require('tap') +const boot = require('..') + +test('calling done twice does not throw error', (t) => { + t.plan(2) + + const app = boot() + + app + .use(twiceDone) + .ready((err) => { + t.notOk(err, 'no error') + }) + + function twiceDone (s, opts, done) { + done() + done() + t.pass('did not throw') + } +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/types/index.ts b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/types/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..43497d0cad59dce1c495ec7ca382f37ab5feeb05 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/types/index.ts @@ -0,0 +1,411 @@ +import * as avvio from "../../"; + +{ + // avvio with no argument + const app = avvio(); + + app.override = (server, fn, options) => server; + + app.use( + (server, opts, done) => { + server.use; + server.after; + server.ready; + server.on; + server.start; + server.override; + server.onClose; + server.close; + + opts.mySuper; + + done(); + }, + { mySuper: "option" } + ); + + app.use(async (server, options) => { + server.use; + server.after; + server.ready; + server.on; + server.start; + server.override; + server.onClose; + server.close; + }); + + app.use(async (server, options) => {}, + (server) => { + server.use; + server.after; + server.ready; + server.on; + server.start; + server.override; + server.onClose; + server.close; + }); + + app.after(err => { + if (err) throw err; + }); + + app.after((err: Error, done: Function) => { + done(); + }); + + app.after((err: Error, context: avvio.context, done: Function) => { + context.use; + context.after; + context.ready; + context.on; + context.start; + context.override; + context.onClose; + context.close; + + done(); + }); + + app.ready().then(context => { + context.use; + context.after; + context.ready; + context.on; + context.start; + context.override; + context.onClose; + context.close; + }); + + app.ready(err => { + if (err) throw err; + }); + + app.ready((err: Error, done: Function) => { + done(); + }); + + app.ready((err: Error, context: avvio.context, done: Function) => { + context.use; + context.after; + context.ready; + context.on; + context.start; + context.override; + context.onClose; + context.close; + + done(); + }); + + app.close(err => { + if (err) throw err; + }); + + app.close((err: Error, done: Function) => { + done(); + }); + + app.close((err: Error, context: avvio.context, done: Function) => { + context.use; + context.after; + context.ready; + context.on; + context.start; + context.override; + context.onClose; + context.close; + + done(); + }); + + app.onClose((context, done) => { + context.use; + context.after; + context.ready; + context.on; + context.start; + context.override; + context.onClose; + context.close; + + done(); + }); +} + +{ + // avvio with done + const app = avvio(() => undefined); + + app.use( + (server, opts, done) => { + server.use; + server.after; + server.ready; + server.on; + server.start; + server.override; + server.onClose; + server.close; + + opts.mySuper; + + done(); + }, + { mySuper: "option" } + ); + + app.use(async (server, options) => { + server.use; + server.after; + server.ready; + server.on; + server.start; + server.override; + server.onClose; + server.close; + }); + + app.use(async (server, options) => {}, + (server) => { + server.use; + server.after; + server.ready; + server.on; + server.start; + server.override; + server.onClose; + server.close; + }); + + app.after(err => { + if (err) throw err; + }); + + app.after((err: Error, done: Function) => { + done(); + }); + + app.after((err: Error, context: avvio.context, done: Function) => { + context.use; + context.after; + context.ready; + context.on; + context.start; + context.override; + context.onClose; + context.close; + + done(); + }); + + app.ready().then(context => { + context.use; + context.after; + context.ready; + context.on; + context.start; + context.override; + context.onClose; + context.close; + }); + + app.ready(err => { + if (err) throw err; + }); + + app.ready((err: Error, done: Function) => { + done(); + }); + + app.ready((err: Error, context: avvio.context, done: Function) => { + context.use; + context.after; + context.ready; + context.on; + context.start; + context.override; + context.onClose; + context.close; + + done(); + }); + + app.close(err => { + if (err) throw err; + }); + + app.close((err: Error, done: Function) => { + done(); + }); + + app.close((err: Error, context: avvio.context, done: Function) => { + context.use; + context.after; + context.ready; + context.on; + context.start; + context.override; + context.onClose; + context.close; + + done(); + }); + + app.onClose((context, done) => { + context.use; + context.after; + context.ready; + context.on; + context.start; + context.override; + context.onClose; + context.close; + + done(); + }); +} + +{ + const server = { typescriptIs: "amazing" }; + // avvio with server + const app = avvio(server); + + app.use( + (server, opts, done) => { + server.use; + server.after; + server.ready; + server.typescriptIs; + + opts.mySuper; + + done(); + }, + { mySuper: "option" } + ); + + app.use(async (server, options) => { + server.use; + server.after; + server.ready; + server.typescriptIs; + }); + + app.use(async (server, options) => {}, + ((server) => { + server.use; + server.after; + server.ready; + server.typescriptIs; + })); + + app.after(err => { + if (err) throw err; + }); + + app.after((err: Error, done: Function) => { + done(); + }); + + app.after( + (err: Error, context: avvio.context, done: Function) => { + context.use; + context.after; + context.ready; + context.typescriptIs; + + done(); + } + ); + + app.ready().then(context => { + context.use; + context.after; + context.ready; + context.typescriptIs; + }); + + app.ready(err => { + if (err) throw err; + }); + + app.ready((err: Error, done: Function) => { + done(); + }); + + app.ready( + (err: Error, context: avvio.context, done: Function) => { + context.use; + context.after; + context.ready; + context.close; + context.onClose; + context.typescriptIs; + + done(); + } + ); + + app.close(err => { + if (err) throw err; + }); + + app.close((err: Error, done: Function) => { + done(); + }); + + app.close( + (err: Error, context: avvio.context, done: Function) => { + context.use; + context.after; + context.ready; + context.close; + context.onClose; + context.typescriptIs; + + done(); + } + ); + + app.onClose((context, done) => { + context.use; + context.after; + context.ready; + context.close; + context.onClose; + context.typescriptIs; + + done(); + }); +} + +{ + const server = { hello: "world" }; + const options = { + autostart: false, + expose: { after: "after", ready: "ready", use: "use", close: "close", onClose : "onClose" }, + timeout: 50000 + }; + // avvio with server and options + const app = avvio(server, options); +} + +{ + const server = { hello: "world" }; + const options = { + autostart: false, + expose: { after: "after", ready: "ready", use: "use" } + }; + // avvio with server, options and done callback + const app = avvio(server, options, () => undefined); +} + +{ + const app = avvio(); + const plugin: avvio.Plugin = async (): Promise => {}; + const promise = plugin(app, {}, undefined as any); + (promise instanceof Promise); +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/types/tsconfig.json b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/types/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..b170f36f4e994b3462921781ed1ba86fd14ed658 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/avvio/test/types/tsconfig.json @@ -0,0 +1,9 @@ +{ + "compilerOptions": { + "target": "es6", + "module": "commonjs", + "noEmit": true, + "strict": true + }, + "files": ["./index.ts"] +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/fast-json-stringify/test/additionalProperties.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/fast-json-stringify/test/additionalProperties.test.js new file mode 100644 index 0000000000000000000000000000000000000000..a42e176b1afc9f61ff59fa84bcc38179842fc6d9 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/fast-json-stringify/test/additionalProperties.test.js @@ -0,0 +1,332 @@ +'use strict' + +const { test } = require('node:test') +const build = require('..') + +test('additionalProperties', (t) => { + t.plan(1) + const stringify = build({ + title: 'additionalProperties', + type: 'object', + properties: { + str: { + type: 'string' + } + }, + additionalProperties: { + type: 'string' + } + }) + + const obj = { str: 'test', foo: 42, ofoo: true, foof: 'string', objfoo: { a: true } } + t.assert.equal(stringify(obj), '{"str":"test","foo":"42","ofoo":"true","foof":"string","objfoo":"[object Object]"}') +}) + +test('additionalProperties should not change properties', (t) => { + t.plan(1) + const stringify = build({ + title: 'patternProperties should not change properties', + type: 'object', + properties: { + foo: { + type: 'string' + } + }, + additionalProperties: { + type: 'number' + } + }) + + const obj = { foo: '42', ofoo: 42 } + t.assert.equal(stringify(obj), '{"foo":"42","ofoo":42}') +}) + +test('additionalProperties should not change properties and patternProperties', (t) => { + t.plan(1) + const stringify = build({ + title: 'patternProperties should not change properties', + type: 'object', + properties: { + foo: { + type: 'string' + } + }, + patternProperties: { + foo: { + type: 'string' + } + }, + additionalProperties: { + type: 'number' + } + }) + + const obj = { foo: '42', ofoo: 42, test: '42' } + t.assert.equal(stringify(obj), '{"foo":"42","ofoo":"42","test":42}') +}) + +test('additionalProperties set to true, use of fast-safe-stringify', (t) => { + t.plan(1) + const stringify = build({ + title: 'check string coerce', + type: 'object', + properties: {}, + additionalProperties: true + }) + + const obj = { foo: true, ofoo: 42, arrfoo: ['array', 'test'], objfoo: { a: 'world' } } + t.assert.equal(stringify(obj), '{"foo":true,"ofoo":42,"arrfoo":["array","test"],"objfoo":{"a":"world"}}') +}) + +test('additionalProperties - string coerce', (t) => { + t.plan(1) + const stringify = build({ + title: 'check string coerce', + type: 'object', + properties: {}, + additionalProperties: { + type: 'string' + } + }) + + const obj = { foo: true, ofoo: 42, arrfoo: ['array', 'test'], objfoo: { a: 'world' } } + t.assert.equal(stringify(obj), '{"foo":"true","ofoo":"42","arrfoo":"array,test","objfoo":"[object Object]"}') +}) + +test('additionalProperties - number skip', (t) => { + t.plan(1) + const stringify = build({ + title: 'check number coerce', + type: 'object', + properties: {}, + additionalProperties: { + type: 'number' + } + }) + + // const obj = { foo: true, ofoo: '42', xfoo: 'string', arrfoo: [1, 2], objfoo: { num: 42 } } + const obj = { foo: true, ofoo: '42' } + t.assert.equal(stringify(obj), '{"foo":1,"ofoo":42}') +}) + +test('additionalProperties - boolean coerce', (t) => { + t.plan(1) + const stringify = build({ + title: 'check boolean coerce', + type: 'object', + properties: {}, + additionalProperties: { + type: 'boolean' + } + }) + + const obj = { foo: 'true', ofoo: 0, arrfoo: [1, 2], objfoo: { a: true } } + t.assert.equal(stringify(obj), '{"foo":true,"ofoo":false,"arrfoo":true,"objfoo":true}') +}) + +test('additionalProperties - object coerce', (t) => { + t.plan(1) + const stringify = build({ + title: 'check object coerce', + type: 'object', + properties: {}, + additionalProperties: { + type: 'object', + properties: { + answer: { + type: 'number' + } + } + } + }) + + const obj = { objfoo: { answer: 42 } } + t.assert.equal(stringify(obj), '{"objfoo":{"answer":42}}') +}) + +test('additionalProperties - array coerce', (t) => { + t.plan(2) + const stringify = build({ + title: 'check array coerce', + type: 'object', + properties: {}, + additionalProperties: { + type: 'array', + items: { + type: 'string' + } + } + }) + + const coercibleValues = { arrfoo: [1, 2] } + t.assert.equal(stringify(coercibleValues), '{"arrfoo":["1","2"]}') + + const incoercibleValues = { foo: 'true', ofoo: 0, objfoo: { tyrion: 'lannister' } } + t.assert.throws(() => stringify(incoercibleValues)) +}) + +test('additionalProperties with empty schema', (t) => { + t.plan(1) + const stringify = build({ + type: 'object', + additionalProperties: {} + }) + + const obj = { a: 1, b: true, c: null } + t.assert.equal(stringify(obj), '{"a":1,"b":true,"c":null}') +}) + +test('additionalProperties with nested empty schema', (t) => { + t.plan(1) + const stringify = build({ + type: 'object', + properties: { + data: { type: 'object', additionalProperties: {} } + }, + required: ['data'] + }) + + const obj = { data: { a: 1, b: true, c: null } } + t.assert.equal(stringify(obj), '{"data":{"a":1,"b":true,"c":null}}') +}) + +test('nested additionalProperties', (t) => { + t.plan(1) + const stringify = build({ + title: 'additionalProperties', + type: 'array', + items: { + type: 'object', + properties: { + ap: { + type: 'object', + additionalProperties: { type: 'string' } + } + } + } + }) + + const obj = [{ ap: { value: 'string' } }] + t.assert.equal(stringify(obj), '[{"ap":{"value":"string"}}]') +}) + +test('very nested additionalProperties', (t) => { + t.plan(1) + const stringify = build({ + title: 'additionalProperties', + type: 'array', + items: { + type: 'object', + properties: { + ap: { + type: 'object', + properties: { + nested: { + type: 'object', + properties: { + moarNested: { + type: 'object', + properties: { + finally: { + type: 'object', + additionalProperties: { + type: 'string' + } + } + } + } + } + } + } + } + } + } + }) + + const obj = [{ ap: { nested: { moarNested: { finally: { value: 'str' } } } } }] + t.assert.equal(stringify(obj), '[{"ap":{"nested":{"moarNested":{"finally":{"value":"str"}}}}}]') +}) + +test('nested additionalProperties set to true', (t) => { + t.plan(1) + const stringify = build({ + title: 'nested additionalProperties=true', + type: 'object', + properties: { + ap: { + type: 'object', + additionalProperties: true + } + } + }) + + const obj = { ap: { value: 'string', someNumber: 42 } } + t.assert.equal(stringify(obj), '{"ap":{"value":"string","someNumber":42}}') +}) + +test('field passed to fastSafeStringify as undefined should be removed', (t) => { + t.plan(1) + const stringify = build({ + title: 'nested additionalProperties=true', + type: 'object', + properties: { + ap: { + type: 'object', + additionalProperties: true + } + } + }) + + const obj = { ap: { value: 'string', someNumber: undefined } } + t.assert.equal(stringify(obj), '{"ap":{"value":"string"}}') +}) + +test('property without type but with enum, will acts as additionalProperties', (t) => { + t.plan(1) + const stringify = build({ + title: 'automatic additionalProperties', + type: 'object', + properties: { + ap: { + enum: ['foobar', 42, ['foo', 'bar'], {}] + } + } + }) + + const obj = { ap: { additional: 'field' } } + t.assert.equal(stringify(obj), '{"ap":{"additional":"field"}}') +}) + +test('property without type but with enum, will acts as additionalProperties without overwriting', (t) => { + t.plan(1) + const stringify = build({ + title: 'automatic additionalProperties', + type: 'object', + properties: { + ap: { + additionalProperties: false, + enum: ['foobar', 42, ['foo', 'bar'], {}] + } + } + }) + + const obj = { ap: { additional: 'field' } } + t.assert.equal(stringify(obj), '{"ap":{}}') +}) + +test('function and symbol references are not serialized as undefined', (t) => { + t.plan(1) + const stringify = build({ + title: 'additionalProperties', + type: 'object', + additionalProperties: true, + properties: { + str: { + type: 'string' + } + } + }) + + const obj = { str: 'x', test: 'test', meth: () => 'x', sym: Symbol('x') } + t.assert.equal(stringify(obj), '{"str":"x","test":"test"}') +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/fast-json-stringify/test/allof.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/fast-json-stringify/test/allof.test.js new file mode 100644 index 0000000000000000000000000000000000000000..fe3d2c204a44036804f0410a2b68145f168a0d3c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/fast-json-stringify/test/allof.test.js @@ -0,0 +1,751 @@ +'use strict' + +const { test } = require('node:test') +const build = require('..') + +process.env.TZ = 'UTC' + +test('allOf: combine type and format ', (t) => { + t.plan(1) + + const schema = { + allOf: [ + { type: 'string' }, + { format: 'time' } + ] + } + const stringify = build(schema) + const date = new Date(1674263005800) + const value = stringify(date) + t.assert.equal(value, '"01:03:25"') +}) + +test('allOf: combine additional properties ', (t) => { + t.plan(1) + + const schema = { + allOf: [ + { type: 'object' }, + { + type: 'object', + additionalProperties: { type: 'boolean' } + } + ] + } + const stringify = build(schema) + const data = { property: true } + const value = stringify(data) + t.assert.equal(value, JSON.stringify(data)) +}) + +test('allOf: combine pattern properties', (t) => { + t.plan(1) + + const schema = { + allOf: [ + { type: 'object' }, + { + type: 'object', + patternProperties: { + foo: { + type: 'number' + } + } + } + ] + } + const stringify = build(schema) + const data = { foo: 42 } + const value = stringify(data) + t.assert.equal(value, JSON.stringify(data)) +}) + +test('object with allOf and multiple schema on the allOf', (t) => { + t.plan(4) + + const schema = { + title: 'object with allOf and multiple schema on the allOf', + type: 'object', + allOf: [ + { + type: 'object', + required: [ + 'name' + ], + properties: { + name: { + type: 'string' + }, + tag: { + type: 'string' + } + } + }, + { + required: [ + 'id' + ], + type: 'object', + properties: { + id: { + type: 'integer' + } + } + } + ] + } + const stringify = build(schema) + + try { + stringify({ + id: 1 + }) + } catch (e) { + t.assert.equal(e.message, '"name" is required!') + } + + try { + stringify({ + name: 'string' + }) + } catch (e) { + t.assert.equal(e.message, '"id" is required!') + } + + t.assert.equal(stringify({ + id: 1, + name: 'string' + }), '{"name":"string","id":1}') + + t.assert.equal(stringify({ + id: 1, + name: 'string', + tag: 'otherString' + }), '{"name":"string","id":1,"tag":"otherString"}') +}) + +test('object with allOf and one schema on the allOf', (t) => { + t.plan(1) + + const schema = { + title: 'object with allOf and one schema on the allOf', + type: 'object', + allOf: [ + { + required: [ + 'id' + ], + type: 'object', + properties: { + id: { + type: 'integer' + } + } + } + ] + } + const stringify = build(schema) + + const value = stringify({ + id: 1 + }) + t.assert.equal(value, '{"id":1}') +}) + +test('object with allOf and no schema on the allOf', (t) => { + t.plan(1) + + const schema = { + title: 'object with allOf and no schema on the allOf', + type: 'object', + allOf: [] + } + + try { + build(schema) + t.fail() + } catch (e) { + t.assert.equal(e.message, 'schema is invalid: data/allOf must NOT have fewer than 1 items') + } +}) + +test('object with nested allOfs', (t) => { + t.plan(1) + + const schema = { + title: 'object with nested allOfs', + type: 'object', + allOf: [ + { + required: [ + 'id1' + ], + type: 'object', + properties: { + id1: { + type: 'integer' + } + } + }, + { + allOf: [ + { + type: 'object', + properties: { + id2: { + type: 'integer' + } + } + }, + { + type: 'object', + properties: { + id3: { + type: 'integer' + } + } + } + ] + } + ] + } + + const stringify = build(schema) + const value = stringify({ + id1: 1, + id2: 2, + id3: 3, + id4: 4 // extra prop shouldn't be in result + }) + t.assert.equal(value, '{"id1":1,"id2":2,"id3":3}') +}) + +test('object with anyOf nested inside allOf', (t) => { + t.plan(1) + + const schema = { + title: 'object with anyOf nested inside allOf', + type: 'object', + allOf: [ + { + required: ['id1', 'obj'], + type: 'object', + properties: { + id1: { + type: 'integer' + }, + obj: { + type: 'object', + properties: { + nested: { type: 'string' } + } + } + } + }, + { + anyOf: [ + { + type: 'object', + properties: { + id2: { type: 'string' } + }, + required: ['id2'] + }, + { + type: 'object', + properties: { + id3: { + type: 'integer' + }, + nestedObj: { + type: 'object', + properties: { + nested: { type: 'string' } + } + } + }, + required: ['id3'] + }, + { + type: 'object', + properties: { + id4: { type: 'integer' } + }, + required: ['id4'] + } + ] + } + ] + } + + const stringify = build(schema) + const value = stringify({ + id1: 1, + id3: 3, + id4: 4, // extra prop shouldn't be in result + obj: { nested: 'yes' }, + nestedObj: { nested: 'yes' } + }) + t.assert.equal(value, '{"id1":1,"obj":{"nested":"yes"},"id3":3,"nestedObj":{"nested":"yes"}}') +}) + +test('object with $ref in allOf', (t) => { + t.plan(1) + + const schema = { + title: 'object with $ref in allOf', + type: 'object', + definitions: { + id1: { + type: 'object', + properties: { + id1: { + type: 'integer' + } + } + } + }, + allOf: [ + { + $ref: '#/definitions/id1' + } + ] + } + + const stringify = build(schema) + const value = stringify({ + id1: 1, + id2: 2 // extra prop shouldn't be in result + }) + t.assert.equal(value, '{"id1":1}') +}) + +test('object with $ref and other object in allOf', (t) => { + t.plan(1) + + const schema = { + title: 'object with $ref in allOf', + type: 'object', + definitions: { + id1: { + type: 'object', + properties: { + id1: { + type: 'integer' + } + } + } + }, + allOf: [ + { + $ref: '#/definitions/id1' + }, + { + type: 'object', + properties: { + id2: { + type: 'integer' + } + } + } + ] + } + + const stringify = build(schema) + const value = stringify({ + id1: 1, + id2: 2, + id3: 3 // extra prop shouldn't be in result + }) + t.assert.equal(value, '{"id1":1,"id2":2}') +}) + +test('object with multiple $refs in allOf', (t) => { + t.plan(1) + + const schema = { + title: 'object with $ref in allOf', + type: 'object', + definitions: { + id1: { + type: 'object', + properties: { + id1: { + type: 'integer' + } + } + }, + id2: { + type: 'object', + properties: { + id2: { + type: 'integer' + } + } + } + }, + allOf: [ + { + $ref: '#/definitions/id1' + }, + { + $ref: '#/definitions/id2' + } + ] + } + + const stringify = build(schema) + const value = stringify({ + id1: 1, + id2: 2, + id3: 3 // extra prop shouldn't be in result + }) + t.assert.equal(value, '{"id1":1,"id2":2}') +}) + +test('allOf with nested allOf in $ref', (t) => { + t.plan(1) + + const schema = { + title: 'allOf with nested allOf in $ref', + type: 'object', + definitions: { + group: { + type: 'object', + allOf: [{ + properties: { + id2: { + type: 'integer' + } + } + }, { + properties: { + id3: { + type: 'integer' + } + } + }] + } + }, + allOf: [ + { + type: 'object', + properties: { + id1: { + type: 'integer' + } + }, + required: [ + 'id1' + ] + }, + { + $ref: '#/definitions/group' + } + ] + } + + const stringify = build(schema) + const value = stringify({ + id1: 1, + id2: 2, + id3: 3, + id4: 4 // extra prop shouldn't be in result + }) + t.assert.equal(value, '{"id1":1,"id2":2,"id3":3}') +}) + +test('object with external $refs in allOf', (t) => { + t.plan(1) + + const externalSchema = { + first: { + definitions: { + id1: { + type: 'object', + properties: { + id1: { + type: 'integer' + } + } + } + } + }, + second: { + definitions: { + id2: { + $id: '#id2', + type: 'object', + properties: { + id2: { + type: 'integer' + } + } + } + } + } + } + + const schema = { + title: 'object with $ref in allOf', + type: 'object', + allOf: [ + { + $ref: 'first#/definitions/id1' + }, + { + $ref: 'second#/definitions/id2' + } + ] + } + + const stringify = build(schema, { schema: externalSchema }) + const value = stringify({ + id1: 1, + id2: 2, + id3: 3 // extra prop shouldn't be in result + }) + t.assert.equal(value, '{"id1":1,"id2":2}') +}) + +test('allof with local anchor reference', (t) => { + t.plan(1) + + const externalSchemas = { + Test: { + $id: 'Test', + definitions: { + Problem: { + type: 'object', + properties: { + type: { + type: 'string' + } + } + }, + ValidationFragment: { + type: 'string' + }, + ValidationErrorProblem: { + type: 'object', + allOf: [ + { + $ref: '#/definitions/Problem' + }, + { + type: 'object', + properties: { + validation: { + $ref: '#/definitions/ValidationFragment' + } + } + } + ] + } + } + } + } + + const schema = { $ref: 'Test#/definitions/ValidationErrorProblem' } + const stringify = build(schema, { schema: externalSchemas }) + const data = { type: 'foo', validation: 'bar' } + + t.assert.equal(stringify(data), JSON.stringify(data)) +}) + +test('allOf: multiple nested $ref properties', (t) => { + t.plan(2) + + const externalSchema1 = { + $id: 'externalSchema1', + oneOf: [ + { $ref: '#/definitions/id1' } + ], + definitions: { + id1: { + type: 'object', + properties: { + id1: { + type: 'integer' + } + }, + additionalProperties: false + } + } + } + + const externalSchema2 = { + $id: 'externalSchema2', + oneOf: [ + { $ref: '#/definitions/id2' } + ], + definitions: { + id2: { + type: 'object', + properties: { + id2: { + type: 'integer' + } + }, + additionalProperties: false + } + } + } + + const schema = { + anyOf: [ + { $ref: 'externalSchema1' }, + { $ref: 'externalSchema2' } + ] + } + + const stringify = build(schema, { schema: [externalSchema1, externalSchema2] }) + + t.assert.equal(stringify({ id1: 1 }), JSON.stringify({ id1: 1 })) + t.assert.equal(stringify({ id2: 2 }), JSON.stringify({ id2: 2 })) +}) + +test('allOf: throw Error if types mismatch ', (t) => { + t.plan(1) + + const schema = { + allOf: [ + { type: 'string' }, + { type: 'number' } + ] + } + t.assert.throws(() => { + build(schema) + }, { + message: 'Failed to merge "type" keyword schemas.', + schemas: [['string'], ['number']] + }) +}) + +test('allOf: throw Error if format mismatch ', (t) => { + t.plan(1) + + const schema = { + allOf: [ + { format: 'date' }, + { format: 'time' } + ] + } + t.assert.throws(() => { + build(schema) + }, { + message: 'Failed to merge "format" keyword schemas.' + // schemas: ['date', 'time'] + }) +}) + +test('recursive nested allOfs', (t) => { + t.plan(1) + + const schema = { + type: 'object', + properties: { + foo: { + additionalProperties: false, + allOf: [{ $ref: '#' }] + } + } + } + + const data = { foo: {} } + const stringify = build(schema) + t.assert.equal(stringify(data), JSON.stringify(data)) +}) + +test('recursive nested allOfs', (t) => { + t.plan(1) + + const schema = { + type: 'object', + properties: { + foo: { + additionalProperties: false, + allOf: [{ allOf: [{ $ref: '#' }] }] + } + } + } + + const data = { foo: {} } + const stringify = build(schema) + t.assert.equal(stringify(data), JSON.stringify(data)) +}) + +test('external recursive allOfs', (t) => { + t.plan(1) + + const externalSchema = { + type: 'object', + properties: { + foo: { + properties: { + bar: { type: 'string' } + }, + allOf: [{ $ref: '#' }] + } + } + } + + const schema = { + type: 'object', + properties: { + a: { $ref: 'externalSchema#/properties/foo' }, + b: { $ref: 'externalSchema#/properties/foo' } + } + } + + const data = { + a: { + foo: {}, + bar: '42', + baz: 42 + }, + b: { + foo: {}, + bar: '42', + baz: 42 + } + } + const stringify = build(schema, { schema: { externalSchema } }) + t.assert.equal(stringify(data), '{"a":{"bar":"42","foo":{}},"b":{"bar":"42","foo":{}}}') +}) + +test('do not crash with $ref prop', (t) => { + t.plan(1) + + const schema = { + title: 'object with $ref', + type: 'object', + properties: { + outside: { + $ref: '#/$defs/outside' + } + }, + $defs: { + inside: { + type: 'object', + properties: { + $ref: { + type: 'string' + } + } + }, + outside: { + allOf: [{ + $ref: '#/$defs/inside' + }] + } + } + } + const stringify = build(schema) + const value = stringify({ + outside: { + $ref: 'true' + } + }) + t.assert.equal(value, '{"outside":{"$ref":"true"}}') +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/fast-json-stringify/test/any.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/fast-json-stringify/test/any.test.js new file mode 100644 index 0000000000000000000000000000000000000000..a73aa0c1236d62720a30c4eca50b9c34539127ef --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/fast-json-stringify/test/any.test.js @@ -0,0 +1,231 @@ +'use strict' + +const { test } = require('node:test') +const build = require('..') + +test('object with nested random property', (t) => { + t.plan(4) + + const schema = { + title: 'empty schema to allow any object', + type: 'object', + properties: { + id: { type: 'number' }, + name: {} + } + } + const stringify = build(schema) + + t.assert.equal(stringify({ + id: 1, name: 'string' + }), '{"id":1,"name":"string"}') + + t.assert.equal(stringify({ + id: 1, name: { first: 'name', last: 'last' } + }), '{"id":1,"name":{"first":"name","last":"last"}}') + + t.assert.equal(stringify({ + id: 1, name: null + }), '{"id":1,"name":null}') + + t.assert.equal(stringify({ + id: 1, name: ['first', 'last'] + }), '{"id":1,"name":["first","last"]}') +}) + +// reference: https://github.com/fastify/fast-json-stringify/issues/259 +test('object with empty schema with $id: undefined set', (t) => { + t.plan(1) + + const schema = { + title: 'empty schema to allow any object with $id: undefined set', + type: 'object', + properties: { + name: { $id: undefined } + } + } + const stringify = build(schema) + t.assert.equal(stringify({ + name: 'string' + }), '{"name":"string"}') +}) + +test('array with random items', (t) => { + t.plan(1) + + const schema = { + title: 'empty schema to allow any object', + type: 'array', + items: {} + } + const stringify = build(schema) + + const value = stringify([1, 'string', null]) + t.assert.equal(value, '[1,"string",null]') +}) + +test('empty schema', (t) => { + t.plan(7) + + const schema = { } + + const stringify = build(schema) + + t.assert.equal(stringify(null), 'null') + t.assert.equal(stringify(1), '1') + t.assert.equal(stringify(true), 'true') + t.assert.equal(stringify('hello'), '"hello"') + t.assert.equal(stringify({}), '{}') + t.assert.equal(stringify({ x: 10 }), '{"x":10}') + t.assert.equal(stringify([true, 1, 'hello']), '[true,1,"hello"]') +}) + +test('empty schema on nested object', (t) => { + t.plan(7) + + const schema = { + type: 'object', + properties: { + x: {} + } + } + + const stringify = build(schema) + + t.assert.equal(stringify({ x: null }), '{"x":null}') + t.assert.equal(stringify({ x: 1 }), '{"x":1}') + t.assert.equal(stringify({ x: true }), '{"x":true}') + t.assert.equal(stringify({ x: 'hello' }), '{"x":"hello"}') + t.assert.equal(stringify({ x: {} }), '{"x":{}}') + t.assert.equal(stringify({ x: { x: 10 } }), '{"x":{"x":10}}') + t.assert.equal(stringify({ x: [true, 1, 'hello'] }), '{"x":[true,1,"hello"]}') +}) + +test('empty schema on array', (t) => { + t.plan(1) + + const schema = { + type: 'array', + items: {} + } + + const stringify = build(schema) + + t.assert.equal(stringify([1, true, 'hello', [], { x: 1 }]), '[1,true,"hello",[],{"x":1}]') +}) + +test('empty schema on anyOf', (t) => { + t.plan(4) + + // any on Foo codepath. + const schema = { + anyOf: [ + { + type: 'object', + properties: { + kind: { + type: 'string', + enum: ['Foo'] + }, + value: {} + } + }, + { + type: 'object', + properties: { + kind: { + type: 'string', + enum: ['Bar'] + }, + value: { + type: 'number' + } + } + } + ] + } + + const stringify = build(schema) + + t.assert.equal(stringify({ kind: 'Bar', value: 1 }), '{"kind":"Bar","value":1}') + t.assert.equal(stringify({ kind: 'Foo', value: 1 }), '{"kind":"Foo","value":1}') + t.assert.equal(stringify({ kind: 'Foo', value: true }), '{"kind":"Foo","value":true}') + t.assert.equal(stringify({ kind: 'Foo', value: 'hello' }), '{"kind":"Foo","value":"hello"}') +}) + +test('should throw a TypeError with the path to the key of the invalid value /1', (t) => { + t.plan(1) + + // any on Foo codepath. + const schema = { + anyOf: [ + { + type: 'object', + properties: { + kind: { + type: 'string', + enum: ['Foo'] + }, + value: {} + } + }, + { + type: 'object', + properties: { + kind: { + type: 'string', + enum: ['Bar'] + }, + value: { + type: 'number' + } + } + } + ] + } + + const stringify = build(schema) + + t.assert.throws(() => stringify({ kind: 'Baz', value: 1 }), new TypeError('The value of \'#\' does not match schema definition.')) +}) + +test('should throw a TypeError with the path to the key of the invalid value /2', (t) => { + t.plan(1) + + // any on Foo codepath. + const schema = { + type: 'object', + properties: { + data: { + anyOf: [ + { + type: 'object', + properties: { + kind: { + type: 'string', + enum: ['Foo'] + }, + value: {} + } + }, + { + type: 'object', + properties: { + kind: { + type: 'string', + enum: ['Bar'] + }, + value: { + type: 'number' + } + } + } + ] + } + } + } + + const stringify = build(schema) + + t.assert.throws(() => stringify({ data: { kind: 'Baz', value: 1 } }), new TypeError('The value of \'#/properties/data\' does not match schema definition.')) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/fast-json-stringify/test/anyof.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/fast-json-stringify/test/anyof.test.js new file mode 100644 index 0000000000000000000000000000000000000000..baa810609128f386a606a88b2850f425ed0bfe8f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/fast-json-stringify/test/anyof.test.js @@ -0,0 +1,792 @@ +'use strict' + +const { test } = require('node:test') +const build = require('..') + +process.env.TZ = 'UTC' + +test('object with multiple types field', (t) => { + t.plan(2) + + const schema = { + title: 'object with multiple types field', + type: 'object', + properties: { + str: { + anyOf: [{ + type: 'string' + }, { + type: 'boolean' + }] + } + } + } + const stringify = build(schema) + + t.assert.equal(stringify({ + str: 'string' + }), '{"str":"string"}') + + t.assert.equal(stringify({ + str: true + }), '{"str":true}') +}) + +test('object with field of type object or null', (t) => { + t.plan(2) + + const schema = { + title: 'object with field of type object or null', + type: 'object', + properties: { + prop: { + anyOf: [{ + type: 'object', + properties: { + str: { + type: 'string' + } + } + }, { + type: 'null' + }] + } + } + } + const stringify = build(schema) + + t.assert.equal(stringify({ + prop: null + }), '{"prop":null}') + + t.assert.equal(stringify({ + prop: { + str: 'string' + } + }), '{"prop":{"str":"string"}}') +}) + +test('object with field of type object or array', (t) => { + t.plan(2) + + const schema = { + title: 'object with field of type object or array', + type: 'object', + properties: { + prop: { + anyOf: [{ + type: 'object', + properties: {}, + additionalProperties: true + }, { + type: 'array', + items: { + type: 'string' + } + }] + } + } + } + const stringify = build(schema) + + t.assert.equal(stringify({ + prop: { + str: 'string' + } + }), '{"prop":{"str":"string"}}') + + t.assert.equal(stringify({ + prop: ['string'] + }), '{"prop":["string"]}') +}) + +test('object with field of type string and coercion disable ', (t) => { + t.plan(1) + + const schema = { + title: 'object with field of type string', + type: 'object', + properties: { + str: { + anyOf: [{ + type: 'string' + }] + } + } + } + const stringify = build(schema) + t.assert.throws(() => stringify({ str: 1 })) +}) + +test('object with field of type string and coercion enable ', (t) => { + t.plan(1) + + const schema = { + title: 'object with field of type string', + type: 'object', + properties: { + str: { + anyOf: [{ + type: 'string' + }] + } + } + } + + const options = { + ajv: { + coerceTypes: true + } + } + const stringify = build(schema, options) + + const value = stringify({ + str: 1 + }) + t.assert.equal(value, '{"str":"1"}') +}) + +test('object with field with type union of multiple objects', (t) => { + t.plan(2) + + const schema = { + title: 'object with anyOf property value containing objects', + type: 'object', + properties: { + anyOfSchema: { + anyOf: [ + { + type: 'object', + properties: { + baz: { type: 'number' } + }, + required: ['baz'] + }, + { + type: 'object', + properties: { + bar: { type: 'string' } + }, + required: ['bar'] + } + ] + } + }, + required: ['anyOfSchema'] + } + + const stringify = build(schema) + + t.assert.equal(stringify({ anyOfSchema: { baz: 5 } }), '{"anyOfSchema":{"baz":5}}') + + t.assert.equal(stringify({ anyOfSchema: { bar: 'foo' } }), '{"anyOfSchema":{"bar":"foo"}}') +}) + +test('null value in schema', (t) => { + t.plan(0) + + const schema = { + title: 'schema with null child', + type: 'string', + nullable: true, + enum: [null] + } + + build(schema) +}) + +test('symbol value in schema', (t) => { + t.plan(4) + + const ObjectKind = Symbol('LiteralKind') + const UnionKind = Symbol('UnionKind') + const LiteralKind = Symbol('LiteralKind') + + const schema = { + kind: ObjectKind, + type: 'object', + properties: { + value: { + kind: UnionKind, + anyOf: [ + { kind: LiteralKind, type: 'string', enum: ['foo'] }, + { kind: LiteralKind, type: 'string', enum: ['bar'] }, + { kind: LiteralKind, type: 'string', enum: ['baz'] } + ] + } + }, + required: ['value'] + } + + const stringify = build(schema) + t.assert.equal(stringify({ value: 'foo' }), '{"value":"foo"}') + t.assert.equal(stringify({ value: 'bar' }), '{"value":"bar"}') + t.assert.equal(stringify({ value: 'baz' }), '{"value":"baz"}') + t.assert.throws(() => stringify({ value: 'qux' })) +}) + +test('anyOf and $ref together', (t) => { + t.plan(2) + + const schema = { + type: 'object', + properties: { + cs: { + anyOf: [ + { + $ref: '#/definitions/Option' + }, + { + type: 'boolean' + } + ] + } + }, + definitions: { + Option: { + type: 'string' + } + } + } + + const stringify = build(schema) + + t.assert.equal(stringify({ cs: 'franco' }), '{"cs":"franco"}') + + t.assert.equal(stringify({ cs: true }), '{"cs":true}') +}) + +test('anyOf and $ref: 2 levels are fine', (t) => { + t.plan(1) + + const schema = { + type: 'object', + properties: { + cs: { + anyOf: [ + { + $ref: '#/definitions/Option' + }, + { + type: 'boolean' + } + ] + } + }, + definitions: { + Option: { + anyOf: [ + { + type: 'number' + }, + { + type: 'boolean' + } + ] + } + } + } + + const stringify = build(schema) + const value = stringify({ cs: 3 }) + t.assert.equal(value, '{"cs":3}') +}) + +test('anyOf and $ref: multiple levels should throw at build.', (t) => { + t.plan(3) + + const schema = { + type: 'object', + properties: { + cs: { + anyOf: [ + { + $ref: '#/definitions/Option' + }, + { + type: 'boolean' + } + ] + } + }, + definitions: { + Option: { + anyOf: [ + { + $ref: '#/definitions/Option2' + }, + { + type: 'string' + } + ] + }, + Option2: { + type: 'number' + } + } + } + + const stringify = build(schema) + + t.assert.equal(stringify({ cs: 3 }), '{"cs":3}') + t.assert.equal(stringify({ cs: true }), '{"cs":true}') + t.assert.equal(stringify({ cs: 'pippo' }), '{"cs":"pippo"}') +}) + +test('anyOf and $ref - multiple external $ref', (t) => { + t.plan(2) + + const externalSchema = { + external: { + definitions: { + def: { + type: 'object', + properties: { + prop: { anyOf: [{ $ref: 'external2#/definitions/other' }] } + } + } + } + }, + external2: { + definitions: { + internal: { + type: 'string' + }, + other: { + type: 'object', + properties: { + prop2: { $ref: '#/definitions/internal' } + } + } + } + } + } + + const schema = { + title: 'object with $ref', + type: 'object', + properties: { + obj: { + $ref: 'external#/definitions/def' + } + } + } + + const object = { + obj: { + prop: { + prop2: 'test' + } + } + } + + const stringify = build(schema, { schema: externalSchema }) + const output = stringify(object) + + t.assert.doesNotThrow(() => JSON.parse(output)) + t.assert.equal(output, '{"obj":{"prop":{"prop2":"test"}}}') +}) + +test('anyOf looks for all of the array items', (t) => { + t.plan(1) + + const schema = { + title: 'type array that may have any of declared items', + type: 'array', + items: { + anyOf: [ + { + type: 'object', + properties: { + savedId: { + type: 'string' + } + }, + required: ['savedId'] + }, + { + type: 'object', + properties: { + error: { + type: 'string' + } + }, + required: ['error'] + } + ] + } + } + const stringify = build(schema) + + const value = stringify([{ savedId: 'great' }, { error: 'oops' }]) + t.assert.equal(value, '[{"savedId":"great"},{"error":"oops"}]') +}) + +test('anyOf with enum with more than 100 entries', (t) => { + t.plan(1) + + const schema = { + title: 'type array that may have any of declared items', + type: 'array', + items: { + anyOf: [ + { + type: 'string', + enum: ['EUR', 'USD', ...(new Set([...new Array(200)].map(() => Math.random().toString(36).substr(2, 3)))).values()] + }, + { type: 'null' } + ] + } + } + const stringify = build(schema) + + const value = stringify(['EUR', 'USD', null]) + t.assert.equal(value, '["EUR","USD",null]') +}) + +test('anyOf object with field date-time of type string with format or null', (t) => { + t.plan(1) + const toStringify = new Date() + const withOneOfSchema = { + type: 'object', + properties: { + prop: { + anyOf: [{ + type: 'string', + format: 'date-time' + }, { + type: 'null' + }] + } + } + } + + const withOneOfStringify = build(withOneOfSchema) + + t.assert.equal(withOneOfStringify({ + prop: toStringify + }), `{"prop":"${toStringify.toISOString()}"}`) +}) + +test('anyOf object with nested field date-time of type string with format or null', (t) => { + t.plan(1) + const withOneOfSchema = { + type: 'object', + properties: { + prop: { + anyOf: [{ + type: 'object', + properties: { + nestedProp: { + type: 'string', + format: 'date-time' + } + } + }] + } + } + } + + const withOneOfStringify = build(withOneOfSchema) + + const data = { + prop: { nestedProp: new Date() } + } + + t.assert.equal(withOneOfStringify(data), JSON.stringify(data)) +}) + +test('anyOf object with nested field date of type string with format or null', (t) => { + t.plan(1) + const withOneOfSchema = { + type: 'object', + properties: { + prop: { + anyOf: [{ + type: 'object', + properties: { + nestedProp: { + type: 'string', + format: 'date' + } + } + }] + } + } + } + + const withOneOfStringify = build(withOneOfSchema) + + const data = { + prop: { nestedProp: new Date(1674263005800) } + } + + t.assert.equal(withOneOfStringify(data), '{"prop":{"nestedProp":"2023-01-21"}}') +}) + +test('anyOf object with nested field time of type string with format or null', (t) => { + t.plan(1) + const withOneOfSchema = { + type: 'object', + properties: { + prop: { + anyOf: [{ + type: 'object', + properties: { + nestedProp: { + type: 'string', + format: 'time' + } + } + }] + } + } + } + + const withOneOfStringify = build(withOneOfSchema) + + const data = { + prop: { nestedProp: new Date(1674263005800) } + } + t.assert.equal(withOneOfStringify(data), '{"prop":{"nestedProp":"01:03:25"}}') +}) + +test('anyOf object with field date of type string with format or null', (t) => { + t.plan(1) + const toStringify = '2011-01-01' + const withOneOfSchema = { + type: 'object', + properties: { + prop: { + anyOf: [{ + type: 'string', + format: 'date' + }, { + type: 'null' + }] + } + } + } + + const withOneOfStringify = build(withOneOfSchema) + t.assert.equal(withOneOfStringify({ + prop: toStringify + }), '{"prop":"2011-01-01"}') +}) + +test('anyOf object with invalid field date of type string with format or null', (t) => { + t.plan(1) + const toStringify = 'foo bar' + const withOneOfSchema = { + type: 'object', + properties: { + prop: { + anyOf: [{ + type: 'string', + format: 'date' + }, { + type: 'null' + }] + } + } + } + + const withOneOfStringify = build(withOneOfSchema) + t.assert.throws(() => withOneOfStringify({ prop: toStringify })) +}) + +test('anyOf with a nested external schema', (t) => { + t.plan(1) + + const externalSchemas = { + schema1: { + definitions: { + def1: { + $id: 'external', + type: 'string' + } + }, + type: 'number' + } + } + const schema = { anyOf: [{ $ref: 'external' }] } + + const stringify = build(schema, { schema: externalSchemas }) + t.assert.equal(stringify('foo'), '"foo"') +}) + +test('object with ref and validated properties', (t) => { + t.plan(1) + + const externalSchemas = { + RefSchema: { + $id: 'RefSchema', + type: 'string' + } + } + + const schema = { + $id: 'root', + type: 'object', + properties: { + id: { + anyOf: [ + { type: 'string' }, + { type: 'number' } + ] + }, + reference: { $ref: 'RefSchema' } + } + } + + const stringify = build(schema, { schema: externalSchemas }) + t.assert.equal(stringify({ id: 1, reference: 'hi' }), '{"id":1,"reference":"hi"}') +}) + +test('anyOf required props', (t) => { + t.plan(3) + + const schema = { + type: 'object', + properties: { + prop1: { type: 'string' }, + prop2: { type: 'string' }, + prop3: { type: 'string' } + }, + required: ['prop1'], + anyOf: [{ required: ['prop2'] }, { required: ['prop3'] }] + } + const stringify = build(schema) + t.assert.equal(stringify({ prop1: 'test', prop2: 'test2' }), '{"prop1":"test","prop2":"test2"}') + t.assert.equal(stringify({ prop1: 'test', prop3: 'test3' }), '{"prop1":"test","prop3":"test3"}') + t.assert.equal(stringify({ prop1: 'test', prop2: 'test2', prop3: 'test3' }), '{"prop1":"test","prop2":"test2","prop3":"test3"}') +}) + +test('anyOf required props', (t) => { + t.plan(3) + + const schema = { + type: 'object', + properties: { + prop1: { type: 'string' } + }, + anyOf: [ + { + properties: { + prop2: { type: 'string' } + } + }, + { + properties: { + prop3: { type: 'string' } + } + } + ] + } + const stringify = build(schema) + t.assert.equal(stringify({ prop1: 'test1' }), '{"prop1":"test1"}') + t.assert.equal(stringify({ prop2: 'test2' }), '{"prop2":"test2"}') + t.assert.equal(stringify({ prop1: 'test1', prop2: 'test2' }), '{"prop1":"test1","prop2":"test2"}') +}) + +test('recursive nested anyOfs', (t) => { + t.plan(1) + + const schema = { + type: 'object', + properties: { + foo: { + additionalProperties: false, + anyOf: [{ $ref: '#' }] + } + } + } + + const data = { foo: {} } + const stringify = build(schema) + t.assert.equal(stringify(data), JSON.stringify(data)) +}) + +test('recursive nested anyOfs', (t) => { + t.plan(1) + + const schema = { + type: 'object', + properties: { + foo: { + additionalProperties: false, + anyOf: [{ anyOf: [{ $ref: '#' }] }] + } + } + } + + const data = { foo: {} } + const stringify = build(schema) + t.assert.equal(stringify(data), JSON.stringify(data)) +}) + +test('external recursive anyOfs', (t) => { + t.plan(1) + + const externalSchema = { + type: 'object', + properties: { + foo: { + properties: { + bar: { type: 'string' } + }, + anyOf: [{ $ref: '#' }] + } + } + } + + const schema = { + type: 'object', + properties: { + a: { $ref: 'externalSchema#/properties/foo' }, + b: { $ref: 'externalSchema#/properties/foo' } + } + } + + const data = { + a: { + foo: {}, + bar: '42', + baz: 42 + }, + b: { + foo: {}, + bar: '42', + baz: 42 + } + } + const stringify = build(schema, { schema: { externalSchema } }) + t.assert.equal(stringify(data), '{"a":{"bar":"42","foo":{}},"b":{"bar":"42","foo":{}}}') +}) + +test('should build merged schemas twice', (t) => { + t.plan(2) + + const schema = { + type: 'object', + properties: { + enums: { + type: 'string', + anyOf: [ + { type: 'string', const: 'FOO' }, + { type: 'string', const: 'BAR' } + ] + } + } + } + + { + const stringify = build(schema) + t.assert.equal(stringify({ enums: 'FOO' }), '{"enums":"FOO"}') + } + + { + const stringify = build(schema) + t.assert.equal(stringify({ enums: 'BAR' }), '{"enums":"BAR"}') + } +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/fast-json-stringify/test/array.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/fast-json-stringify/test/array.test.js new file mode 100644 index 0000000000000000000000000000000000000000..dc64322615b625c9e5b3f0fcdf1f70ccfaf90e1e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/fast-json-stringify/test/array.test.js @@ -0,0 +1,638 @@ +'use strict' + +const { test } = require('node:test') +const validator = require('is-my-json-valid') +const build = require('..') +const Ajv = require('ajv') + +test('error on invalid largeArrayMechanism', (t) => { + t.plan(1) + + t.assert.throws(() => build({ + title: 'large array of null values with default mechanism', + type: 'object', + properties: { + ids: { + type: 'array', + items: { type: 'null' } + } + } + }, { + largeArraySize: 2e4, + largeArrayMechanism: 'invalid' + }), Error('Unsupported large array mechanism invalid')) +}) + +function buildTest (schema, toStringify, options) { + test(`render a ${schema.title} as JSON`, (t) => { + t.plan(3) + + const validate = validator(schema) + const stringify = build(schema, options) + const output = stringify(toStringify) + + t.assert.deepStrictEqual(JSON.parse(output), JSON.parse(JSON.stringify(toStringify))) + t.assert.equal(output, JSON.stringify(toStringify)) + t.assert.ok(validate(JSON.parse(output)), 'valid schema') + }) +} + +buildTest({ + title: 'dates tuple', + type: 'object', + properties: { + dates: { + type: 'array', + minItems: 2, + maxItems: 2, + items: [ + { + type: 'string', + format: 'date-time' + }, + { + type: 'string', + format: 'date-time' + } + ] + } + } +}, { + dates: [new Date(1), new Date(2)] +}) + +buildTest({ + title: 'string array', + type: 'object', + properties: { + ids: { + type: 'array', + items: { + type: 'string' + } + } + } +}, { + ids: ['test'] +}) + +buildTest({ + title: 'number array', + type: 'object', + properties: { + ids: { + type: 'array', + items: { + type: 'number' + } + } + } +}, { + ids: [1] +}) + +buildTest({ + title: 'mixed array', + type: 'object', + properties: { + ids: { + type: 'array', + items: [ + { + type: 'null' + }, + { + type: 'string' + }, + { + type: 'integer' + }, + { + type: 'number' + }, + { + type: 'boolean' + }, + { + type: 'object', + properties: { + a: { + type: 'string' + } + } + }, + { + type: 'array', + items: { + type: 'string' + } + } + ] + } + } +}, { + ids: [null, 'test', 1, 1.1, true, { a: 'test' }, ['test']] +}) + +buildTest({ + title: 'repeated types', + type: 'object', + properties: { + ids: { + type: 'array', + items: [ + { + type: 'number' + }, + { + type: 'number' + } + ] + } + } +}, { ids: [1, 2] }) + +buildTest({ + title: 'pattern properties array', + type: 'object', + properties: { + args: { + type: 'array', + items: [ + { + type: 'object', + patternProperties: { + '.*': { + type: 'string' + } + } + }, + { + type: 'object', + patternProperties: { + '.*': { + type: 'number' + } + } + } + ] + } + } +}, { args: [{ a: 'test' }, { b: 1 }] }) + +buildTest({ + title: 'array with weird key', + type: 'object', + properties: { + '@data': { + type: 'array', + items: { + type: 'string' + } + } + } +}, { + '@data': ['test'] +}) + +test('invalid items throw', (t) => { + t.plan(1) + const schema = { + type: 'object', + properties: { + args: { + type: 'array', + items: [ + { + type: 'object', + patternProperties: { + '.*': { + type: 'string' + } + } + } + ] + } + } + } + const stringify = build(schema) + t.assert.throws(() => stringify({ args: ['invalid'] })) +}) + +buildTest({ + title: 'item types in array default to any', + type: 'object', + properties: { + foo: { + type: 'array' + } + } +}, { + foo: [1, 'string', {}, null] +}) + +test('array items is a list of schema and additionalItems is true, just the described item is validated', (t) => { + t.plan(1) + + const schema = { + type: 'object', + properties: { + foo: { + type: 'array', + items: [ + { + type: 'string' + } + ], + additionalItems: true + } + } + } + + const stringify = build(schema) + const result = stringify({ + foo: [ + 'foo', + 'bar', + 1 + ] + }) + + t.assert.equal(result, '{"foo":["foo","bar",1]}') +}) + +test('array items is a list of schema and additionalItems is true, just the described item is validated', (t) => { + t.plan(1) + + const schema = { + type: 'object', + properties: { + foo: { + type: 'array', + items: [ + { + type: 'string' + }, + { + type: 'number' + } + ], + additionalItems: true + } + } + } + + const stringify = build(schema) + const result = stringify({ + foo: ['foo'] + }) + + t.assert.equal(result, '{"foo":["foo"]}') +}) + +test('array items is a list of schema and additionalItems is false /1', (t) => { + t.plan(1) + + const schema = { + type: 'object', + properties: { + foo: { + type: 'array', + items: [ + { type: 'string' } + ], + additionalItems: false + } + } + } + + const stringify = build(schema) + t.assert.throws(() => stringify({ foo: ['foo', 'bar'] }), new Error('Item at 1 does not match schema definition.')) +}) + +test('array items is a list of schema and additionalItems is false /2', (t) => { + t.plan(3) + + const schema = { + type: 'object', + properties: { + foo: { + type: 'array', + items: [ + { type: 'string' }, + { type: 'string' } + ], + additionalItems: false + } + } + } + + const stringify = build(schema) + + t.assert.throws(() => stringify({ foo: [1, 'bar'] }), new Error('Item at 0 does not match schema definition.')) + t.assert.throws(() => stringify({ foo: ['foo', 1] }), new Error('Item at 1 does not match schema definition.')) + t.assert.throws(() => stringify({ foo: ['foo', 'bar', 'baz'] }), new Error('Item at 2 does not match schema definition.')) +}) + +test('array items is a schema and additionalItems is false', (t) => { + t.plan(2) + + const schema = { + type: 'object', + properties: { + foo: { + type: 'array', + items: { type: 'string' }, + additionalItems: false + } + } + } + + const stringify = build(schema) + + // ajv ignores additionalItems if items is not an Array + const ajv = new Ajv({ allErrors: true, strict: false }) + + const validate = ajv.compile(schema) + t.assert.equal(stringify({ foo: ['foo', 'bar'] }), '{"foo":["foo","bar"]}') + t.assert.equal(validate({ foo: ['foo', 'bar'] }), true) +}) + +// https://github.com/fastify/fast-json-stringify/issues/279 +test('object array with anyOf and symbol', (t) => { + t.plan(1) + const ArrayKind = Symbol('ArrayKind') + const ObjectKind = Symbol('LiteralKind') + const UnionKind = Symbol('UnionKind') + const LiteralKind = Symbol('LiteralKind') + const StringKind = Symbol('StringKind') + + const schema = { + kind: ArrayKind, + type: 'array', + items: { + kind: ObjectKind, + type: 'object', + properties: { + name: { + kind: StringKind, + type: 'string' + }, + option: { + kind: UnionKind, + anyOf: [ + { + kind: LiteralKind, + type: 'string', + enum: ['Foo'] + }, + { + kind: LiteralKind, + type: 'string', + enum: ['Bar'] + } + ] + } + }, + required: ['name', 'option'] + } + } + const stringify = build(schema) + const value = stringify([ + { name: 'name-0', option: 'Foo' }, + { name: 'name-1', option: 'Bar' } + ]) + t.assert.equal(value, '[{"name":"name-0","option":"Foo"},{"name":"name-1","option":"Bar"}]') +}) + +test('different arrays with same item schemas', (t) => { + t.plan(1) + + const schema = { + type: 'object', + properties: { + array1: { + type: 'array', + items: [{ type: 'string' }], + additionalItems: false + }, + array2: { + type: 'array', + items: { $ref: '#/properties/array1/items' }, + additionalItems: true + } + } + } + + const stringify = build(schema) + const data = { array1: ['bar'], array2: ['foo', 'bar'] } + + t.assert.equal(stringify(data), '{"array1":["bar"],"array2":["foo","bar"]}') +}) + +const largeArray = new Array(2e4).fill({ a: 'test', b: 1 }) +buildTest({ + title: 'large array with default mechanism', + type: 'object', + properties: { + ids: { + type: 'array', + items: { + type: 'object', + properties: { + a: { type: 'string' }, + b: { type: 'number' } + } + } + } + } +}, { + ids: largeArray +}, { + largeArraySize: 2e4, + largeArrayMechanism: 'default' +}) + +buildTest({ + title: 'large array of objects with json-stringify mechanism', + type: 'object', + properties: { + ids: { + type: 'array', + items: { + type: 'object', + properties: { + a: { type: 'string' }, + b: { type: 'number' } + } + } + } + } +}, { + ids: largeArray +}, { + largeArrayMechanism: 'json-stringify' +}) + +buildTest({ + title: 'large array of strings with default mechanism', + type: 'object', + properties: { + ids: { + type: 'array', + items: { type: 'string' } + } + } +}, { + ids: new Array(2e4).fill('string') +}, { + largeArraySize: 2e4, + largeArrayMechanism: 'default' +}) + +buildTest({ + title: 'large array of numbers with default mechanism', + type: 'object', + properties: { + ids: { + type: 'array', + items: { type: 'number' } + } + } +}, { + ids: new Array(2e4).fill(42) +}, { + largeArraySize: 2e4, + largeArrayMechanism: 'default' +}) + +buildTest({ + title: 'large array of integers with default mechanism', + type: 'object', + properties: { + ids: { + type: 'array', + items: { type: 'integer' } + } + } +}, { + ids: new Array(2e4).fill(42) +}, { + largeArraySize: 2e4, + largeArrayMechanism: 'default' +}) + +buildTest({ + title: 'large array of booleans with default mechanism', + type: 'object', + properties: { + ids: { + type: 'array', + items: { type: 'boolean' } + } + } +}, { + ids: new Array(2e4).fill(true) +}, { + largeArraySize: 2e4, + largeArrayMechanism: 'default' +}) + +buildTest({ + title: 'large array of null values with default mechanism', + type: 'object', + properties: { + ids: { + type: 'array', + items: { type: 'null' } + } + } +}, { + ids: new Array(2e4).fill(null) +}, { + largeArraySize: 2e4, + largeArrayMechanism: 'default' +}) + +test('error on invalid value for largeArraySize /1', (t) => { + t.plan(1) + + t.assert.throws(() => build({ + title: 'large array of null values with default mechanism', + type: 'object', + properties: { + ids: { + type: 'array', + items: { type: 'null' } + } + } + }, { + largeArraySize: 'invalid' + }), Error('Unsupported large array size. Expected integer-like, got string with value invalid')) +}) + +test('error on invalid value for largeArraySize /2', (t) => { + t.plan(1) + + t.assert.throws(() => build({ + title: 'large array of null values with default mechanism', + type: 'object', + properties: { + ids: { + type: 'array', + items: { type: 'null' } + } + } + }, { + largeArraySize: Infinity + }), Error('Unsupported large array size. Expected integer-like, got number with value Infinity')) +}) + +test('error on invalid value for largeArraySize /3', (t) => { + t.plan(1) + + t.assert.throws(() => build({ + title: 'large array of null values with default mechanism', + type: 'object', + properties: { + ids: { + type: 'array', + items: { type: 'null' } + } + } + }, { + largeArraySize: [200] + }), Error('Unsupported large array size. Expected integer-like, got object with value 200')) +}) + +buildTest({ + title: 'large array of integers with largeArraySize is bigint', + type: 'object', + properties: { + ids: { + type: 'array', + items: { type: 'integer' } + } + } +}, { + ids: new Array(2e4).fill(42) +}, { + largeArraySize: 20000n, + largeArrayMechanism: 'default' +}) + +buildTest({ + title: 'large array of integers with largeArraySize is valid string', + type: 'object', + properties: { + ids: { + type: 'array', + items: { type: 'integer' } + } + } +}, { + ids: new Array(1e4).fill(42) +}, { + largeArraySize: '10000', + largeArrayMechanism: 'default' +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/fast-json-stringify/test/asNumber.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/fast-json-stringify/test/asNumber.test.js new file mode 100644 index 0000000000000000000000000000000000000000..94a40b4352900d25ae42fe8fd54d393b270548c0 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/fast-json-stringify/test/asNumber.test.js @@ -0,0 +1,13 @@ +'use strict' + +const { test } = require('node:test') + +test('asNumber should convert BigInt', (t) => { + t.plan(1) + const Serializer = require('../lib/serializer') + const serializer = new Serializer() + + const number = serializer.asNumber(11753021440n) + + t.assert.equal(number, '11753021440') +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/fast-json-stringify/test/basic.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/fast-json-stringify/test/basic.test.js new file mode 100644 index 0000000000000000000000000000000000000000..754f4489b24baa8df1b87826282538ca935e4f15 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/fast-json-stringify/test/basic.test.js @@ -0,0 +1,400 @@ +'use strict' + +const { test } = require('node:test') +const validator = require('is-my-json-valid') +const build = require('..') + +function buildTest (schema, toStringify) { + test(`render a ${schema.title} as JSON`, (t) => { + t.plan(3) + + const validate = validator(schema) + const stringify = build(schema) + const output = stringify(toStringify) + + t.assert.deepStrictEqual(JSON.parse(output), toStringify) + t.assert.equal(output, JSON.stringify(toStringify)) + t.assert.ok(validate(JSON.parse(output)), 'valid schema') + }) +} + +buildTest({ + title: 'string', + type: 'string', + format: 'unsafe' +}, 'hello world') + +buildTest({ + title: 'basic', + type: 'object', + properties: { + firstName: { + type: 'string' + }, + lastName: { + type: 'string' + }, + age: { + description: 'Age in years', + type: 'integer', + minimum: 0 + }, + magic: { + type: 'number' + } + }, + required: ['firstName', 'lastName'] +}, { + firstName: 'Matteo', + lastName: 'Collina', + age: 32, + magic: 42.42 +}) + +buildTest({ + title: 'string', + type: 'string' +}, 'hello world') + +buildTest({ + title: 'string', + type: 'string' +}, 'hello\nworld') + +buildTest({ + title: 'string with quotes', + type: 'string' +}, 'hello """" world') + +buildTest({ + title: 'boolean true', + type: 'boolean' +}, true) + +buildTest({ + title: 'boolean false', + type: 'boolean' +}, false) + +buildTest({ + title: 'an integer', + type: 'integer' +}, 42) + +buildTest({ + title: 'a number', + type: 'number' +}, 42.42) + +buildTest({ + title: 'deep', + type: 'object', + properties: { + firstName: { + type: 'string' + }, + lastName: { + type: 'string' + }, + more: { + description: 'more properties', + type: 'object', + properties: { + something: { + type: 'string' + } + } + } + } +}, { + firstName: 'Matteo', + lastName: 'Collina', + more: { + something: 'else' + } +}) + +buildTest({ + title: 'null', + type: 'null' +}, null) + +buildTest({ + title: 'deep object with weird keys', + type: 'object', + properties: { + '@version': { + type: 'integer' + } + } +}, { + '@version': 1 +}) + +buildTest({ + title: 'deep object with weird keys of type object', + type: 'object', + properties: { + '@data': { + type: 'object', + properties: { + id: { + type: 'string' + } + } + } + } +}, { + '@data': { + id: 'string' + } +}) + +buildTest({ + title: 'deep object with spaces in key', + type: 'object', + properties: { + 'spaces in key': { + type: 'object', + properties: { + something: { + type: 'integer' + } + } + } + } +}, { + 'spaces in key': { + something: 1 + } +}) + +buildTest({ + title: 'with null', + type: 'object', + properties: { + firstName: { + type: 'null' + } + } +}, { + firstName: null +}) + +buildTest({ + title: 'array with objects', + type: 'array', + items: { + type: 'object', + properties: { + name: { + type: 'string' + } + } + } +}, [{ + name: 'Matteo' +}, { + name: 'Dave' +}]) + +buildTest({ + title: 'array with strings', + type: 'array', + items: { + type: 'string' + } +}, [ + 'Matteo', + 'Dave' +]) + +buildTest({ + title: 'array with numbers', + type: 'array', + items: { + type: 'number' + } +}, [ + 42.42, + 24 +]) + +buildTest({ + title: 'array with integers', + type: 'array', + items: { + type: 'number' + } +}, [ + 42, + 24 +]) + +buildTest({ + title: 'nested array with objects', + type: 'object', + properties: { + data: { + type: 'array', + items: { + type: 'object', + properties: { + name: { + type: 'string' + } + } + } + } + } +}, { + data: [{ + name: 'Matteo' + }, { + name: 'Dave' + }] +}) + +buildTest({ + title: 'object with boolean', + type: 'object', + properties: { + readonly: { + type: 'boolean' + } + } +}, { + readonly: true +}) + +test('throw an error or coerce numbers and integers that are not numbers', (t) => { + const stringify = build({ + title: 'basic', + type: 'object', + properties: { + age: { + type: 'number' + }, + distance: { + type: 'integer' + } + } + }) + + t.assert.throws(() => { + stringify({ age: 'hello ', distance: 'long' }) + }, { message: 'The value "hello " cannot be converted to a number.' }) + + const result = stringify({ + age: '42', + distance: true + }) + + t.assert.deepStrictEqual(JSON.parse(result), { age: 42, distance: 1 }) +}) + +test('Should throw on invalid schema', t => { + t.plan(1) + t.assert.throws(() => { + build({ + type: 'Dinosaur', + properties: { + claws: { type: 'sharp' } + } + }) + }, { message: 'schema is invalid: data/properties/claws/type must be equal to one of the allowed values' }) +}) + +test('additionalProperties - throw on unknown type', (t) => { + t.plan(1) + + t.assert.throws(() => { + build({ + title: 'check array coerce', + type: 'object', + properties: {}, + additionalProperties: { + type: 'strangetype' + } + }) + t.fail('should be an invalid schema') + }, { message: 'schema is invalid: data/additionalProperties/type must be equal to one of the allowed values' }) +}) + +test('patternProperties - throw on unknown type', (t) => { + t.plan(1) + + t.assert.throws(() => { + build({ + title: 'check array coerce', + type: 'object', + properties: {}, + patternProperties: { + foo: { + type: 'strangetype' + } + } + }) + }, { message: 'schema is invalid: data/patternProperties/foo/type must be equal to one of the allowed values' }) +}) + +test('render a double quote as JSON /1', (t) => { + t.plan(2) + + const schema = { + type: 'string' + } + const toStringify = '" double quote' + + const validate = validator(schema) + const stringify = build(schema) + const output = stringify(toStringify) + + t.assert.equal(output, JSON.stringify(toStringify)) + t.assert.ok(validate(JSON.parse(output)), 'valid schema') +}) + +test('render a double quote as JSON /2', (t) => { + t.plan(2) + + const schema = { + type: 'string' + } + const toStringify = 'double quote " 2' + + const validate = validator(schema) + const stringify = build(schema) + const output = stringify(toStringify) + + t.assert.equal(output, JSON.stringify(toStringify)) + t.assert.ok(validate(JSON.parse(output)), 'valid schema') +}) + +test('render a long string', (t) => { + t.plan(2) + + const schema = { + type: 'string' + } + const toStringify = 'the Ultimate Question of Life, the Universe, and Everything.' + + const validate = validator(schema) + const stringify = build(schema) + const output = stringify(toStringify) + + t.assert.equal(output, JSON.stringify(toStringify)) + t.assert.ok(validate(JSON.parse(output)), 'valid schema') +}) + +test('returns JSON.stringify if schema type is boolean', t => { + t.plan(1) + + const schema = { + type: 'array', + items: true + } + + const array = [1, true, 'test'] + const stringify = build(schema) + t.assert.equal(stringify(array), JSON.stringify(array)) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/fast-json-stringify/test/bigint.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/fast-json-stringify/test/bigint.test.js new file mode 100644 index 0000000000000000000000000000000000000000..86bb4fa8e4af686d20574d6cf445defb6be4b24a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/fast-json-stringify/test/bigint.test.js @@ -0,0 +1,76 @@ +'use strict' + +const { test } = require('node:test') + +const build = require('..') + +test('render a bigint as JSON', (t) => { + t.plan(1) + + const schema = { + title: 'bigint', + type: 'integer' + } + + const stringify = build(schema) + const output = stringify(1615n) + + t.assert.equal(output, '1615') +}) + +test('render an object with a bigint as JSON', (t) => { + t.plan(1) + + const schema = { + title: 'object with bigint', + type: 'object', + properties: { + id: { + type: 'integer' + } + } + } + + const stringify = build(schema) + const output = stringify({ + id: 1615n + }) + + t.assert.equal(output, '{"id":1615}') +}) + +test('render an array with a bigint as JSON', (t) => { + t.plan(1) + + const schema = { + title: 'array with bigint', + type: 'array', + items: { + type: 'integer' + } + } + + const stringify = build(schema) + const output = stringify([1615n]) + + t.assert.equal(output, '[1615]') +}) + +test('render an object with an additionalProperty of type bigint as JSON', (t) => { + t.plan(1) + + const schema = { + title: 'object with bigint', + type: 'object', + additionalProperties: { + type: 'integer' + } + } + + const stringify = build(schema) + const output = stringify({ + num: 1615n + }) + + t.assert.equal(output, '{"num":1615}') +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/fast-json-stringify/test/clean-cache.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/fast-json-stringify/test/clean-cache.test.js new file mode 100644 index 0000000000000000000000000000000000000000..958fbcaa8504214c3d74b88cf5e28c48c4fa9233 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/fast-json-stringify/test/clean-cache.test.js @@ -0,0 +1,47 @@ +'use strict' + +const { test } = require('node:test') +const build = require('..') + +test('Should clean the cache', (t) => { + t.plan(1) + + const schema = { + $id: 'test', + type: 'string' + } + + t.assert.doesNotThrow(() => { + build(schema) + build(schema) + }) +}) + +test('Should clean the cache with external schemas', (t) => { + t.plan(1) + + const schema = { + $id: 'test', + definitions: { + def: { + type: 'object', + properties: { + str: { + type: 'string' + } + } + } + }, + type: 'object', + properties: { + obj: { + $ref: '#/definitions/def' + } + } + } + + t.assert.doesNotThrow(() => { + build(schema) + build(schema) + }) +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/fast-json-stringify/test/const.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/fast-json-stringify/test/const.test.js new file mode 100644 index 0000000000000000000000000000000000000000..48e105259d6b601a601b72cf6be385ac8835018d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/fast-json-stringify/test/const.test.js @@ -0,0 +1,314 @@ +'use strict' + +const { test } = require('node:test') +const validator = require('is-my-json-valid') +const build = require('..') + +test('schema with const string', (t) => { + t.plan(2) + + const schema = { + type: 'object', + properties: { + foo: { const: 'bar' } + } + } + + const validate = validator(schema) + const stringify = build(schema) + const output = stringify({ + foo: 'bar' + }) + + t.assert.equal(output, '{"foo":"bar"}') + t.assert.ok(validate(JSON.parse(output)), 'valid schema') +}) + +test('schema with const string and different input', (t) => { + t.plan(2) + + const schema = { + type: 'object', + properties: { + foo: { const: 'bar' } + } + } + + const validate = validator(schema) + const stringify = build(schema) + const output = stringify({ + foo: 'baz' + }) + + t.assert.equal(output, '{"foo":"bar"}') + t.assert.ok(validate(JSON.parse(output)), 'valid schema') +}) + +test('schema with const string and different type input', (t) => { + t.plan(2) + + const schema = { + type: 'object', + properties: { + foo: { const: 'bar' } + } + } + + const validate = validator(schema) + const stringify = build(schema) + const output = stringify({ + foo: 1 + }) + + t.assert.equal(output, '{"foo":"bar"}') + t.assert.ok(validate(JSON.parse(output)), 'valid schema') +}) + +test('schema with const string and no input', (t) => { + t.plan(2) + + const schema = { + type: 'object', + properties: { + foo: { const: 'bar' } + } + } + + const validate = validator(schema) + const stringify = build(schema) + const output = stringify({}) + + t.assert.equal(output, '{}') + t.assert.ok(validate(JSON.parse(output)), 'valid schema') +}) + +test('schema with const string that contains \'', (t) => { + t.plan(2) + + const schema = { + type: 'object', + properties: { + foo: { const: "'bar'" } + } + } + + const validate = validator(schema) + const stringify = build(schema) + const output = stringify({ + foo: "'bar'" + }) + + t.assert.equal(output, '{"foo":"\'bar\'"}') + t.assert.ok(validate(JSON.parse(output)), 'valid schema') +}) + +test('schema with const number', (t) => { + t.plan(2) + + const schema = { + type: 'object', + properties: { + foo: { const: 1 } + } + } + + const validate = validator(schema) + const stringify = build(schema) + const output = stringify({ + foo: 1 + }) + + t.assert.equal(output, '{"foo":1}') + t.assert.ok(validate(JSON.parse(output)), 'valid schema') +}) + +test('schema with const number and different input', (t) => { + t.plan(2) + + const schema = { + type: 'object', + properties: { + foo: { const: 1 } + } + } + + const validate = validator(schema) + const stringify = build(schema) + const output = stringify({ + foo: 2 + }) + + t.assert.equal(output, '{"foo":1}') + t.assert.ok(validate(JSON.parse(output)), 'valid schema') +}) + +test('schema with const bool', (t) => { + t.plan(2) + + const schema = { + type: 'object', + properties: { + foo: { const: true } + } + } + + const validate = validator(schema) + const stringify = build(schema) + const output = stringify({ + foo: true + }) + + t.assert.equal(output, '{"foo":true}') + t.assert.ok(validate(JSON.parse(output)), 'valid schema') +}) + +test('schema with const number', (t) => { + t.plan(2) + + const schema = { + type: 'object', + properties: { + foo: { const: 1 } + } + } + + const validate = validator(schema) + const stringify = build(schema) + const output = stringify({ + foo: 1 + }) + + t.assert.equal(output, '{"foo":1}') + t.assert.ok(validate(JSON.parse(output)), 'valid schema') +}) + +test('schema with const null', (t) => { + t.plan(2) + + const schema = { + type: 'object', + properties: { + foo: { const: null } + } + } + + const validate = validator(schema) + const stringify = build(schema) + const output = stringify({ + foo: null + }) + + t.assert.equal(output, '{"foo":null}') + t.assert.ok(validate(JSON.parse(output)), 'valid schema') +}) + +test('schema with const array', (t) => { + t.plan(2) + + const schema = { + type: 'object', + properties: { + foo: { const: [1, 2, 3] } + } + } + + const validate = validator(schema) + const stringify = build(schema) + const output = stringify({ + foo: [1, 2, 3] + }) + + t.assert.equal(output, '{"foo":[1,2,3]}') + t.assert.ok(validate(JSON.parse(output)), 'valid schema') +}) + +test('schema with const object', (t) => { + t.plan(2) + + const schema = { + type: 'object', + properties: { + foo: { const: { bar: 'baz' } } + } + } + + const validate = validator(schema) + const stringify = build(schema) + const output = stringify({ + foo: { bar: 'baz' } + }) + + t.assert.equal(output, '{"foo":{"bar":"baz"}}') + t.assert.ok(validate(JSON.parse(output)), 'valid schema') +}) + +test('schema with const and null as type', (t) => { + t.plan(4) + + const schema = { + type: 'object', + properties: { + foo: { type: ['string', 'null'], const: 'baz' } + } + } + + const validate = validator(schema) + const stringify = build(schema) + const output = stringify({ + foo: null + }) + + t.assert.equal(output, '{"foo":null}') + t.assert.ok(validate(JSON.parse(output)), 'valid schema') + + const output2 = stringify({ foo: 'baz' }) + t.assert.equal(output2, '{"foo":"baz"}') + t.assert.ok(validate(JSON.parse(output2)), 'valid schema') +}) + +test('schema with const as nullable', (t) => { + t.plan(4) + + const schema = { + type: 'object', + properties: { + foo: { nullable: true, const: 'baz' } + } + } + + const validate = validator(schema) + const stringify = build(schema) + const output = stringify({ + foo: null + }) + + t.assert.equal(output, '{"foo":null}') + t.assert.ok(validate(JSON.parse(output)), 'valid schema') + + const output2 = stringify({ + foo: 'baz' + }) + t.assert.equal(output2, '{"foo":"baz"}') + t.assert.ok(validate(JSON.parse(output2)), 'valid schema') +}) + +test('schema with const and invalid object', (t) => { + t.plan(2) + + const schema = { + type: 'object', + properties: { + foo: { const: { foo: 'bar' } } + }, + required: ['foo'] + } + + const validate = validator(schema) + const stringify = build(schema) + const result = stringify({ + foo: { foo: 'baz' } + }) + + t.assert.equal(result, '{"foo":{"foo":"bar"}}') + t.assert.ok(validate(JSON.parse(result)), 'valid schema') +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/fast-json-stringify/test/date.test.js b/novas/novacore-zephyr/claude-code-router/node_modules/fast-json-stringify/test/date.test.js new file mode 100644 index 0000000000000000000000000000000000000000..3d143fa836187fa30ef3784755fec4f890b2bf97 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/fast-json-stringify/test/date.test.js @@ -0,0 +1,639 @@ +'use strict' + +const { test } = require('node:test') +const validator = require('is-my-json-valid') +const build = require('..') + +process.env.TZ = 'UTC' + +test('render a date in a string as JSON', (t) => { + t.plan(2) + + const schema = { + title: 'a date in a string', + type: 'string' + } + const toStringify = new Date(1674263005800) + + const validate = validator(schema) + const stringify = build(schema) + const output = stringify(toStringify) + + t.assert.equal(output, JSON.stringify(toStringify)) + t.assert.ok(validate(JSON.parse(output)), 'valid schema') +}) + +test('render a date in a string when format is date-format as ISOString', (t) => { + t.plan(2) + + const schema = { + title: 'a date in a string', + type: 'string', + format: 'date-time' + } + const toStringify = new Date(1674263005800) + + const validate = validator(schema) + const stringify = build(schema) + const output = stringify(toStringify) + + t.assert.equal(output, JSON.stringify(toStringify)) + t.assert.ok(validate(JSON.parse(output)), 'valid schema') +}) + +test('render a nullable date in a string when format is date-format as ISOString', (t) => { + t.plan(2) + + const schema = { + title: 'a date in a string', + type: 'string', + format: 'date-time', + nullable: true + } + const toStringify = new Date(1674263005800) + + const validate = validator(schema) + const stringify = build(schema) + const output = stringify(toStringify) + + t.assert.equal(output, JSON.stringify(toStringify)) + t.assert.ok(validate(JSON.parse(output)), 'valid schema') +}) + +test('render a date in a string when format is date as YYYY-MM-DD', (t) => { + t.plan(2) + + const schema = { + title: 'a date in a string', + type: 'string', + format: 'date' + } + const toStringify = new Date(1674263005800) + + const validate = validator(schema) + const stringify = build(schema) + const output = stringify(toStringify) + + t.assert.equal(output, '"2023-01-21"') + t.assert.ok(validate(JSON.parse(output)), 'valid schema') +}) + +test('render a nullable date in a string when format is date as YYYY-MM-DD', (t) => { + t.plan(2) + + const schema = { + title: 'a date in a string', + type: 'string', + format: 'date', + nullable: true + } + const toStringify = new Date(1674263005800) + + const validate = validator(schema) + const stringify = build(schema) + const output = stringify(toStringify) + + t.assert.equal(output, '"2023-01-21"') + t.assert.ok(validate(JSON.parse(output)), 'valid schema') +}) + +test('verify padding for rendered date in a string when format is date', (t) => { + t.plan(2) + + const schema = { + title: 'a date in a string', + type: 'string', + format: 'date' + } + const toStringify = new Date(2020, 0, 1, 0, 0, 0, 0) + + const validate = validator(schema) + const stringify = build(schema) + const output = stringify(toStringify) + + t.assert.equal(output, '"2020-01-01"') + t.assert.ok(validate(JSON.parse(output)), 'valid schema') +}) + +test('render a date in a string when format is time as kk:mm:ss', (t) => { + t.plan(3) + + const schema = { + title: 'a date in a string', + type: 'string', + format: 'time' + } + const toStringify = new Date(1674263005800) + + const validate = validator(schema) + const stringify = build(schema) + const output = stringify(toStringify) + + validate(JSON.parse(output)) + t.assert.equal(validate.errors, null) + + t.assert.equal(output, '"01:03:25"') + t.assert.ok(validate(JSON.parse(output)), 'valid schema') +}) + +test('render a nullable date in a string when format is time as kk:mm:ss', (t) => { + t.plan(3) + + const schema = { + title: 'a date in a string', + type: 'string', + format: 'time', + nullable: true + } + const toStringify = new Date(1674263005800) + + const validate = validator(schema) + const stringify = build(schema) + const output = stringify(toStringify) + + validate(JSON.parse(output)) + t.assert.equal(validate.errors, null) + + t.assert.equal(output, '"01:03:25"') + t.assert.ok(validate(JSON.parse(output)), 'valid schema') +}) + +test('render a midnight time', (t) => { + t.plan(3) + + const schema = { + title: 'a date in a string', + type: 'string', + format: 'time' + } + const midnight = new Date(new Date(1674263005800).setHours(24)) + + const validate = validator(schema) + const stringify = build(schema) + const output = stringify(midnight) + + validate(JSON.parse(output)) + t.assert.equal(validate.errors, null) + + t.assert.equal(output, '"00:03:25"') + t.assert.ok(validate(JSON.parse(output)), 'valid schema') +}) + +test('verify padding for rendered date in a string when format is time', (t) => { + t.plan(3) + + const schema = { + title: 'a date in a string', + type: 'string', + format: 'time' + } + const toStringify = new Date(2020, 0, 1, 1, 1, 1, 1) + + const validate = validator(schema) + const stringify = build(schema) + const output = stringify(toStringify) + + validate(JSON.parse(output)) + t.assert.equal(validate.errors, null) + + t.assert.equal(output, '"01:01:01"') + t.assert.ok(validate(JSON.parse(output)), 'valid schema') +}) + +test('render a nested object in a string when type is date-format as ISOString', (t) => { + t.plan(2) + + const schema = { + title: 'an object in a string', + type: 'object', + properties: { + date: { + type: 'string', + format: 'date-time' + } + } + } + const toStringify = { date: new Date(1674263005800) } + + const validate = validator(schema) + const stringify = build(schema) + const output = stringify(toStringify) + + t.assert.equal(output, JSON.stringify(toStringify)) + t.assert.ok(validate(JSON.parse(output)), 'valid schema') +}) + +test('serializing null value', async t => { + const input = { updatedAt: null } + + function createSchema (properties) { + return { + title: 'an object in a string', + type: 'object', + properties + } + } + + function serialize (schema, input) { + const validate = validator(schema) + const stringify = build(schema) + const output = stringify(input) + + return { + validate, + output + } + } + + t.plan(3) + + await t.test('type::string', async t => { + t.plan(3) + + await t.test('format::date-time', t => { + t.plan(2) + + const prop = { + updatedAt: { + type: 'string', + format: 'date-time' + } + } + + const { + output, + validate + } = serialize(createSchema(prop), input) + + t.assert.equal(output, '{"updatedAt":""}') + t.assert.equal(validate(JSON.parse(output)), false, 'an empty string is not a date-time format') + }) + + await t.test('format::date', t => { + t.plan(2) + + const prop = { + updatedAt: { + type: 'string', + format: 'date' + } + } + + const { + output, + validate + } = serialize(createSchema(prop), input) + + t.assert.equal(output, '{"updatedAt":""}') + t.assert.equal(validate(JSON.parse(output)), false, 'an empty string is not a date format') + }) + + await t.test('format::time', t => { + t.plan(2) + + const prop = { + updatedAt: { + type: 'string', + format: 'time' + } + } + + const { + output, + validate + } = serialize(createSchema(prop), input) + + t.assert.equal(output, '{"updatedAt":""}') + t.assert.equal(validate(JSON.parse(output)), false, 'an empty string is not a time format') + }) + }) + + await t.test('type::array', async t => { + t.plan(6) + + await t.test('format::date-time', t => { + t.plan(2) + + const prop = { + updatedAt: { + type: ['string'], + format: 'date-time' + } + } + + const { + output, + validate + } = serialize(createSchema(prop), input) + + t.assert.equal(output, '{"updatedAt":""}') + t.assert.equal(validate(JSON.parse(output)), false, 'an empty string is not a date-time format') + }) + + await t.test('format::date', t => { + t.plan(2) + + const prop = { + updatedAt: { + type: ['string'], + format: 'date' + } + } + + const { + output, + validate + } = serialize(createSchema(prop), input) + + t.assert.equal(output, '{"updatedAt":""}') + t.assert.equal(validate(JSON.parse(output)), false, 'an empty string is not a date format') + }) + + await t.test('format::date', t => { + t.plan(2) + + const prop = { + updatedAt: { + type: ['string'], + format: 'date' + } + } + + const { + output, + validate + } = serialize(createSchema(prop), input) + + t.assert.equal(output, '{"updatedAt":""}') + t.assert.equal(validate(JSON.parse(output)), false, 'an empty string is not a date format') + }) + + await t.test('format::time, Date object', t => { + t.plan(1) + + const schema = { + oneOf: [ + { + type: 'object', + properties: { + updatedAt: { + type: ['string', 'number'], + format: 'time' + } + } + } + ] + } + + const date = new Date(1674263005800) + const input = { updatedAt: date } + const { output } = serialize(schema, input) + + t.assert.equal(output, JSON.stringify({ updatedAt: '01:03:25' })) + }) + + await t.test('format::time, Date object', t => { + t.plan(1) + + const schema = { + oneOf: [ + { + type: ['string', 'number'], + format: 'time' + } + ] + } + + const date = new Date(1674263005800) + const { output } = serialize(schema, date) + + t.assert.equal(output, '"01:03:25"') + }) + + await t.test('format::time, Date object', t => { + t.plan(1) + + const schema = { + oneOf: [ + { + type: ['string', 'number'], + format: 'time' + } + ] + } + + const { output } = serialize(schema, 42) + + t.assert.equal(output, JSON.stringify(42)) + }) + }) + + await t.test('type::array::nullable', async t => { + t.plan(3) + + await t.test('format::date-time', t => { + t.plan(2) + + const prop = { + updatedAt: { + type: ['string', 'null'], + format: 'date-time' + } + } + + const { + output, + validate + } = serialize(createSchema(prop), input) + + t.assert.equal(output, '{"updatedAt":null}') + t.assert.ok(validate(JSON.parse(output)), 'valid schema') + }) + + await t.test('format::date', t => { + t.plan(2) + + const prop = { + updatedAt: { + type: ['string', 'null'], + format: 'date' + } + } + + const { + output, + validate + } = serialize(createSchema(prop), input) + + t.assert.equal(output, '{"updatedAt":null}') + t.assert.ok(validate(JSON.parse(output)), 'valid schema') + }) + + await t.test('format::time', t => { + t.plan(2) + + const prop = { + updatedAt: { + type: ['string', 'null'], + format: 'time' + } + } + + const { + output, + validate + } = serialize(createSchema(prop), input) + + t.assert.equal(output, '{"updatedAt":null}') + t.assert.ok(validate(JSON.parse(output)), 'valid schema') + }) + }) +}) + +test('Validate Date object as string type', (t) => { + t.plan(1) + + const schema = { + oneOf: [ + { type: 'string' } + ] + } + const toStringify = new Date(1674263005800) + + const stringify = build(schema) + const output = stringify(toStringify) + + t.assert.equal(output, JSON.stringify(toStringify)) +}) + +test('nullable date', (t) => { + t.plan(1) + + const schema = { + anyOf: [ + { + format: 'date', + type: 'string', + nullable: true + } + ] + } + + const stringify = build(schema) + + const data = new Date(1674263005800) + const result = stringify(data) + + t.assert.equal(result, '"2023-01-21"') +}) + +test('non-date format should not affect data serialization (issue #491)', (t) => { + t.plan(1) + + const schema = { + type: 'object', + properties: { + hello: { + type: 'string', + format: 'int64', + pattern: '^[0-9]*$' + } + } + } + + const stringify = build(schema) + const data = { hello: 123n } + t.assert.equal(stringify(data), '{"hello":"123"}') +}) + +test('should serialize also an invalid string value, even if it is not a valid date', (t) => { + t.plan(2) + + const schema = { + title: 'a date in a string', + type: 'string', + format: 'date-time', + nullable: true + } + const toStringify = 'invalid' + + const validate = validator(schema) + const stringify = build(schema) + const output = stringify(toStringify) + + t.assert.equal(output, JSON.stringify(toStringify)) + t.assert.equal(validate(JSON.parse(output)), false, 'valid schema') +}) + +test('should throw an error if value can not be transformed to date-time', (t) => { + t.plan(2) + + const schema = { + title: 'a date in a string', + type: 'string', + format: 'date-time', + nullable: true + } + const toStringify = true + + const validate = validator(schema) + const stringify = build(schema) + + t.assert.throws(() => stringify(toStringify), new Error('The value "true" cannot be converted to a date-time.')) + t.assert.equal(validate(toStringify), false) +}) + +test('should throw an error if value can not be transformed to date', (t) => { + t.plan(2) + + const schema = { + title: 'a date in a string', + type: 'string', + format: 'date', + nullable: true + } + const toStringify = true + + const validate = validator(schema) + const stringify = build(schema) + + t.assert.throws(() => stringify(toStringify), new Error('The value "true" cannot be converted to a date.')) + t.assert.equal(validate(toStringify), false) +}) + +test('should throw an error if value can not be transformed to time', (t) => { + t.plan(2) + + const schema = { + title: 'a time in a string', + type: 'string', + format: 'time', + nullable: true + } + const toStringify = true + + const validate = validator(schema) + const stringify = build(schema) + + t.assert.throws(() => stringify(toStringify), new Error('The value "true" cannot be converted to a time.')) + t.assert.equal(validate(toStringify), false) +}) + +test('should serialize also an invalid string value, even if it is not a valid time', (t) => { + t.plan(2) + + const schema = { + title: 'a time in a string', + type: 'string', + format: 'time', + nullable: true + } + const toStringify = 'invalid' + + const validate = validator(schema) + const stringify = build(schema) + const output = stringify(toStringify) + + t.assert.equal(output, JSON.stringify(toStringify)) + t.assert.equal(validate(JSON.parse(output)), false, 'valid schema') +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/authclient.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/authclient.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..823dbccb2879d7f1f3a43f141f5a1c53432cb92e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/authclient.d.ts @@ -0,0 +1,298 @@ +import { EventEmitter } from 'events'; +import { Gaxios, GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios'; +import { Credentials } from './credentials'; +import { OriginalAndCamel } from '../util'; +/** + * An interface for enforcing `fetch`-type compliance. + * + * @remarks + * + * This provides type guarantees during build-time, ensuring the `fetch` method is 1:1 + * compatible with the `Gaxios#fetch` API. + */ +interface GaxiosFetchCompliance { + fetch: typeof fetch | Gaxios['fetch']; +} +/** + * Easy access to symbol-indexed strings on config objects. + */ +export type SymbolIndexString = { + [key: symbol]: string | undefined; +}; +/** + * Base auth configurations (e.g. from JWT or `.json` files) with conventional + * camelCased options. + * + * @privateRemarks + * + * This interface is purposely not exported so that it can be removed once + * {@link https://github.com/microsoft/TypeScript/issues/50715} has been + * resolved. Then, we can use {@link OriginalAndCamel} to shrink this interface. + * + * Tracking: {@link https://github.com/googleapis/google-auth-library-nodejs/issues/1686} + */ +interface AuthJSONOptions { + /** + * The project ID corresponding to the current credentials if available. + */ + project_id: string | null; + /** + * An alias for {@link AuthJSONOptions.project_id `project_id`}. + */ + projectId: AuthJSONOptions['project_id']; + /** + * The quota project ID. The quota project can be used by client libraries for the billing purpose. + * See {@link https://cloud.google.com/docs/quota Working with quotas} + */ + quota_project_id: string; + /** + * An alias for {@link AuthJSONOptions.quota_project_id `quota_project_id`}. + */ + quotaProjectId: AuthJSONOptions['quota_project_id']; + /** + * The default service domain for a given Cloud universe. + * + * @example + * 'googleapis.com' + */ + universe_domain: string; + /** + * An alias for {@link AuthJSONOptions.universe_domain `universe_domain`}. + */ + universeDomain: AuthJSONOptions['universe_domain']; +} +/** + * Base `AuthClient` configuration. + * + * The camelCased options are aliases of the snake_cased options, supporting both + * JSON API and JS conventions. + */ +export interface AuthClientOptions extends Partial> { + /** + * An API key to use, optional. + */ + apiKey?: string; + credentials?: Credentials; + /** + * The {@link Gaxios `Gaxios`} instance used for making requests. + * + * @see {@link AuthClientOptions.useAuthRequestParameters} + */ + transporter?: Gaxios; + /** + * Provides default options to the transporter, such as {@link GaxiosOptions.agent `agent`} or + * {@link GaxiosOptions.retryConfig `retryConfig`}. + * + * This option is ignored if {@link AuthClientOptions.transporter `gaxios`} has been provided + */ + transporterOptions?: GaxiosOptions; + /** + * The expiration threshold in milliseconds before forcing token refresh of + * unexpired tokens. + */ + eagerRefreshThresholdMillis?: number; + /** + * Whether to attempt to refresh tokens on status 401/403 responses + * even if an attempt is made to refresh the token preemptively based + * on the expiry_date. + */ + forceRefreshOnFailure?: boolean; + /** + * Enables/disables the adding of the AuthClient's default interceptor. + * + * @see {@link AuthClientOptions.transporter} + * + * @remarks + * + * Disabling is useful for debugging and experimentation. + * + * @default true + */ + useAuthRequestParameters?: boolean; +} +/** + * The default cloud universe + * + * @see {@link AuthJSONOptions.universe_domain} + */ +export declare const DEFAULT_UNIVERSE = "googleapis.com"; +/** + * The default {@link AuthClientOptions.eagerRefreshThresholdMillis} + */ +export declare const DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS: number; +/** + * Defines the root interface for all clients that generate credentials + * for calling Google APIs. All clients should implement this interface. + */ +export interface CredentialsClient { + projectId?: AuthClientOptions['projectId']; + eagerRefreshThresholdMillis: NonNullable; + forceRefreshOnFailure: NonNullable; + /** + * @return A promise that resolves with the current GCP access token + * response. If the current credential is expired, a new one is retrieved. + */ + getAccessToken(): Promise; + /** + * 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 ' } + * @param url The URI being authorized. + */ + getRequestHeaders(url?: string | URL): Promise; + /** + * Provides an alternative Gaxios request implementation with auth credentials + */ + request(opts: GaxiosOptions): GaxiosPromise; + /** + * Sets the auth credentials. + */ + setCredentials(credentials: Credentials): void; + /** + * Subscribes a listener to the tokens event triggered when a token is + * generated. + * + * @param event The tokens event to subscribe to. + * @param listener The listener that triggers on event trigger. + * @return The current client instance. + */ + on(event: 'tokens', listener: (tokens: Credentials) => void): this; +} +export declare interface AuthClient { + on(event: 'tokens', listener: (tokens: Credentials) => void): this; +} +/** + * The base of all Auth Clients. + */ +export declare abstract class AuthClient extends EventEmitter implements CredentialsClient, GaxiosFetchCompliance { + apiKey?: string; + projectId?: string | null; + /** + * The quota project ID. The quota project can be used by client libraries for the billing purpose. + * See {@link https://cloud.google.com/docs/quota Working with quotas} + */ + quotaProjectId?: string; + /** + * The {@link Gaxios `Gaxios`} instance used for making requests. + */ + transporter: Gaxios; + credentials: Credentials; + eagerRefreshThresholdMillis: number; + forceRefreshOnFailure: boolean; + universeDomain: string; + /** + * Symbols that can be added to GaxiosOptions to specify the method name that is + * making an RPC call, for logging purposes, as well as a string ID that can be + * used to correlate calls and responses. + */ + static readonly RequestMethodNameSymbol: unique symbol; + static readonly RequestLogIdSymbol: unique symbol; + constructor(opts?: AuthClientOptions); + /** + * A {@link fetch `fetch`} compliant API for {@link AuthClient}. + * + * @see {@link AuthClient.request} for the classic method. + * + * @remarks + * + * This is useful as a drop-in replacement for `fetch` API usage. + * + * @example + * + * ```ts + * const authClient = new AuthClient(); + * const fetchWithAuthClient: typeof fetch = (...args) => authClient.fetch(...args); + * await fetchWithAuthClient('https://example.com'); + * ``` + * + * @param args `fetch` API or {@link Gaxios.fetch `Gaxios#fetch`} parameters + * @returns the {@link GaxiosResponse} with Gaxios-added properties + */ + fetch(...args: Parameters): GaxiosPromise; + /** + * The public request API in which credentials may be added to the request. + * + * @see {@link AuthClient.fetch} for the modern method. + * + * @param options options for `gaxios` + */ + abstract request(options: GaxiosOptions): GaxiosPromise; + /** + * 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: + * ```ts + * new Headers({'authorization': 'Bearer '}); + * ``` + * + * @param url The URI being authorized. + */ + abstract getRequestHeaders(url?: string | URL): Promise; + /** + * @return A promise that resolves with the current GCP access token + * response. If the current credential is expired, a new one is retrieved. + */ + abstract getAccessToken(): Promise<{ + token?: string | null; + res?: GaxiosResponse | null; + }>; + /** + * Sets the auth credentials. + */ + setCredentials(credentials: Credentials): void; + /** + * 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. + */ + protected addSharedMetadataHeaders(headers: Headers): Headers; + /** + * Adds the `x-goog-user-project` and `authorization` headers to the target Headers + * object, if they exist on the source. + * + * @param target the headers to target + * @param source the headers to source from + * @returns the target headers + */ + protected addUserProjectAndAuthHeaders(target: T, source: Headers): T; + static log: import("google-logging-utils").AdhocDebugLogFunction; + static readonly DEFAULT_REQUEST_INTERCEPTOR: Parameters[0]; + static readonly DEFAULT_RESPONSE_INTERCEPTOR: Parameters[0]; + /** + * Sets the method name that is making a Gaxios request, so that logging may tag + * log lines with the operation. + * @param config A Gaxios request config + * @param methodName The method name making the call + */ + static setMethodName(config: GaxiosOptions, methodName: string): void; + /** + * 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. + */ + protected static get RETRY_CONFIG(): GaxiosOptions; +} +export type HeadersInit = ConstructorParameters[0]; +export interface GetAccessTokenResponse { + token?: string | null; + res?: GaxiosResponse | null; +} +/** + * @deprecated - use the Promise API instead + */ +export interface BodyResponseCallback { + (err: Error | null, res?: GaxiosResponse | null): void; +} +export {}; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/authclient.js b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/authclient.js new file mode 100644 index 0000000000000000000000000000000000000000..9c22bd51eb852f85ee5e57cf3c9799b10c908c4a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/authclient.js @@ -0,0 +1,286 @@ +"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 util_1 = require("../util"); +const google_logging_utils_1 = require("google-logging-utils"); +const shared_cjs_1 = require("../shared.cjs"); +/** + * 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; +/** + * The base of all Auth Clients. + */ +class AuthClient extends events_1.EventEmitter { + apiKey; + projectId; + /** + * The quota project ID. The quota project can be used by client libraries for the billing purpose. + * See {@link https://cloud.google.com/docs/quota Working with quotas} + */ + quotaProjectId; + /** + * The {@link Gaxios `Gaxios`} instance used for making requests. + */ + transporter; + credentials = {}; + eagerRefreshThresholdMillis = exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS; + forceRefreshOnFailure = false; + universeDomain = exports.DEFAULT_UNIVERSE; + /** + * Symbols that can be added to GaxiosOptions to specify the method name that is + * making an RPC call, for logging purposes, as well as a string ID that can be + * used to correlate calls and responses. + */ + static RequestMethodNameSymbol = Symbol('request method name'); + static RequestLogIdSymbol = Symbol('request log id'); + constructor(opts = {}) { + super(); + const options = (0, util_1.originalOrCamelOptions)(opts); + // Shared auth options + this.apiKey = opts.apiKey; + this.projectId = options.get('project_id') ?? null; + this.quotaProjectId = options.get('quota_project_id'); + this.credentials = options.get('credentials') ?? {}; + this.universeDomain = options.get('universe_domain') ?? exports.DEFAULT_UNIVERSE; + // Shared client options + this.transporter = opts.transporter ?? new gaxios_1.Gaxios(opts.transporterOptions); + if (options.get('useAuthRequestParameters') !== false) { + this.transporter.interceptors.request.add(AuthClient.DEFAULT_REQUEST_INTERCEPTOR); + this.transporter.interceptors.response.add(AuthClient.DEFAULT_RESPONSE_INTERCEPTOR); + } + if (opts.eagerRefreshThresholdMillis) { + this.eagerRefreshThresholdMillis = opts.eagerRefreshThresholdMillis; + } + this.forceRefreshOnFailure = opts.forceRefreshOnFailure ?? false; + } + /** + * A {@link fetch `fetch`} compliant API for {@link AuthClient}. + * + * @see {@link AuthClient.request} for the classic method. + * + * @remarks + * + * This is useful as a drop-in replacement for `fetch` API usage. + * + * @example + * + * ```ts + * const authClient = new AuthClient(); + * const fetchWithAuthClient: typeof fetch = (...args) => authClient.fetch(...args); + * await fetchWithAuthClient('https://example.com'); + * ``` + * + * @param args `fetch` API or {@link Gaxios.fetch `Gaxios#fetch`} parameters + * @returns the {@link GaxiosResponse} with Gaxios-added properties + */ + fetch(...args) { + // Up to 2 parameters in either overload + const input = args[0]; + const init = args[1]; + let url = undefined; + const headers = new Headers(); + // prepare URL + if (typeof input === 'string') { + url = new URL(input); + } + else if (input instanceof URL) { + url = input; + } + else if (input && input.url) { + url = new URL(input.url); + } + // prepare headers + if (input && typeof input === 'object' && 'headers' in input) { + gaxios_1.Gaxios.mergeHeaders(headers, input.headers); + } + if (init) { + gaxios_1.Gaxios.mergeHeaders(headers, new Headers(init.headers)); + } + // prepare request + if (typeof input === 'object' && !(input instanceof URL)) { + // input must have been a non-URL object + return this.request({ ...init, ...input, headers, url }); + } + else { + // input must have been a string or URL + return this.request({ ...init, headers, url }); + } + } + /** + * 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.has('x-goog-user-project') && // don't override a value the user sets. + this.quotaProjectId) { + headers.set('x-goog-user-project', this.quotaProjectId); + } + return headers; + } + /** + * Adds the `x-goog-user-project` and `authorization` headers to the target Headers + * object, if they exist on the source. + * + * @param target the headers to target + * @param source the headers to source from + * @returns the target headers + */ + addUserProjectAndAuthHeaders(target, source) { + const xGoogUserProject = source.get('x-goog-user-project'); + const authorizationHeader = source.get('authorization'); + if (xGoogUserProject) { + target.set('x-goog-user-project', xGoogUserProject); + } + if (authorizationHeader) { + target.set('authorization', authorizationHeader); + } + return target; + } + static log = (0, google_logging_utils_1.log)('auth'); + static DEFAULT_REQUEST_INTERCEPTOR = { + resolved: async (config) => { + // Set `x-goog-api-client`, if not already set + if (!config.headers.has('x-goog-api-client')) { + const nodeVersion = process.version.replace(/^v/, ''); + config.headers.set('x-goog-api-client', `gl-node/${nodeVersion}`); + } + // Set `User-Agent` + const userAgent = config.headers.get('User-Agent'); + if (!userAgent) { + config.headers.set('User-Agent', shared_cjs_1.USER_AGENT); + } + else if (!userAgent.includes(`${shared_cjs_1.PRODUCT_NAME}/`)) { + config.headers.set('User-Agent', `${userAgent} ${shared_cjs_1.USER_AGENT}`); + } + try { + const symbols = config; + const methodName = symbols[AuthClient.RequestMethodNameSymbol]; + // This doesn't need to be very unique or interesting, it's just an aid for + // matching requests to responses. + const logId = `${Math.floor(Math.random() * 1000)}`; + symbols[AuthClient.RequestLogIdSymbol] = logId; + // Boil down the object we're printing out. + const logObject = { + url: config.url, + headers: config.headers, + }; + if (methodName) { + AuthClient.log.info('%s [%s] request %j', methodName, logId, logObject); + } + else { + AuthClient.log.info('[%s] request %j', logId, logObject); + } + } + catch (e) { + // Logging must not create new errors; swallow them all. + } + return config; + }, + }; + static DEFAULT_RESPONSE_INTERCEPTOR = { + resolved: async (response) => { + try { + const symbols = response.config; + const methodName = symbols[AuthClient.RequestMethodNameSymbol]; + const logId = symbols[AuthClient.RequestLogIdSymbol]; + if (methodName) { + AuthClient.log.info('%s [%s] response %j', methodName, logId, response.data); + } + else { + AuthClient.log.info('[%s] response %j', logId, response.data); + } + } + catch (e) { + // Logging must not create new errors; swallow them all. + } + return response; + }, + rejected: async (error) => { + try { + const symbols = error.config; + const methodName = symbols[AuthClient.RequestMethodNameSymbol]; + const logId = symbols[AuthClient.RequestLogIdSymbol]; + if (methodName) { + AuthClient.log.info('%s [%s] error %j', methodName, logId, error.response?.data); + } + else { + AuthClient.log.error('[%s] error %j', logId, error.response?.data); + } + } + catch (e) { + // Logging must not create new errors; swallow them all. + } + // Re-throw the error. + throw error; + }, + }; + /** + * Sets the method name that is making a Gaxios request, so that logging may tag + * log lines with the operation. + * @param config A Gaxios request config + * @param methodName The method name making the call + */ + static setMethodName(config, methodName) { + try { + const symbols = config; + symbols[AuthClient.RequestMethodNameSymbol] = methodName; + } + catch (e) { + // Logging must not create new errors; swallow them all. + } + } + /** + * 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; +//# sourceMappingURL=authclient.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/awsclient.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/awsclient.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e97a791c211f8bbe222cc15b33200c24ed0be3da --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/awsclient.d.ts @@ -0,0 +1,115 @@ +import { AwsSecurityCredentials } from './awsrequestsigner'; +import { BaseExternalAccountClient, BaseExternalAccountClientOptions, ExternalAccountSupplierContext } from './baseexternalclient'; +import { SnakeToCamelObject } from '../util'; +/** + * AWS credentials JSON interface. This is used for AWS workloads. + */ +export interface AwsClientOptions extends BaseExternalAccountClientOptions { + /** + * Object containing options to retrieve AWS security credentials. A valid credential + * source or a aws security credentials supplier should be specified. + */ + credential_source?: { + /** + * AWS environment ID. Currently only 'AWS1' is supported. + */ + environment_id: string; + /** + * The EC2 metadata URL to retrieve the current AWS region from. If this is + * not provided, the region should be present in the AWS_REGION or AWS_DEFAULT_REGION + * environment variables. + */ + region_url?: string; + /** + * The EC2 metadata URL to retrieve AWS security credentials. If this is not provided, + * the credentials should be present in the AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, + * and AWS_SESSION_TOKEN environment variables. + */ + url?: string; + /** + * The regional GetCallerIdentity action URL, used to determine the account + * ID and its roles. + */ + regional_cred_verification_url: string; + /** + * The imdsv2 session token url is used to fetch session token from AWS + * which is later sent through headers for metadata requests. If the + * field is missing, then session token won't be fetched and sent with + * the metadata requests. + * The session token is required for IMDSv2 but optional for IMDSv1 + */ + imdsv2_session_token_url?: string; + }; + /** + * The AWS security credentials supplier to call to retrieve the AWS region + * and AWS security credentials. Either this or a valid credential source + * must be specified. + */ + aws_security_credentials_supplier?: AwsSecurityCredentialsSupplier; +} +/** + * Supplier interface for AWS security credentials. This can be implemented to + * return an AWS region and AWS security credentials. These credentials can + * then be exchanged for a GCP token by an {@link AwsClient}. + */ +export interface AwsSecurityCredentialsSupplier { + /** + * Gets the active AWS region. + * @param context {@link ExternalAccountSupplierContext} from the calling + * {@link AwsClient}, contains the requested audience and subject token type + * for the external account identity as well as the transport from the + * calling client to use for requests. + * @return A promise that resolves with the AWS region string. + */ + getAwsRegion: (context: ExternalAccountSupplierContext) => Promise; + /** + * Gets valid AWS security credentials for the requested external account + * identity. Note that these are not cached by the calling {@link AwsClient}, + * so caching should be including in the implementation. + * @param context {@link ExternalAccountSupplierContext} from the calling + * {@link AwsClient}, contains the requested audience and subject token type + * for the external account identity as well as the transport from the + * calling client to use for requests. + * @return A promise that resolves with the requested {@link AwsSecurityCredentials}. + */ + getAwsSecurityCredentials: (context: ExternalAccountSupplierContext) => Promise; +} +/** + * AWS external account client. This is used for AWS workloads, where + * AWS STS GetCallerIdentity serialized signed requests are exchanged for + * GCP access token. + */ +export declare class AwsClient extends BaseExternalAccountClient { + #private; + private readonly environmentId?; + private readonly awsSecurityCredentialsSupplier; + private readonly regionalCredVerificationUrl; + private awsRequestSigner; + private region; + /** + * @deprecated AWS client no validates the EC2 metadata address. + **/ + static AWS_EC2_METADATA_IPV4_ADDRESS: string; + /** + * @deprecated AWS client no validates the EC2 metadata address. + **/ + static AWS_EC2_METADATA_IPV6_ADDRESS: string; + /** + * 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. + */ + constructor(options: AwsClientOptions | SnakeToCamelObject); + private validateEnvironmentId; + /** + * 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. + */ + retrieveSubjectToken(): Promise; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/awsclient.js b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/awsclient.js new file mode 100644 index 0000000000000000000000000000000000000000..3cd45341036783ba0cfe0557b9e694c5410c2c9b --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/awsclient.js @@ -0,0 +1,154 @@ +"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.AwsClient = void 0; +const awsrequestsigner_1 = require("./awsrequestsigner"); +const baseexternalclient_1 = require("./baseexternalclient"); +const defaultawssecuritycredentialssupplier_1 = require("./defaultawssecuritycredentialssupplier"); +const util_1 = require("../util"); +const gaxios_1 = require("gaxios"); +/** + * 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 { + environmentId; + awsSecurityCredentialsSupplier; + regionalCredVerificationUrl; + awsRequestSigner; + region; + static #DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL = 'https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15'; + /** + * @deprecated AWS client no validates the EC2 metadata address. + **/ + static AWS_EC2_METADATA_IPV4_ADDRESS = '169.254.169.254'; + /** + * @deprecated AWS client no validates the EC2 metadata address. + **/ + static AWS_EC2_METADATA_IPV6_ADDRESS = 'fd00:ec2::254'; + /** + * 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. + */ + constructor(options) { + super(options); + 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 = + 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() { + const match = this.environmentId?.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({ + ...AwsClient.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 = gaxios_1.Gaxios.mergeHeaders({ + // 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. + extendedHeaders.forEach((value, key) => reformattedHeader.push({ key, value })); + // Serialize the reformatted signed request. + return encodeURIComponent(JSON.stringify({ + url: options.url, + method: options.method, + headers: reformattedHeader, + })); + } +} +exports.AwsClient = AwsClient; +//# sourceMappingURL=awsclient.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/awsrequestsigner.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/awsrequestsigner.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3467e973f6879bae31286a5c37aa9b511e93ee96 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/awsrequestsigner.d.ts @@ -0,0 +1,40 @@ +import { GaxiosOptions } from 'gaxios'; +/** + * Interface defining AWS security credentials. + * These are either determined from AWS security_credentials endpoint or + * AWS environment variables. + */ +export interface AwsSecurityCredentials { + accessKeyId: string; + secretAccessKey: string; + token?: string; +} +/** + * 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 + */ +export declare class AwsRequestSigner { + private readonly getCredentials; + private readonly region; + private readonly crypto; + /** + * 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: () => Promise, region: string); + /** + * 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. + */ + getRequestOptions(amzOptions: GaxiosOptions): Promise; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/awsrequestsigner.js b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/awsrequestsigner.js new file mode 100644 index 0000000000000000000000000000000000000000..813169a87c7f3ee13cda281aafda8657d2752a8a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/awsrequestsigner.js @@ -0,0 +1,213 @@ +"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 gaxios_1 = require("gaxios"); +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 { + getCredentials; + region; + crypto; + /** + * 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 RangeError('"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); + if (typeof requestPayload !== 'string' && requestPayload !== undefined) { + throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${requestPayload}`); + } + const headerMap = await generateAuthenticationHeaderMap({ + crypto: this.crypto, + host: uri.host, + canonicalUri: uri.pathname, + canonicalQuerystring: uri.search.slice(1), + method, + region: this.region, + securityCredentials: awsSecurityCredentials, + requestPayload, + additionalAmzHeaders, + }); + // Append additional optional headers, eg. X-Amz-Target, Content-Type, etc. + const headers = gaxios_1.Gaxios.mergeHeaders( + // Add x-amz-date if available. + headerMap.amzDate ? { 'x-amz-date': headerMap.amzDate } : {}, { + authorization: headerMap.authorizationHeader, + host: uri.host, + }, additionalAmzHeaders || {}); + if (awsSecurityCredentials.token) { + gaxios_1.Gaxios.mergeHeaders(headers, { + 'x-amz-security-token': awsSecurityCredentials.token, + }); + } + const awsSignedReq = { + url, + method: method, + headers, + }; + if (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 = gaxios_1.Gaxios.mergeHeaders(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.*/, ''); + // Add AWS token if available. + if (options.securityCredentials.token) { + additionalAmzHeaders.set('x-amz-security-token', options.securityCredentials.token); + } + // Header keys need to be sorted alphabetically. + const amzHeaders = gaxios_1.Gaxios.mergeHeaders({ + 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 + additionalAmzHeaders.has('date') ? {} : { 'x-amz-date': amzDate }, additionalAmzHeaders); + let canonicalHeaders = ''; + // TypeScript is missing `Headers#keys` at the time of writing + const signedHeadersList = [ + ...amzHeaders.keys(), + ].sort(); + signedHeadersList.forEach(key => { + canonicalHeaders += `${key}:${amzHeaders.get(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.toUpperCase()}\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: additionalAmzHeaders.has('date') ? undefined : amzDate, + authorizationHeader, + canonicalQuerystring: options.canonicalQuerystring, + }; +} +//# sourceMappingURL=awsrequestsigner.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/baseexternalclient.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/baseexternalclient.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b6a7769da2df3a26cf60b8f54e9719f95d80d81e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/baseexternalclient.d.ts @@ -0,0 +1,318 @@ +import { Gaxios, GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios'; +import { Credentials } from './credentials'; +import { AuthClient, AuthClientOptions, GetAccessTokenResponse, BodyResponseCallback } from './authclient'; +import * as sts from './stscredentials'; +import { ClientAuthentication } from './oauth2common'; +import { SnakeToCamelObject } from '../util'; +/** + * Offset to take into account network delays and server clock skews. + */ +export declare const EXPIRATION_TIME_OFFSET: number; +/** + * 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) + */ +export declare const EXTERNAL_ACCOUNT_TYPE = "external_account"; +/** + * Cloud resource manager URL used to retrieve project information. + * + * @deprecated use {@link BaseExternalAccountClient.cloudResourceManagerURL} instead + **/ +export declare const CLOUD_RESOURCE_MANAGER = "https://cloudresourcemanager.googleapis.com/v1/projects/"; +/** + * Shared options used to build {@link ExternalAccountClient} and + * {@link ExternalAccountAuthorizedUserClient}. + */ +export interface SharedExternalAccountClientOptions extends AuthClientOptions { + /** + * The Security Token Service audience, which is usually the fully specified + * resource name of the workload or workforce pool provider. + */ + audience: string; + /** + * The Security Token Service token URL used to exchange the third party token + * for a GCP access token. If not provided, will default to + * 'https://sts.googleapis.com/v1/token' + */ + token_url?: string; +} +/** + * Interface containing context about the requested external identity. This is + * passed on all requests from external account clients to external identity suppliers. + */ +export interface ExternalAccountSupplierContext { + /** + * The requested external account audience. For example: + * * "//iam.googleapis.com/locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID" + * * "//iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID" + */ + audience: string; + /** + * The requested subject token type. Expected values include: + * * "urn:ietf:params:oauth:token-type:jwt" + * * "urn:ietf:params:aws:token-type:aws4_request" + * * "urn:ietf:params:oauth:token-type:saml2" + * * "urn:ietf:params:oauth:token-type:id_token" + */ + subjectTokenType: string; + /** + * The {@link Gaxios} instance for calling external account + * to use for requests. + */ + transporter: Gaxios; +} +/** + * Base external account credentials json interface. + */ +export interface BaseExternalAccountClientOptions extends SharedExternalAccountClientOptions { + /** + * Credential type, should always be 'external_account'. + */ + type?: string; + /** + * The Security Token Service subject token type based on the OAuth 2.0 + * token exchange spec. Expected values include: + * * 'urn:ietf:params:oauth:token-type:jwt' + * * 'urn:ietf:params:aws:token-type:aws4_request' + * * 'urn:ietf:params:oauth:token-type:saml2' + * * 'urn:ietf:params:oauth:token-type:id_token' + */ + subject_token_type: string; + /** + * The URL for the service account impersonation request. This URL is required + * for some APIs. If this URL is not available, the access token from the + * Security Token Service is used directly. + */ + service_account_impersonation_url?: string; + /** + * Object containing additional options for service account impersonation. + */ + service_account_impersonation?: { + /** + * The desired lifetime of the impersonated service account access token. + * If not provided, the default lifetime will be 3600 seconds. + */ + token_lifetime_seconds?: number; + }; + /** + * The endpoint used to retrieve account related information. + */ + token_info_url?: string; + /** + * Client ID of the service account from the console. + */ + client_id?: string; + /** + * Client secret of the service account from the console. + */ + client_secret?: string; + /** + * The workforce pool user project. Required when using a workforce identity + * pool. + */ + workforce_pool_user_project?: string; + /** + * The scopes to request during the authorization grant. + */ + scopes?: string[]; + /** + * @example + * https://cloudresourcemanager.googleapis.com/v1/projects/ + **/ + cloud_resource_manager_url?: string | URL; +} +/** + * Interface defining the successful response for iamcredentials + * generateAccessToken API. + * https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/generateAccessToken + */ +export interface IamGenerateAccessTokenResponse { + accessToken: string; + /** + * ISO format used for expiration time. + * + * @example + * '2014-10-02T15:01:23.045123456Z' + */ + expireTime: string; +} +/** + * Interface defining the project information response returned by the cloud + * resource manager. + * https://cloud.google.com/resource-manager/reference/rest/v1/projects#Project + */ +export interface ProjectInfo { + projectNumber: string; + projectId: string; + lifecycleState: string; + name: string; + createTime?: string; + parent: { + [key: string]: ReturnType; + }; +} +/** + * Internal interface for tracking the access token expiration time. + */ +interface CredentialsWithResponse extends Credentials { + res?: GaxiosResponse | null; +} +/** + * 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. + */ +export declare abstract class BaseExternalAccountClient extends AuthClient { + #private; + /** + * OAuth scopes for the GCP access token to use. When not provided, + * the default https://www.googleapis.com/auth/cloud-platform is + * used. + */ + scopes?: string | string[]; + projectNumber: string | null; + protected readonly audience: string; + protected readonly subjectTokenType: string; + protected stsCredential: sts.StsCredentials; + protected readonly clientAuth?: ClientAuthentication; + protected credentialSourceType?: string; + private cachedAccessToken; + private readonly serviceAccountImpersonationUrl?; + private readonly serviceAccountImpersonationLifetime?; + private readonly workforcePoolUserProject?; + private readonly configLifetimeRequested; + private readonly tokenUrl; + /** + * @example + * ```ts + * new URL('https://cloudresourcemanager.googleapis.com/v1/projects/'); + * ``` + */ + protected cloudResourceManagerURL: URL | string; + protected supplierContext: ExternalAccountSupplierContext; + /** + * 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. + */ + constructor(options: BaseExternalAccountClientOptions | SnakeToCamelObject); + /** The service account email to be impersonated, if available. */ + getServiceAccountEmail(): string | 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: Credentials): void; + /** + * Triggered when a external subject token is needed to be exchanged for a GCP + * access token via GCP STS endpoint. + * This abstract method needs to be implemented by subclasses depending on + * the type of external credential used. + * @return A promise that resolves with the external subject token. + */ + abstract retrieveSubjectToken(): Promise; + /** + * @return A promise that resolves with the current GCP access token + * response. If the current credential is expired, a new one is retrieved. + */ + getAccessToken(): Promise; + /** + * 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 ' } + */ + getRequestHeaders(): Promise; + /** + * Provides a request implementation with OAuth 2.0 flow. In cases of + * HTTP 401 and 403 responses, it automatically asks for a new access token + * and replays the unsuccessful request. + * @param opts Request options. + * @param callback callback. + * @return A promise that resolves with the HTTP response when no callback is + * provided. + */ + request(opts: GaxiosOptions): GaxiosPromise; + request(opts: GaxiosOptions, callback: BodyResponseCallback): void; + /** + * @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 + */ + getProjectId(): Promise; + /** + * 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. + */ + protected requestAsync(opts: GaxiosOptions, reAuthRetried?: boolean): Promise>; + /** + * 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. + */ + protected refreshAccessTokenAsync(): Promise; + /** + * 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. + */ + private getProjectNumber; + /** + * 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. + */ + private getImpersonatedAccessToken; + /** + * 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. + */ + private isExpired; + /** + * @return The list of scopes for the requested GCP access token. + */ + private getScopesArray; + private getMetricsHeaderValue; + protected getTokenUrl(): string; +} +export {}; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/baseexternalclient.js b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/baseexternalclient.js new file mode 100644 index 0000000000000000000000000000000000000000..fcfe79a768dbd0ff794af856def3b6e0ccdae748 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/baseexternalclient.js @@ -0,0 +1,475 @@ +"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.BaseExternalAccountClient = exports.CLOUD_RESOURCE_MANAGER = exports.EXTERNAL_ACCOUNT_TYPE = exports.EXPIRATION_TIME_OFFSET = void 0; +const gaxios_1 = require("gaxios"); +const stream = require("stream"); +const authclient_1 = require("./authclient"); +const sts = require("./stscredentials"); +const util_1 = require("../util"); +const shared_cjs_1 = require("../shared.cjs"); +/** + * 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'; +/** + * 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 { + /** + * OAuth scopes for the GCP access token to use. When not provided, + * the default https://www.googleapis.com/auth/cloud-platform is + * used. + */ + scopes; + projectNumber; + audience; + subjectTokenType; + stsCredential; + clientAuth; + credentialSourceType; + cachedAccessToken; + serviceAccountImpersonationUrl; + serviceAccountImpersonationLifetime; + workforcePoolUserProject; + configLifetimeRequested; + tokenUrl; + /** + * @example + * ```ts + * new URL('https://cloudresourcemanager.googleapis.com/v1/projects/'); + * ``` + */ + cloudResourceManagerURL; + supplierContext; + /** + * A pending access token request. Used for concurrent calls. + */ + #pendingAccessToken = null; + /** + * 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. + */ + constructor(options) { + super(options); + 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'); + this.tokenUrl = + opts.get('token_url') ?? + 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({ + tokenExchangeEndpoint: this.tokenUrl, + clientAuthentication: 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() { + 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 result?.groups?.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 = new 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 opts = { + ...BaseExternalAccountClient.RETRY_CONFIG, + headers, + url: `${this.cloudResourceManagerURL.toString()}${projectNumber}`, + }; + authclient_1.AuthClient.setMethodName(opts, 'getProjectId'); + const response = await this.transporter.request(opts); + 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 = gaxios_1.Gaxios.mergeHeaders(opts.headers); + this.addUserProjectAndAuthHeaders(opts.headers, requestHeaders); + 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 + this.#pendingAccessToken = + this.#pendingAccessToken || this.#internalRefreshAccessTokenAsync(); + try { + return await this.#pendingAccessToken; + } + finally { + // clear pending access token for future requests + this.#pendingAccessToken = null; + } + } + async #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 = new Headers({ + '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; + } + /** + * 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', + }, + }; + authclient_1.AuthClient.setMethodName(opts, 'getImpersonatedAccessToken'); + 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/${shared_cjs_1.pkg.version} google-byoid-sdk source/${credentialSourceType} sa-impersonation/${saImpersonation} config-lifetime/${this.configLifetimeRequested}`; + } + getTokenUrl() { + return this.tokenUrl; + } +} +exports.BaseExternalAccountClient = BaseExternalAccountClient; +//# sourceMappingURL=baseexternalclient.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/certificatesubjecttokensupplier.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/certificatesubjecttokensupplier.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c2f01ae17453640709223bab1fc080a73353b980 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/certificatesubjecttokensupplier.d.ts @@ -0,0 +1,60 @@ +import { SubjectTokenSupplier } from './identitypoolclient'; +import * as https from 'https'; +export declare const CERTIFICATE_CONFIGURATION_ENV_VARIABLE = "GOOGLE_API_CERTIFICATE_CONFIG"; +/** + * Thrown when the certificate source cannot be located or accessed. + */ +export declare class CertificateSourceUnavailableError extends Error { + constructor(message: string); +} +/** + * Thrown for invalid configuration that is not related to file availability. + */ +export declare class InvalidConfigurationError extends Error { + constructor(message: string); +} +/** + * Defines options for creating a {@link CertificateSubjectTokenSupplier}. + */ +export interface CertificateSubjectTokenSupplierOptions { + /** + * If true, uses the default well-known location for the certificate config. + * Either this or `certificateConfigLocation` must be provided. + */ + useDefaultCertificateConfig?: boolean; + /** + * The file path to the certificate configuration JSON file. + * Required if `useDefaultCertificateConfig` is not true. + */ + certificateConfigLocation?: string; + /** + * The file path to the trust chain (PEM format). + */ + trustChainPath?: string; +} +/** + * A subject token supplier that uses a client certificate for authentication. + * It provides the certificate chain as the subject token for identity federation. + */ +export declare class CertificateSubjectTokenSupplier implements SubjectTokenSupplier { + #private; + private certificateConfigPath; + private readonly trustChainPath?; + private cert?; + private key?; + /** + * Initializes a new instance of the CertificateSubjectTokenSupplier. + * @param opts The configuration options for the supplier. + */ + constructor(opts: CertificateSubjectTokenSupplierOptions); + /** + * Creates an HTTPS agent configured with the client certificate and private key for mTLS. + * @returns An mTLS-configured https.Agent. + */ + createMtlsHttpsAgent(): Promise; + /** + * Constructs the subject token, which is the base64-encoded certificate chain. + * @returns A promise that resolves with the subject token. + */ + getSubjectToken(): Promise; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/certificatesubjecttokensupplier.js b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/certificatesubjecttokensupplier.js new file mode 100644 index 0000000000000000000000000000000000000000..4de6cca82e11bb1a0e26d07000cdab59b6cf34a5 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/certificatesubjecttokensupplier.js @@ -0,0 +1,223 @@ +"use strict"; +// Copyright 2025 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.CertificateSubjectTokenSupplier = exports.InvalidConfigurationError = exports.CertificateSourceUnavailableError = exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE = void 0; +const util_1 = require("../util"); +const fs = require("fs"); +const crypto_1 = require("crypto"); +const https = require("https"); +exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE = 'GOOGLE_API_CERTIFICATE_CONFIG'; +/** + * Thrown when the certificate source cannot be located or accessed. + */ +class CertificateSourceUnavailableError extends Error { + constructor(message) { + super(message); + this.name = 'CertificateSourceUnavailableError'; + } +} +exports.CertificateSourceUnavailableError = CertificateSourceUnavailableError; +/** + * Thrown for invalid configuration that is not related to file availability. + */ +class InvalidConfigurationError extends Error { + constructor(message) { + super(message); + this.name = 'InvalidConfigurationError'; + } +} +exports.InvalidConfigurationError = InvalidConfigurationError; +/** + * A subject token supplier that uses a client certificate for authentication. + * It provides the certificate chain as the subject token for identity federation. + */ +class CertificateSubjectTokenSupplier { + certificateConfigPath; + trustChainPath; + cert; + key; + /** + * Initializes a new instance of the CertificateSubjectTokenSupplier. + * @param opts The configuration options for the supplier. + */ + constructor(opts) { + if (!opts.useDefaultCertificateConfig && !opts.certificateConfigLocation) { + throw new InvalidConfigurationError('Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.'); + } + if (opts.useDefaultCertificateConfig && opts.certificateConfigLocation) { + throw new InvalidConfigurationError('Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.'); + } + this.trustChainPath = opts.trustChainPath; + this.certificateConfigPath = opts.certificateConfigLocation ?? ''; + } + /** + * Creates an HTTPS agent configured with the client certificate and private key for mTLS. + * @returns An mTLS-configured https.Agent. + */ + async createMtlsHttpsAgent() { + if (!this.key || !this.cert) { + throw new InvalidConfigurationError('Cannot create mTLS Agent with missing certificate or key'); + } + return new https.Agent({ key: this.key, cert: this.cert }); + } + /** + * Constructs the subject token, which is the base64-encoded certificate chain. + * @returns A promise that resolves with the subject token. + */ + async getSubjectToken() { + // The "subject token" in this context is the processed certificate chain. + this.certificateConfigPath = await this.#resolveCertificateConfigFilePath(); + const { certPath, keyPath } = await this.#getCertAndKeyPaths(); + ({ cert: this.cert, key: this.key } = await this.#getKeyAndCert(certPath, keyPath)); + return await this.#processChainFromPaths(this.cert); + } + /** + * Resolves the absolute path to the certificate configuration file + * by checking the "certificate_config_location" provided in the ADC file, + * or the "GOOGLE_API_CERTIFICATE_CONFIG" environment variable + * or in the default gcloud path. + * @param overridePath An optional path to check first. + * @returns The resolved file path. + */ + async #resolveCertificateConfigFilePath() { + // 1. Check for the override path from constructor options. + const overridePath = this.certificateConfigPath; + if (overridePath) { + if (await (0, util_1.isValidFile)(overridePath)) { + return overridePath; + } + throw new CertificateSourceUnavailableError(`Provided certificate config path is invalid: ${overridePath}`); + } + // 2. Check the standard environment variable. + const envPath = process.env[exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE]; + if (envPath) { + if (await (0, util_1.isValidFile)(envPath)) { + return envPath; + } + throw new CertificateSourceUnavailableError(`Path from environment variable "${exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${envPath}`); + } + // 3. Check the well-known gcloud config location. + const wellKnownPath = (0, util_1.getWellKnownCertificateConfigFileLocation)(); + if (await (0, util_1.isValidFile)(wellKnownPath)) { + return wellKnownPath; + } + // 4. If none are found, throw an error. + throw new CertificateSourceUnavailableError('Could not find certificate configuration file. Searched override path, ' + + `the "${exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${wellKnownPath}).`); + } + /** + * Reads and parses the certificate config JSON file to extract the certificate and key paths. + * @returns An object containing the certificate and key paths. + */ + async #getCertAndKeyPaths() { + const configPath = this.certificateConfigPath; + let fileContents; + try { + fileContents = await fs.promises.readFile(configPath, 'utf8'); + } + catch (err) { + throw new CertificateSourceUnavailableError(`Failed to read certificate config file at: ${configPath}`); + } + try { + const config = JSON.parse(fileContents); + const certPath = config?.cert_configs?.workload?.cert_path; + const keyPath = config?.cert_configs?.workload?.key_path; + if (!certPath || !keyPath) { + throw new InvalidConfigurationError(`Certificate config file (${configPath}) is missing required "cert_path" or "key_path" in the workload config.`); + } + return { certPath, keyPath }; + } + catch (e) { + if (e instanceof InvalidConfigurationError) + throw e; + throw new InvalidConfigurationError(`Failed to parse certificate config from ${configPath}: ${e.message}`); + } + } + /** + * Reads and parses the cert and key files get their content and check valid format. + * @returns An object containing the cert content and key content in buffer format. + */ + async #getKeyAndCert(certPath, keyPath) { + let cert, key; + try { + cert = await fs.promises.readFile(certPath); + new crypto_1.X509Certificate(cert); + } + catch (err) { + const message = err instanceof Error ? err.message : String(err); + throw new CertificateSourceUnavailableError(`Failed to read certificate file at ${certPath}: ${message}`); + } + try { + key = await fs.promises.readFile(keyPath); + (0, crypto_1.createPrivateKey)(key); + } + catch (err) { + const message = err instanceof Error ? err.message : String(err); + throw new CertificateSourceUnavailableError(`Failed to read private key file at ${keyPath}: ${message}`); + } + return { cert, key }; + } + /** + * Reads the leaf certificate and trust chain, combines them, + * and returns a JSON array of base64-encoded certificates. + * @returns A stringified JSON array of the certificate chain. + */ + async #processChainFromPaths(leafCertBuffer) { + const leafCert = new crypto_1.X509Certificate(leafCertBuffer); + // If no trust chain is provided, just use the successfully parsed leaf certificate. + if (!this.trustChainPath) { + return JSON.stringify([leafCert.raw.toString('base64')]); + } + // Handle the trust chain logic. + try { + const chainPems = await fs.promises.readFile(this.trustChainPath, 'utf8'); + const pemBlocks = chainPems.match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g) ?? []; + const chainCerts = pemBlocks.map((pem, index) => { + try { + return new crypto_1.X509Certificate(pem); + } + catch (err) { + const message = err instanceof Error ? err.message : String(err); + // Throw a more precise error if a single certificate in the chain is invalid. + throw new InvalidConfigurationError(`Failed to parse certificate at index ${index} in trust chain file ${this.trustChainPath}: ${message}`); + } + }); + const leafIndex = chainCerts.findIndex(chainCert => leafCert.raw.equals(chainCert.raw)); + let finalChain; + if (leafIndex === -1) { + // Leaf not found, so prepend it to the chain. + finalChain = [leafCert, ...chainCerts]; + } + else if (leafIndex === 0) { + // Leaf is already the first element, so the chain is correctly ordered. + finalChain = chainCerts; + } + else { + // Leaf is in the chain but not at the top, which is invalid. + throw new InvalidConfigurationError(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${leafIndex}).`); + } + return JSON.stringify(finalChain.map(cert => cert.raw.toString('base64'))); + } + catch (err) { + // Re-throw our specific configuration errors. + if (err instanceof InvalidConfigurationError) + throw err; + const message = err instanceof Error ? err.message : String(err); + throw new CertificateSourceUnavailableError(`Failed to process certificate chain from ${this.trustChainPath}: ${message}`); + } + } +} +exports.CertificateSubjectTokenSupplier = CertificateSubjectTokenSupplier; +//# sourceMappingURL=certificatesubjecttokensupplier.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/computeclient.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/computeclient.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..23e9a9a08b2172b8f62d515c5061034e87463ae9 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/computeclient.d.ts @@ -0,0 +1,37 @@ +import { GaxiosError } from 'gaxios'; +import { GetTokenResponse, OAuth2Client, OAuth2ClientOptions } from './oauth2client'; +export interface ComputeOptions extends OAuth2ClientOptions { + /** + * The service account email to use, or 'default'. A Compute Engine instance + * may have multiple service accounts. + */ + serviceAccountEmail?: string; + /** + * The scopes that will be requested when acquiring service account + * credentials. Only applicable to modern App Engine and Cloud Function + * runtimes as of March 2019. + */ + scopes?: string | string[]; +} +export declare class Compute extends OAuth2Client { + readonly serviceAccountEmail: string; + scopes: string[]; + /** + * 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?: ComputeOptions); + /** + * Refreshes the access token. + * @param refreshToken Unused parameter + */ + protected refreshTokenNoCache(): Promise; + /** + * Fetches an ID token. + * @param targetAudience the audience for the fetched ID token. + */ + fetchIdToken(targetAudience: string): Promise; + protected wrapError(e: GaxiosError): void; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/computeclient.js b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/computeclient.js new file mode 100644 index 0000000000000000000000000000000000000000..34ef9d00015dce981eb9b2bb3ce7b9d7614d8da1 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/computeclient.js @@ -0,0 +1,118 @@ +"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 { + serviceAccountEmail; + scopes; + /** + * 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() { + 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; +//# sourceMappingURL=computeclient.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/credentials.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/credentials.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..896b014ccb8d6c6b54b13f6b3da2b019a7b74c1c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/credentials.d.ts @@ -0,0 +1,75 @@ +export interface Credentials { + /** + * This field is only present if the access_type parameter was set to offline in the authentication request. For details, see Refresh tokens. + */ + refresh_token?: string | null; + /** + * The time in ms at which this token is thought to expire. + */ + expiry_date?: number | null; + /** + * A token that can be sent to a Google API. + */ + access_token?: string | null; + /** + * Identifies the type of token returned. At this time, this field always has the value Bearer. + */ + token_type?: string | null; + /** + * A JWT that contains identity information about the user that is digitally signed by Google. + */ + id_token?: string | null; + /** + * The scopes of access granted by the access_token expressed as a list of space-delimited, case-sensitive strings. + */ + scope?: string; +} +export interface CredentialRequest { + /** + * This field is only present if the access_type parameter was set to offline in the authentication request. For details, see Refresh tokens. + */ + refresh_token?: string; + /** + * A token that can be sent to a Google API. + */ + access_token?: string; + /** + * Identifies the type of token returned. At this time, this field always has the value Bearer. + */ + token_type?: string; + /** + * The remaining lifetime of the access token in seconds. + */ + expires_in?: number; + /** + * A JWT that contains identity information about the user that is digitally signed by Google. + */ + id_token?: string; + /** + * The scopes of access granted by the access_token expressed as a list of space-delimited, case-sensitive strings. + */ + scope?: string; +} +export interface JWTInput { + type?: string; + client_email?: string; + private_key?: string; + private_key_id?: string; + project_id?: string; + client_id?: string; + client_secret?: string; + refresh_token?: string; + quota_project_id?: string; + universe_domain?: string; +} +export interface ImpersonatedJWTInput { + type?: string; + source_credentials?: JWTInput; + service_account_impersonation_url?: string; + delegates?: string[]; +} +export interface CredentialBody { + client_email?: string; + private_key?: string; + universe_domain?: string; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/credentials.js b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/credentials.js new file mode 100644 index 0000000000000000000000000000000000000000..5ea0d586fe973398e4cb09c245d6b10dd49d785f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/credentials.js @@ -0,0 +1,16 @@ +"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 }); +//# sourceMappingURL=credentials.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..62a2fa41464d57aa6850157938c567be5e0fa3e5 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.d.ts @@ -0,0 +1,79 @@ +import { ExternalAccountSupplierContext } from './baseexternalclient'; +import { GaxiosOptions } from 'gaxios'; +import { AwsSecurityCredentialsSupplier } from './awsclient'; +import { AwsSecurityCredentials } from './awsrequestsigner'; +/** + * Interface defining the options used to build a {@link DefaultAwsSecurityCredentialsSupplier}. + */ +export interface DefaultAwsSecurityCredentialsSupplierOptions { + /** + * The URL to call to retrieve the active AWS region. + **/ + regionUrl?: string; + /** + * The URL to call to retrieve AWS security credentials. + **/ + securityCredentialsUrl?: string; + /** + ** The URL to call to retrieve the IMDSV2 session token. + **/ + imdsV2SessionTokenUrl?: string; + /** + * Additional Gaxios options to use when making requests to the AWS metadata + * endpoints. + */ + additionalGaxiosOptions?: GaxiosOptions; +} +/** + * 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. + */ +export declare class DefaultAwsSecurityCredentialsSupplier implements AwsSecurityCredentialsSupplier { + #private; + private readonly regionUrl?; + private readonly securityCredentialsUrl?; + private readonly imdsV2SessionTokenUrl?; + private readonly additionalGaxiosOptions?; + /** + * 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: DefaultAwsSecurityCredentialsSupplierOptions); + /** + * 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. + */ + getAwsRegion(context: ExternalAccountSupplierContext): Promise; + /** + * 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. + */ + getAwsSecurityCredentials(context: ExternalAccountSupplierContext): Promise; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.js b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.js new file mode 100644 index 0000000000000000000000000000000000000000..374af30cfa87dbc9b38857866718954c13d74be2 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.js @@ -0,0 +1,195 @@ +"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.DefaultAwsSecurityCredentialsSupplier = void 0; +const authclient_1 = require("./authclient"); +/** + * 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 { + regionUrl; + securityCredentialsUrl; + imdsV2SessionTokenUrl; + additionalGaxiosOptions; + /** + * 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) { + 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 (this.#regionFromEnv) { + return this.#regionFromEnv; + } + const metadataHeaders = new Headers(); + if (!this.#regionFromEnv && this.imdsV2SessionTokenUrl) { + metadataHeaders.set('x-aws-ec2-metadata-token', await this.#getImdsV2SessionToken(context.transporter)); + } + if (!this.regionUrl) { + throw new RangeError('Unable to determine AWS region due to missing ' + + '"options.credential_source.region_url"'); + } + const opts = { + ...this.additionalGaxiosOptions, + url: this.regionUrl, + method: 'GET', + headers: metadataHeaders, + }; + authclient_1.AuthClient.setMethodName(opts, 'getAwsRegion'); + 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 (this.#securityCredentialsFromEnv) { + return this.#securityCredentialsFromEnv; + } + const metadataHeaders = new Headers(); + if (this.imdsV2SessionTokenUrl) { + metadataHeaders.set('x-aws-ec2-metadata-token', await this.#getImdsV2SessionToken(context.transporter)); + } + // Since the role on a VM can change, we don't need to cache it. + const roleName = await this.#getAwsRoleName(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 this.#retrieveAwsSecurityCredentials(roleName, metadataHeaders, context.transporter); + return { + accessKeyId: awsCreds.AccessKeyId, + secretAccessKey: awsCreds.SecretAccessKey, + token: awsCreds.Token, + }; + } + /** + * @param transporter The transporter to use for requests. + * @return A promise that resolves with the IMDSv2 Session Token. + */ + async #getImdsV2SessionToken(transporter) { + const opts = { + ...this.additionalGaxiosOptions, + url: this.imdsV2SessionTokenUrl, + method: 'PUT', + headers: { 'x-aws-ec2-metadata-token-ttl-seconds': '300' }, + }; + authclient_1.AuthClient.setMethodName(opts, '#getImdsV2SessionToken'); + const response = await transporter.request(opts); + return response.data; + } + /** + * @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 #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', + headers: headers, + }; + authclient_1.AuthClient.setMethodName(opts, '#getAwsRoleName'); + const response = await transporter.request(opts); + return response.data; + } + /** + * 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 #retrieveAwsSecurityCredentials(roleName, headers, transporter) { + const opts = { + ...this.additionalGaxiosOptions, + url: `${this.securityCredentialsUrl}/${roleName}`, + headers: headers, + }; + authclient_1.AuthClient.setMethodName(opts, '#retrieveAwsSecurityCredentials'); + const response = await transporter.request(opts); + return response.data; + } + get #regionFromEnv() { + // 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); + } + get #securityCredentialsFromEnv() { + // 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; + } +} +exports.DefaultAwsSecurityCredentialsSupplier = DefaultAwsSecurityCredentialsSupplier; +//# sourceMappingURL=defaultawssecuritycredentialssupplier.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/downscopedclient.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/downscopedclient.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ff1b5e2bfab128b9506154ec7a818123762f9768 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/downscopedclient.d.ts @@ -0,0 +1,149 @@ +import { GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios'; +import { Credentials } from './credentials'; +import { AuthClient, AuthClientOptions, GetAccessTokenResponse, BodyResponseCallback } from './authclient'; +/** + * The maximum number of access boundary rules a Credential Access Boundary + * can contain. + */ +export declare const MAX_ACCESS_BOUNDARY_RULES_COUNT = 10; +/** + * Offset to take into account network delays and server clock skews. + */ +export declare const EXPIRATION_TIME_OFFSET: number; +/** + * Internal interface for tracking the access token expiration time. + */ +interface CredentialsWithResponse extends Credentials { + res?: GaxiosResponse | null; +} +/** + * Internal interface for tracking and returning the Downscoped access token + * expiration time in epoch time (seconds). + */ +interface DownscopedAccessTokenResponse extends GetAccessTokenResponse { + expirationTime?: number | null; +} +/** + * Defines an upper bound of permissions available for a GCP credential. + */ +export interface CredentialAccessBoundary { + accessBoundary: { + accessBoundaryRules: AccessBoundaryRule[]; + }; +} +/** Defines an upper bound of permissions on a particular resource. */ +interface AccessBoundaryRule { + availablePermissions: string[]; + availableResource: string; + availabilityCondition?: AvailabilityCondition; +} +/** + * An optional condition that can be used as part of a + * CredentialAccessBoundary to further restrict permissions. + */ +interface AvailabilityCondition { + expression: string; + title?: string; + description?: string; +} +export interface DownscopedClientOptions extends AuthClientOptions { + /** + * The source AuthClient to be downscoped based on the provided Credential Access Boundary rules. + */ + authClient: AuthClient; + /** + * 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. + */ + credentialAccessBoundary: CredentialAccessBoundary; +} +/** + * 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. + */ +export declare class DownscopedClient extends AuthClient { + private readonly authClient; + private readonly credentialAccessBoundary; + private cachedDownscopedAccessToken; + private readonly stsCredential; + /** + * 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 options the {@link DownscopedClientOptions `DownscopedClientOptions`} to use. Passing an `AuthClient` directly is **@DEPRECATED**. + * @param credentialAccessBoundary **@DEPRECATED**. Provide a {@link DownscopedClientOptions `DownscopedClientOptions`} object in the first parameter instead. + */ + constructor( + /** + * AuthClient is for backwards-compatibility. + */ + options: AuthClient | DownscopedClientOptions, + /** + * @deprecated - provide a {@link DownscopedClientOptions `DownscopedClientOptions`} object in the first parameter instead + */ + credentialAccessBoundary?: CredentialAccessBoundary); + /** + * 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: Credentials): void; + getAccessToken(): Promise; + /** + * 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 ' } + */ + getRequestHeaders(): Promise; + /** + * Provides a request implementation with OAuth 2.0 flow. In cases of + * HTTP 401 and 403 responses, it automatically asks for a new access token + * and replays the unsuccessful request. + * @param opts Request options. + * @param callback callback. + * @return A promise that resolves with the HTTP response when no callback + * is provided. + */ + request(opts: GaxiosOptions): GaxiosPromise; + request(opts: GaxiosOptions, callback: BodyResponseCallback): void; + /** + * 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. + */ + protected requestAsync(opts: GaxiosOptions, reAuthRetried?: boolean): Promise>; + /** + * 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. + */ + protected refreshAccessTokenAsync(): Promise; + /** + * 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. + */ + private isExpired; +} +export {}; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/downscopedclient.js b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/downscopedclient.js new file mode 100644 index 0000000000000000000000000000000000000000..43140f0f9bb88eedf80d4338f066e7213bade540 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/downscopedclient.js @@ -0,0 +1,273 @@ +"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 gaxios_1 = require("gaxios"); +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 { + authClient; + credentialAccessBoundary; + cachedDownscopedAccessToken; + stsCredential; + /** + * 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 options the {@link DownscopedClientOptions `DownscopedClientOptions`} to use. Passing an `AuthClient` directly is **@DEPRECATED**. + * @param credentialAccessBoundary **@DEPRECATED**. Provide a {@link DownscopedClientOptions `DownscopedClientOptions`} object in the first parameter instead. + */ + constructor( + /** + * AuthClient is for backwards-compatibility. + */ + options, + /** + * @deprecated - provide a {@link DownscopedClientOptions `DownscopedClientOptions`} object in the first parameter instead + */ + credentialAccessBoundary = { + accessBoundary: { + accessBoundaryRules: [], + }, + }) { + super(options instanceof authclient_1.AuthClient ? {} : options); + if (options instanceof authclient_1.AuthClient) { + this.authClient = options; + this.credentialAccessBoundary = credentialAccessBoundary; + } + else { + this.authClient = options.authClient; + this.credentialAccessBoundary = options.credentialAccessBoundary; + } + // Check 1-10 Access Boundary Rules are defined within Credential Access + // Boundary. + if (this.credentialAccessBoundary.accessBoundary.accessBoundaryRules + .length === 0) { + throw new Error('At least one access boundary rule needs to be defined.'); + } + else if (this.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 this.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({ + tokenExchangeEndpoint: `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 = new 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 = gaxios_1.Gaxios.mergeHeaders(opts.headers); + this.addUserProjectAndAuthHeaders(opts.headers, requestHeaders); + 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() { + // 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 = this.authClient.credentials?.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; +//# sourceMappingURL=downscopedclient.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/envDetect.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/envDetect.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..be6f1afb086cc494c8f52215c767f7fc1ef09e55 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/envDetect.d.ts @@ -0,0 +1,11 @@ +export declare enum GCPEnv { + APP_ENGINE = "APP_ENGINE", + KUBERNETES_ENGINE = "KUBERNETES_ENGINE", + CLOUD_FUNCTIONS = "CLOUD_FUNCTIONS", + COMPUTE_ENGINE = "COMPUTE_ENGINE", + CLOUD_RUN = "CLOUD_RUN", + CLOUD_RUN_JOBS = "CLOUD_RUN_JOBS", + NONE = "NONE" +} +export declare function clear(): void; +export declare function getEnv(): Promise; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/envDetect.js b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/envDetect.js new file mode 100644 index 0000000000000000000000000000000000000000..ee6ceb08aa275f73a27c28061c966ac3eb5064ad --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/envDetect.js @@ -0,0 +1,97 @@ +"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["CLOUD_RUN_JOBS"] = "CLOUD_RUN_JOBS"; + 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 if (isCloudRunJob()) { + env = GCPEnv.CLOUD_RUN_JOBS; + } + 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; +} +function isCloudRunJob() { + return !!process.env.CLOUD_RUN_JOB; +} +async function isKubernetesEngine() { + try { + await gcpMetadata.instance('attributes/cluster-name'); + return true; + } + catch (e) { + return false; + } +} +async function isComputeEngine() { + return gcpMetadata.isAvailable(); +} +//# sourceMappingURL=envDetect.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/executable-response.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/executable-response.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..259d276940a262600152c5ff565c76df0b5ee77a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/executable-response.d.ts @@ -0,0 +1,137 @@ +/** + * Interface defining the JSON formatted response of a 3rd party executable + * used by the pluggable auth client. + */ +export interface ExecutableResponseJson { + /** + * The version of the JSON response. Only version 1 is currently supported. + * Always required. + */ + version: number; + /** + * Whether the executable ran successfully. Always required. + */ + success: boolean; + /** + * The epoch time for expiration of the token in seconds, required for + * successful responses. + */ + expiration_time?: number; + /** + * The type of subject token in the response, currently supported values are: + * urn:ietf:params:oauth:token-type:saml2 + * urn:ietf:params:oauth:token-type:id_token + * urn:ietf:params:oauth:token-type:jwt + */ + token_type?: string; + /** + * The error code from the executable, required when unsuccessful. + */ + code?: string; + /** + * The error message from the executable, required when unsuccessful. + */ + message?: string; + /** + * The ID token to be used as a subject token when token_type is id_token or jwt. + */ + id_token?: string; + /** + * The response to be used as a subject token when token_type is saml2. + */ + saml_response?: string; +} +/** + * Defines the response of a 3rd party executable run by the pluggable auth client. + */ +export declare class ExecutableResponse { + /** + * The version of the Executable response. Only version 1 is currently supported. + */ + readonly version: number; + /** + * Whether the executable ran successfully. + */ + readonly success: boolean; + /** + * The epoch time for expiration of the token in seconds. + */ + readonly expirationTime?: number; + /** + * The type of subject token in the response, currently supported values are: + * urn:ietf:params:oauth:token-type:saml2 + * urn:ietf:params:oauth:token-type:id_token + * urn:ietf:params:oauth:token-type:jwt + */ + readonly tokenType?: string; + /** + * The error code from the executable. + */ + readonly errorCode?: string; + /** + * The error message from the executable. + */ + readonly errorMessage?: string; + /** + * The subject token from the executable, format depends on tokenType. + */ + readonly subjectToken?: string; + /** + * 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: ExecutableResponseJson); + /** + * @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(): boolean; + /** + * @return A boolean representing if the response is expired. Returns true if the + * provided timeout has passed. + */ + isExpired(): boolean; +} +/** + * An error thrown by the ExecutableResponse class. + */ +export declare class ExecutableResponseError extends Error { + constructor(message: string); +} +/** + * An error thrown when the 'version' field in an executable response is missing or invalid. + */ +export declare class InvalidVersionFieldError extends ExecutableResponseError { +} +/** + * An error thrown when the 'success' field in an executable response is missing or invalid. + */ +export declare class InvalidSuccessFieldError extends ExecutableResponseError { +} +/** + * An error thrown when the 'expiration_time' field in an executable response is missing or invalid. + */ +export declare class InvalidExpirationTimeFieldError extends ExecutableResponseError { +} +/** + * An error thrown when the 'token_type' field in an executable response is missing or invalid. + */ +export declare class InvalidTokenTypeFieldError extends ExecutableResponseError { +} +/** + * An error thrown when the 'code' field in an executable response is missing or invalid. + */ +export declare class InvalidCodeFieldError extends ExecutableResponseError { +} +/** + * An error thrown when the 'message' field in an executable response is missing or invalid. + */ +export declare class InvalidMessageFieldError extends ExecutableResponseError { +} +/** + * An error thrown when the subject token in an executable response is missing or invalid. + */ +export declare class InvalidSubjectTokenError extends ExecutableResponseError { +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/executable-response.js b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/executable-response.js new file mode 100644 index 0000000000000000000000000000000000000000..3ad9f5d8687d5f5e5dbe69d1ec92e1b5785eca55 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/executable-response.js @@ -0,0 +1,178 @@ +"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 { + /** + * The version of the Executable response. Only version 1 is currently supported. + */ + version; + /** + * Whether the executable ran successfully. + */ + success; + /** + * The epoch time for expiration of the token in seconds. + */ + expirationTime; + /** + * The type of subject token in the response, currently supported values are: + * urn:ietf:params:oauth:token-type:saml2 + * urn:ietf:params:oauth:token-type:id_token + * urn:ietf:params:oauth:token-type:jwt + */ + tokenType; + /** + * The error code from the executable. + */ + errorCode; + /** + * The error message from the executable. + */ + errorMessage; + /** + * The subject token from the executable, format depends on tokenType. + */ + subjectToken; + /** + * 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; +//# sourceMappingURL=executable-response.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ec9d5a3544d2af95b0df11caf61d3b9ddd6fd77b --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.d.ts @@ -0,0 +1,72 @@ +import { AuthClient, BodyResponseCallback } from './authclient'; +import { GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios'; +import { Credentials } from './credentials'; +import { SharedExternalAccountClientOptions } from './baseexternalclient'; +/** + * The credentials JSON file type for external account authorized user clients. + */ +export declare const EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = "external_account_authorized_user"; +/** + * External Account Authorized User Credentials JSON interface. + */ +export interface ExternalAccountAuthorizedUserClientOptions extends SharedExternalAccountClientOptions { + type: typeof EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE; + client_id: string; + client_secret: string; + refresh_token: string; + token_info_url: string; + revoke_url?: string; +} +/** + * Internal interface for tracking the access token expiration time. + */ +interface CredentialsWithResponse extends Credentials { + res?: GaxiosResponse | null; +} +/** + * 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. + */ +export declare class ExternalAccountAuthorizedUserClient extends AuthClient { + private cachedAccessToken; + private readonly externalAccountAuthorizedUserHandler; + private refreshToken; + /** + * 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. + */ + constructor(options: ExternalAccountAuthorizedUserClientOptions); + getAccessToken(): Promise<{ + token?: string | null; + res?: GaxiosResponse | null; + }>; + getRequestHeaders(): Promise; + request(opts: GaxiosOptions): GaxiosPromise; + request(opts: GaxiosOptions, callback: BodyResponseCallback): void; + /** + * 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. + */ + protected requestAsync(opts: GaxiosOptions, reAuthRetried?: boolean): Promise>; + /** + * Forces token refresh, even if unexpired tokens are currently cached. + * @return A promise that resolves with the refreshed credential. + */ + protected refreshAccessTokenAsync(): Promise; + /** + * 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. + */ + private isExpired; +} +export {}; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.js b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.js new file mode 100644 index 0000000000000000000000000000000000000000..ad56f6939b0484ad98a977ba146ab1cb9ac090c0 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.js @@ -0,0 +1,232 @@ +"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 { + #tokenRefreshEndpoint; + /** + * 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(options) { + super(options); + this.#tokenRefreshEndpoint = options.tokenRefreshEndpoint; + } + /** + * 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, headers) { + const opts = { + ...ExternalAccountAuthorizedUserHandler.RETRY_CONFIG, + url: this.#tokenRefreshEndpoint, + method: 'POST', + headers, + data: new URLSearchParams({ + grant_type: 'refresh_token', + refresh_token: refreshToken, + }), + }; + authclient_1.AuthClient.setMethodName(opts, 'refreshToken'); + // 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 { + cachedAccessToken; + externalAccountAuthorizedUserHandler; + refreshToken; + /** + * 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. + */ + constructor(options) { + super(options); + if (options.universe_domain) { + this.universeDomain = options.universe_domain; + } + this.refreshToken = options.refresh_token; + const clientAuthentication = { + confidentialClientType: 'basic', + clientId: options.client_id, + clientSecret: options.client_secret, + }; + this.externalAccountAuthorizedUserHandler = + new ExternalAccountAuthorizedUserHandler({ + tokenRefreshEndpoint: options.token_url ?? + DEFAULT_TOKEN_URL.replace('{universeDomain}', this.universeDomain), + transporter: this.transporter, + clientAuthentication, + }); + 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 options?.eagerRefreshThresholdMillis !== 'number') { + this.eagerRefreshThresholdMillis = baseexternalclient_1.EXPIRATION_TIME_OFFSET; + } + else { + this.eagerRefreshThresholdMillis = options + .eagerRefreshThresholdMillis; + } + this.forceRefreshOnFailure = !!options?.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 = new 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 = gaxios_1.Gaxios.mergeHeaders(opts.headers); + this.addUserProjectAndAuthHeaders(opts.headers, requestHeaders); + 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; +//# sourceMappingURL=externalAccountAuthorizedUserClient.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/externalclient.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/externalclient.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bdad04e73ae8a663207c407263444a311fa6347a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/externalclient.d.ts @@ -0,0 +1,21 @@ +import { BaseExternalAccountClient } from './baseexternalclient'; +import { IdentityPoolClientOptions } from './identitypoolclient'; +import { AwsClientOptions } from './awsclient'; +import { PluggableAuthClientOptions } from './pluggable-auth-client'; +export type ExternalAccountClientOptions = IdentityPoolClientOptions | AwsClientOptions | PluggableAuthClientOptions; +/** + * Dummy class with no constructor. Developers are expected to use fromJSON. + */ +export declare class ExternalAccountClient { + constructor(); + /** + * 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. + * @return A BaseExternalAccountClient instance or null if the options + * provided do not correspond to an external account credential. + */ + static fromJSON(options: ExternalAccountClientOptions): BaseExternalAccountClient | null; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/externalclient.js b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/externalclient.js new file mode 100644 index 0000000000000000000000000000000000000000..0949656b1a1cca78b1f1bc1754d818719fe12011 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/externalclient.js @@ -0,0 +1,60 @@ +"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. + * @return A BaseExternalAccountClient instance or null if the options + * provided do not correspond to an external account credential. + */ + static fromJSON(options) { + if (options && options.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) { + if (options.credential_source?.environment_id) { + return new awsclient_1.AwsClient(options); + } + else if (options.credential_source?.executable) { + return new pluggable_auth_client_1.PluggableAuthClient(options); + } + else { + return new identitypoolclient_1.IdentityPoolClient(options); + } + } + else { + return null; + } + } +} +exports.ExternalAccountClient = ExternalAccountClient; +//# sourceMappingURL=externalclient.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ca77e7107b2e7ab1ddf672d32f3660b8ddeb7975 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.d.ts @@ -0,0 +1,41 @@ +import { SubjectTokenFormatType, SubjectTokenSupplier } from './identitypoolclient'; +/** + * Interface that defines options used to build a {@link FileSubjectTokenSupplier} + */ +export interface FileSubjectTokenSupplierOptions { + /** + * The file path where the external credential is located. + */ + filePath: string; + /** + * The token file or URL response type (JSON or text). + */ + formatType: SubjectTokenFormatType; + /** + * For JSON response types, this is the subject_token field name. For Azure, + * this is access_token. For text response types, this is ignored. + */ + subjectTokenFieldName?: string; +} +/** + * Internal subject token supplier implementation used when a file location + * is configured in the credential configuration used to build an {@link IdentityPoolClient} + */ +export declare class FileSubjectTokenSupplier implements SubjectTokenSupplier { + private readonly filePath; + private readonly formatType; + private readonly subjectTokenFieldName?; + /** + * Instantiates a new file based subject token supplier. + * @param opts The file subject token supplier options to build the supplier + * with. + */ + constructor(opts: FileSubjectTokenSupplierOptions); + /** + * 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. + */ + getSubjectToken(): Promise; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.js b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.js new file mode 100644 index 0000000000000000000000000000000000000000..fc89fc668987f1e9be2f17d524b2357430c6a87a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.js @@ -0,0 +1,84 @@ +"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.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)(fs.readFile ?? (() => { })); +const realpath = (0, util_1.promisify)(fs.realpath ?? (() => { })); +const lstat = (0, util_1.promisify)(fs.lstat ?? (() => { })); +/** + * Internal subject token supplier implementation used when a file location + * is configured in the credential configuration used to build an {@link IdentityPoolClient} + */ +class FileSubjectTokenSupplier { + filePath; + formatType; + subjectTokenFieldName; + /** + * 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() { + // 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; +//# sourceMappingURL=filesubjecttokensupplier.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/googleauth.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/googleauth.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..87c491bf97aa530c4e72c6d9c98b06e59d7e10bd --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/googleauth.d.ts @@ -0,0 +1,383 @@ +import { GaxiosOptions, GaxiosResponse } from 'gaxios'; +import * as stream from 'stream'; +import { CredentialBody, ImpersonatedJWTInput, JWTInput } from './credentials'; +import { IdTokenClient } from './idtokenclient'; +import { GCPEnv } from './envDetect'; +import { JWT } from './jwtclient'; +import { UserRefreshClient } from './refreshclient'; +import { Impersonated } from './impersonated'; +import { ExternalAccountClientOptions } from './externalclient'; +import { BaseExternalAccountClient } from './baseexternalclient'; +import { AuthClient, AuthClientOptions } from './authclient'; +import { ExternalAccountAuthorizedUserClient } from './externalAccountAuthorizedUserClient'; +import { AnyAuthClient, AnyAuthClientConstructor } from '..'; +/** + * Defines all types of explicit clients that are determined via ADC JSON + * config file. + */ +export type JSONClient = JWT | UserRefreshClient | BaseExternalAccountClient | ExternalAccountAuthorizedUserClient | Impersonated; +export interface ProjectIdCallback { + (err?: Error | null, projectId?: string | null): void; +} +export interface CredentialCallback { + (err: Error | null, result?: JSONClient): void; +} +export interface ADCCallback { + (err: Error | null, credential?: AuthClient, projectId?: string | null): void; +} +export interface ADCResponse { + credential: AuthClient; + projectId: string | null; +} +export interface GoogleAuthOptions { + /** + * An API key to use, optional. Cannot be used with {@link GoogleAuthOptions.credentials `credentials`}. + */ + apiKey?: string; + /** + * An `AuthClient` to use + */ + authClient?: T; + /** + * Path to a .json, .pem, or .p12 key file + */ + keyFilename?: string; + /** + * Path to a .json, .pem, or .p12 key file + */ + keyFile?: string; + /** + * Object containing client_email and private_key properties, or the + * external account client options. + * Cannot be used with {@link GoogleAuthOptions.apiKey `apiKey`}. + * + * @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}. + */ + credentials?: JWTInput | ExternalAccountClientOptions; + /** + * `AuthClientOptions` object passed to the constructor of the client + */ + clientOptions?: Extract[0], AuthClientOptions>; + /** + * Required scopes for the desired API request + */ + scopes?: string | string[]; + /** + * Your project ID. + */ + projectId?: string; + /** + * The default service domain for a given Cloud universe. + * + * This is an ergonomic equivalent to {@link clientOptions}'s `universeDomain` + * property and will be set for all generated {@link AuthClient}s. + */ + universeDomain?: string; +} +export declare const GoogleAuthExceptionMessages: { + readonly API_KEY_WITH_CREDENTIALS: "API Keys and Credentials are mutually exclusive authentication methods and cannot be used together."; + readonly NO_PROJECT_ID_FOUND: string; + readonly NO_CREDENTIALS_FOUND: string; + readonly NO_ADC_FOUND: "Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information."; + readonly NO_UNIVERSE_DOMAIN_FOUND: string; +}; +export declare class GoogleAuth { + #private; + /** + * Caches a value indicating whether the auth layer is running on Google + * Compute Engine. + * @private + */ + private checkIsGCE?; + useJWTAccessWithScope?: boolean; + defaultServicePath?: string; + get isGCE(): boolean | undefined; + private _findProjectIdPromise?; + private _cachedProjectId?; + jsonContent: JWTInput | ExternalAccountClientOptions | null; + apiKey: string | null; + cachedCredential: AnyAuthClient | T | null; + /** + * Scopes populated by the client library by default. We differentiate between + * these and user defined scopes when deciding whether to use a self-signed JWT. + */ + defaultScopes?: string | string[]; + private keyFilename?; + private scopes?; + private clientOptions; + /** + * 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?: GoogleAuthOptions); + setGapicJWTValues(client: JWT): void; + /** + * Obtains the default project ID for the application. + * + * Retrieves in the following order of precedence: + * - The `projectId` provided in this object's construction + * - 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 + */ + getProjectId(): Promise; + getProjectId(callback: ProjectIdCallback): void; + /** + * 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`) + */ + private getProjectIdOptional; + /** + * 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 + */ + private findAndCacheProjectId; + private getProjectIdAsync; + /** + * Retrieves a universe domain from the metadata server via + * {@link gcpMetadata.universe}. + * + * @returns a universe domain + */ + getUniverseDomainFromMetadataServer(): Promise; + /** + * 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 + */ + getUniverseDomain(): Promise; + /** + * @returns Any scopes (user-specified or default scopes specified by the + * client library) that need to be set on the current Auth client. + */ + private getAnyScopes; + /** + * Obtains the default service-level credentials for the application. + * @param callback Optional callback. + * @returns Promise that resolves with the ADCResponse (if no callback was + * passed). + */ + getApplicationDefault(): Promise; + getApplicationDefault(callback: ADCCallback): void; + getApplicationDefault(options: AuthClientOptions): Promise; + getApplicationDefault(options: AuthClientOptions, callback: ADCCallback): void; + private getApplicationDefaultAsync; + /** + * 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 + */ + _checkIsGCE(): Promise; + /** + * Attempts to load default credentials from the environment variable path.. + * @returns Promise that resolves with the OAuth2Client or null. + * @api private + */ + _tryGetApplicationCredentialsFromEnvironmentVariable(options?: AuthClientOptions): Promise; + /** + * Attempts to load default credentials from a well-known file location + * @return Promise that resolves with the OAuth2Client or null. + * @api private + */ + _tryGetApplicationCredentialsFromWellKnownFile(options?: AuthClientOptions): Promise; + /** + * 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 + */ + _getApplicationCredentialsFromFilePath(filePath: string, options?: AuthClientOptions): Promise; + /** + * 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: ImpersonatedJWTInput): Impersonated; + /** + * 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: JWTInput | ImpersonatedJWTInput, options?: AuthClientOptions): JSONClient; + /** + * 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 + */ + private _cacheClientFromJSON; + /** + * Create a credentials instance using the given input stream. + * @param inputStream The input stream. + * @param callback Optional callback. + */ + fromStream(inputStream: stream.Readable): Promise; + fromStream(inputStream: stream.Readable, callback: CredentialCallback): void; + fromStream(inputStream: stream.Readable, options: AuthClientOptions): Promise; + fromStream(inputStream: stream.Readable, options: AuthClientOptions, callback: CredentialCallback): void; + private fromStreamAsync; + /** + * 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: string, options?: AuthClientOptions): JWT; + /** + * Determines whether the current operating system is Windows. + * @api private + */ + private _isWindows; + /** + * Run the Google Cloud SDK command that prints the default project ID + */ + private getDefaultServiceProjectId; + /** + * Loads the project id from environment variables. + * @api private + */ + private getProductionProjectId; + /** + * Loads the project id from the GOOGLE_APPLICATION_CREDENTIALS json file. + * @api private + */ + private getFileProjectId; + /** + * Gets the project ID from external account client if available. + */ + private getExternalAccountClientProjectId; + /** + * Gets the Compute Engine project ID if it can be inferred. + */ + private getGCEProjectId; + /** + * The callback function handles a credential object that contains the + * client_email and private_key (if exists). + * getCredentials first checks if the client is using an external account and + * uses the service account email in place of client_email. + * If that doesn't exist, it checks for these values from the user JSON. + * If the user JSON doesn't exist, and the environment is on GCE, it gets the + * client_email from the cloud metadata server. + * @param callback Callback that handles the credential object that contains + * a client_email and optional private key, or the error. + * returned + */ + getCredentials(): Promise; + getCredentials(callback: (err: Error | null, credentials?: CredentialBody) => void): void; + private getCredentialsAsync; + /** + * Automatically obtain an {@link AuthClient `AuthClient`} based on the + * provided configuration. If no options were passed, use Application + * Default Credentials. + */ + getClient(): Promise; + /** + * 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. + */ + getIdTokenClient(targetAudience: string): Promise; + /** + * Automatically obtain application default credentials, and return + * an access token for making requests. + */ + getAccessToken(): Promise; + /** + * Obtain the HTTP headers that will provide authorization for a given + * request. + */ + getRequestHeaders(url?: string | URL): Promise; + /** + * 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 + */ + authorizeRequest(opts?: Pick): Promise>; + /** + * A {@link fetch `fetch`} compliant API for {@link GoogleAuth}. + * + * @see {@link GoogleAuth.request} for the classic method. + * + * @remarks + * + * This is useful as a drop-in replacement for `fetch` API usage. + * + * @example + * + * ```ts + * const auth = new GoogleAuth(); + * const fetchWithAuth: typeof fetch = (...args) => auth.fetch(...args); + * await fetchWithAuth('https://example.com'); + * ``` + * + * @param args `fetch` API or {@link Gaxios.fetch `Gaxios#fetch`} parameters + * @returns the {@link GaxiosResponse} with Gaxios-added properties + */ + fetch(...args: Parameters): Promise>; + /** + * Automatically obtain application default credentials, and make an + * HTTP request using the given options. + * + * @see {@link GoogleAuth.fetch} for the modern method. + * + * @param opts Axios request options for the HTTP request. + */ + request(opts: GaxiosOptions): Promise>; + /** + * Determine the compute environment in which the code is running. + */ + getEnv(): Promise; + /** + * 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/'); + * ``` + */ + sign(data: string, endpoint?: string): Promise; + private signBlob; +} +export interface SignBlobResponse { + keyId: string; + signedBlob: string; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/googleauth.js b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/googleauth.js new file mode 100644 index 0000000000000000000000000000000000000000..5e1a6d38c0344048b84f7243e0cf0ee1f8fa6f8d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/googleauth.js @@ -0,0 +1,867 @@ +"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.GoogleAuth = exports.GoogleAuthExceptionMessages = void 0; +const child_process_1 = require("child_process"); +const fs = require("fs"); +const gaxios_1 = require("gaxios"); +const gcpMetadata = require("gcp-metadata"); +const os = require("os"); +const path = require("path"); +const crypto_1 = require("../crypto/crypto"); +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.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 { + /** + * Caches a value indicating whether the auth layer is running on Google + * Compute Engine. + * @private + */ + checkIsGCE = undefined; + useJWTAccessWithScope; + defaultServicePath; + // Note: this properly is only public to satisfy unit tests. + // https://github.com/Microsoft/TypeScript/issues/5228 + get isGCE() { + return this.checkIsGCE; + } + _findProjectIdPromise; + _cachedProjectId; + // To save the contents of the JSON credential file + jsonContent = null; + apiKey; + cachedCredential = null; + /** + * A pending {@link AuthClient}. Used for concurrent {@link GoogleAuth.getClient} calls. + */ + #pendingAuthClient = null; + /** + * Scopes populated by the client library by default. We differentiate between + * these and user defined scopes when deciding whether to use a self-signed JWT. + */ + defaultScopes; + keyFilename; + scopes; + clientOptions = {}; + /** + * 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 = {}) { + 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 ||= await this.getProductionProjectId(); + projectId ||= await this.getFileProjectId(); + projectId ||= await this.getDefaultServiceProjectId(); + projectId ||= await this.getGCEProjectId(); + 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() { + let universeDomain; + try { + universeDomain = await gcpMetadata.universe('universe-domain'); + universeDomain ||= authclient_1.DEFAULT_UNIVERSE; + } + catch (e) { + if (e && e?.response?.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 ??= (await this.getClient()).universeDomain; + } + catch { + // client or ADC is not available + 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 this.#prepareAndCacheClient(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 this.#prepareAndCacheClient(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 this.#prepareAndCacheClient(credential); + } + // Determine if we're running on GCE. + if (await this._checkIsGCE()) { + options.scopes = this.getAnyScopes(); + return await this.#prepareAndCacheClient(new computeclient_1.Compute(options)); + } + throw new Error(exports.GoogleAuthExceptionMessages.NO_ADC_FOUND); + } + async #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 }; + } + /** + * 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) { + 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 (json.service_account_impersonation_url?.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 = /(?[^/]+):(generateAccessToken|generateIdToken)$/.exec(json.service_account_impersonation_url)?.groups?.target; + if (!targetPrincipal) { + throw new RangeError(`Cannot extract target principal from ${json.service_account_impersonation_url}`); + } + const targetScopes = this.getAnyScopes() ?? []; + 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 + this.#pendingAuthClient = + this.#pendingAuthClient || this.#determineClient(); + try { + return await this.#pendingAuthClient; + } + finally { + // reset the pending auth client in case it is changed later + this.#pendingAuthClient = null; + } + } + async #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 this.#prepareAndCacheClient(client); + return credential; + } + else { + const { credential } = await this.getApplicationDefaultAsync(this.clientOptions); + return credential; + } + } + /** + * 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 = {}) { + const url = opts.url; + const client = await this.getClient(); + const headers = await client.getRequestHeaders(url); + opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers, headers); + return opts; + } + /** + * A {@link fetch `fetch`} compliant API for {@link GoogleAuth}. + * + * @see {@link GoogleAuth.request} for the classic method. + * + * @remarks + * + * This is useful as a drop-in replacement for `fetch` API usage. + * + * @example + * + * ```ts + * const auth = new GoogleAuth(); + * const fetchWithAuth: typeof fetch = (...args) => auth.fetch(...args); + * await fetchWithAuth('https://example.com'); + * ``` + * + * @param args `fetch` API or {@link Gaxios.fetch `Gaxios#fetch`} parameters + * @returns the {@link GaxiosResponse} with Gaxios-added properties + */ + async fetch(...args) { + const client = await this.getClient(); + return client.fetch(...args); + } + /** + * Automatically obtain application default credentials, and make an + * HTTP request using the given options. + * + * @see {@link GoogleAuth.fetch} for the modern method. + * + * @param opts Axios request options for the HTTP request. + */ + 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; +//# sourceMappingURL=googleauth.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/iam.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/iam.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..93470a4439cb77cb5f703701f424c481306920a4 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/iam.d.ts @@ -0,0 +1,23 @@ +export interface RequestMetadata { + 'x-goog-iam-authority-selector': string; + 'x-goog-iam-authorization-token': string; +} +export declare class IAMAuth { + selector: string; + token: string; + /** + * IAM credentials. + * + * @param selector the iam authority selector + * @param token the token + * @constructor + */ + constructor(selector: string, token: string); + /** + * Acquire the HTTP headers required to make an authenticated request. + */ + getRequestHeaders(): { + 'x-goog-iam-authority-selector': string; + 'x-goog-iam-authorization-token': string; + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/iam.js b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/iam.js new file mode 100644 index 0000000000000000000000000000000000000000..d8999fd64de3eb97a75cce27b07883ef15258f64 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/iam.js @@ -0,0 +1,44 @@ +"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 { + selector; + token; + /** + * 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; +//# sourceMappingURL=iam.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/identitypoolclient.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/identitypoolclient.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..19eb41dfbab0c30f13590b3614f328ae6490bf17 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/identitypoolclient.d.ts @@ -0,0 +1,132 @@ +import { BaseExternalAccountClient, BaseExternalAccountClientOptions, ExternalAccountSupplierContext } from './baseexternalclient'; +import { SnakeToCamelObject } from '../util'; +export type SubjectTokenFormatType = 'json' | 'text'; +export interface SubjectTokenJsonResponse { + [key: string]: string; +} +/** + * Supplier interface for subject tokens. This can be implemented to + * return a subject token which can then be exchanged for a GCP token by an + * {@link IdentityPoolClient}. + */ +export interface SubjectTokenSupplier { + /** + * Gets a valid subject token for the requested external account identity. + * Note that these are not cached by the calling {@link IdentityPoolClient}, + * so caching should be including in the implementation. + * @param context {@link ExternalAccountSupplierContext} from the calling + * {@link IdentityPoolClient}, contains the requested audience and subject token type + * for the external account identity as well as the transport from the + * calling client to use for requests. + * @return A promise that resolves with the requested subject token string. + */ + getSubjectToken: (context: ExternalAccountSupplierContext) => Promise; +} +/** + * Url-sourced/file-sourced credentials json interface. + * This is used for K8s and Azure workloads. + */ +export interface IdentityPoolClientOptions extends BaseExternalAccountClientOptions { + /** + * Object containing options to retrieve identity pool credentials. A valid credential + * source or a subject token supplier must be specified. + */ + credential_source?: { + /** + * The file location to read the subject token from. Either this, a URL + * or a certificate location should be specified. + */ + file?: string; + /** + * The URL to call to retrieve the subject token. Either this, a file + * location or a certificate location should be specified. + */ + url?: string; + /** + * Optional headers to send on the request to the specified URL. + */ + headers?: { + [key: string]: string; + }; + /** + * The format that the subject token is in the file or the URL response. + * If not provided, will default to reading the text string directly. + */ + format?: { + /** + * The format type. Can either be 'text' or 'json'. + */ + type: SubjectTokenFormatType; + /** + * The field name containing the subject token value if the type is 'json'. + */ + subject_token_field_name?: string; + }; + /** + * The certificate location to call to retrieve the subject token. Either this, a file + * location, or an url should be specified. + * @example + * File Format: + * ```json + * { + * "cert_configs": { + * "workload": { + * "key_path": "$PATH_TO_LEAF_KEY", + * "cert_path": "$PATH_TO_LEAF_CERT" + * } + * } + * } + * ``` + */ + certificate?: { + /** + * Specify whether the certificate config should be used from the default location. + * Either this or the certificate_config_location must be provided. + * The certificate config file must be in the following JSON format: + */ + use_default_certificate_config?: boolean; + /** + * Location to fetch certificate config from in case default config is not to be used. + * Either this or use_default_certificate_config=true should be provided. + */ + certificate_config_location?: string; + /** + * TrustChainPath specifies the path to a PEM-formatted file containing the X.509 certificate trust chain. + * The file should contain any intermediate certificates needed to connect + * the mTLS leaf certificate to a root certificate in the trust store. + */ + trust_chain_path?: string; + }; + }; + /** + * The subject token supplier to call to retrieve the subject token to exchange + * for a GCP access token. Either this or a valid credential source should + * be specified. + */ + subject_token_supplier?: SubjectTokenSupplier; +} +/** + * Defines the Url-sourced and file-sourced external account clients mainly + * used for K8s and Azure workloads. + */ +export declare class IdentityPoolClient extends BaseExternalAccountClient { + private readonly subjectTokenSupplier; + /** + * 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. + */ + constructor(options: IdentityPoolClientOptions | SnakeToCamelObject); + /** + * 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. + */ + retrieveSubjectToken(): Promise; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/identitypoolclient.js b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/identitypoolclient.js new file mode 100644 index 0000000000000000000000000000000000000000..3b3f0b3bca016031e681c1882bcf92f11da899f8 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/identitypoolclient.js @@ -0,0 +1,131 @@ +"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"); +const certificatesubjecttokensupplier_1 = require("./certificatesubjecttokensupplier"); +const stscredentials_1 = require("./stscredentials"); +const gaxios_1 = require("gaxios"); +/** + * Defines the Url-sourced and file-sourced external account clients mainly + * used for K8s and Azure workloads. + */ +class IdentityPoolClient extends baseexternalclient_1.BaseExternalAccountClient { + subjectTokenSupplier; + /** + * 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. + */ + constructor(options) { + super(options); + 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 certificate = credentialSourceOpts.get('certificate'); + const headers = credentialSourceOpts.get('headers'); + if ((file && url) || (url && certificate) || (file && certificate)) { + throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.'); + } + else if (file) { + this.credentialSourceType = 'file'; + this.subjectTokenSupplier = new filesubjecttokensupplier_1.FileSubjectTokenSupplier({ + filePath: file, + formatType: formatType, + subjectTokenFieldName: formatSubjectTokenFieldName, + }); + } + else if (url) { + this.credentialSourceType = 'url'; + this.subjectTokenSupplier = new urlsubjecttokensupplier_1.UrlSubjectTokenSupplier({ + url: url, + formatType: formatType, + subjectTokenFieldName: formatSubjectTokenFieldName, + headers: headers, + additionalGaxiosOptions: IdentityPoolClient.RETRY_CONFIG, + }); + } + else if (certificate) { + this.credentialSourceType = 'certificate'; + const certificateSubjecttokensupplier = new certificatesubjecttokensupplier_1.CertificateSubjectTokenSupplier({ + useDefaultCertificateConfig: certificate.use_default_certificate_config, + certificateConfigLocation: certificate.certificate_config_location, + trustChainPath: certificate.trust_chain_path, + }); + this.subjectTokenSupplier = certificateSubjecttokensupplier; + } + else { + throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.'); + } + } + } + /** + * 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() { + const subjectToken = await this.subjectTokenSupplier.getSubjectToken(this.supplierContext); + if (this.subjectTokenSupplier instanceof certificatesubjecttokensupplier_1.CertificateSubjectTokenSupplier) { + const mtlsAgent = await this.subjectTokenSupplier.createMtlsHttpsAgent(); + this.stsCredential = new stscredentials_1.StsCredentials({ + tokenExchangeEndpoint: this.getTokenUrl(), + clientAuthentication: this.clientAuth, + transporter: new gaxios_1.Gaxios({ agent: mtlsAgent }), + }); + this.transporter = new gaxios_1.Gaxios({ + ...(this.transporter.defaults || {}), + agent: mtlsAgent, + }); + } + return subjectToken; + } +} +exports.IdentityPoolClient = IdentityPoolClient; +//# sourceMappingURL=identitypoolclient.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/idtokenclient.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/idtokenclient.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..78b80b454d7fe86a74525dc3474058193d98534a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/idtokenclient.d.ts @@ -0,0 +1,27 @@ +import { OAuth2Client, OAuth2ClientOptions, RequestMetadataResponse } from './oauth2client'; +export interface IdTokenOptions extends OAuth2ClientOptions { + /** + * The client to make the request to fetch an ID token. + */ + idTokenProvider: IdTokenProvider; + /** + * The audience to use when requesting an ID token. + */ + targetAudience: string; +} +export interface IdTokenProvider { + fetchIdToken: (targetAudience: string) => Promise; +} +export declare class IdTokenClient extends OAuth2Client { + targetAudience: string; + idTokenProvider: IdTokenProvider; + /** + * 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: IdTokenOptions); + protected getRequestMetadataAsync(): Promise; + private getIdTokenExpiryDate; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/idtokenclient.js b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/idtokenclient.js new file mode 100644 index 0000000000000000000000000000000000000000..7deb96e1f0104f5bb722fde9e1e4ac743aae5b2d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/idtokenclient.js @@ -0,0 +1,56 @@ +"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 { + targetAudience; + idTokenProvider; + /** + * 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() { + 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 = new 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; +//# sourceMappingURL=idtokenclient.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/impersonated.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/impersonated.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fed007ddc70dfd31b2132c3a923c8833a82a0ada --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/impersonated.d.ts @@ -0,0 +1,127 @@ +/** + * 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. + */ +import { GetTokenResponse, OAuth2Client, OAuth2ClientOptions } from './oauth2client'; +import { AuthClient } from './authclient'; +import { IdTokenProvider } from './idtokenclient'; +import { SignBlobResponse } from './googleauth'; +export interface ImpersonatedOptions extends OAuth2ClientOptions { + /** + * Client used to perform exchange for impersonated client. + */ + sourceClient?: AuthClient; + /** + * The service account to impersonate. + */ + targetPrincipal?: string; + /** + * Scopes to request during the authorization grant. + */ + targetScopes?: string[]; + /** + * The chained list of delegates required to grant the final access_token. + */ + delegates?: string[]; + /** + * Number of seconds the delegated credential should be valid. + */ + lifetime?: number | 3600; + /** + * API endpoint to fetch token from. + */ + endpoint?: string; +} +export declare const IMPERSONATED_ACCOUNT_TYPE = "impersonated_service_account"; +export interface TokenResponse { + accessToken: string; + expireTime: string; +} +export interface FetchIdTokenOptions { + /** + * Include the service account email in the token. + * If set to `true`, the token will contain `email` and `email_verified` claims. + */ + includeEmail: boolean; +} +export interface FetchIdTokenResponse { + /** The OpenId Connect ID token. */ + token: string; +} +export declare class Impersonated extends OAuth2Client implements IdTokenProvider { + private sourceClient; + private targetPrincipal; + private targetScopes; + private delegates; + private lifetime; + private endpoint; + /** + * 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?: ImpersonatedOptions); + /** + * 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 + */ + sign(blobToSign: string): Promise; + /** The service account email to be impersonated. */ + getTargetPrincipal(): string; + /** + * Refreshes the access token. + */ + protected refreshToken(): Promise; + /** + * 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 + */ + fetchIdToken(targetAudience: string, options?: FetchIdTokenOptions): Promise; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/impersonated.js b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/impersonated.js new file mode 100644 index 0000000000000000000000000000000000000000..25643a40bb38ddf0e38998f88b6251f05f8a1330 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/impersonated.js @@ -0,0 +1,190 @@ +"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 { + sourceClient; + targetPrincipal; + targetScopes; + delegates; + lifetime; + endpoint; + /** + * 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 = {}) { + 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 = options.sourceClient ?? new oauth2client_1.OAuth2Client(); + this.targetPrincipal = options.targetPrincipal ?? ''; + this.delegates = options.delegates ?? []; + this.targetScopes = options.targetScopes ?? []; + this.lifetime = options.lifetime ?? 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 = + options.endpoint ?? `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() { + 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 = error?.response?.data?.error?.status; + message = error?.response?.data?.error?.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) { + 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: options?.includeEmail ?? true, + useEmailAzp: options?.includeEmail ?? true, + }; + const res = await this.sourceClient.request({ + ...Impersonated.RETRY_CONFIG, + url: u, + data: body, + method: 'POST', + }); + return res.data.token; + } +} +exports.Impersonated = Impersonated; +//# sourceMappingURL=impersonated.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/jwtaccess.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/jwtaccess.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7467cfe749297c118734e6778903a7571673130c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/jwtaccess.d.ts @@ -0,0 +1,61 @@ +import * as stream from 'stream'; +import { JWTInput } from './credentials'; +export interface Claims { + [index: string]: string; +} +export declare class JWTAccess { + email?: string | null; + key?: string | null; + keyId?: string | null; + projectId?: string; + eagerRefreshThresholdMillis: number; + private cache; + /** + * 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?: string | null, key?: string | null, keyId?: string | null, eagerRefreshThresholdMillis?: number); + /** + * 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?: string, scopes?: string | string[]): string; + /** + * 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?: string, additionalClaims?: Claims, scopes?: string | string[]): 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. + */ + private static getExpirationTime; + /** + * Create a JWTAccess credentials instance using the given input options. + * @param json The input object. + */ + fromJSON(json: JWTInput): void; + /** + * Create a JWTAccess credentials instance using the given input stream. + * @param inputStream The input stream. + * @param callback Optional callback. + */ + fromStream(inputStream: stream.Readable): Promise; + fromStream(inputStream: stream.Readable, callback: (err?: Error) => void): void; + private fromStreamAsync; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/jwtaccess.js b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/jwtaccess.js new file mode 100644 index 0000000000000000000000000000000000000000..1b3c6056b35994b8448f5c0f15efe447dae3a49c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/jwtaccess.js @@ -0,0 +1,201 @@ +"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 { + email; + key; + keyId; + projectId; + eagerRefreshThresholdMillis; + cache = new util_1.LRUCache({ + capacity: 500, + maxAge: 60 * 60 * 1000, + }); + /** + * 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.email = email; + this.key = key; + this.keyId = keyId; + this.eagerRefreshThresholdMillis = + 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) { + // Copying headers into a new `Headers` object to avoid potential leakage - + // as this is a cache it is possible for multiple requests to reference this + // same value. + return new Headers(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 = new 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; +//# sourceMappingURL=jwtaccess.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/jwtclient.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/jwtclient.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..37cfaac9e1a99e6c1f1daef8e474946f1ccf10f0 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/jwtclient.d.ts @@ -0,0 +1,137 @@ +import { GoogleToken } from 'gtoken'; +import * as stream from 'stream'; +import { CredentialBody, Credentials, JWTInput } from './credentials'; +import { IdTokenProvider } from './idtokenclient'; +import { GetTokenResponse, OAuth2Client, OAuth2ClientOptions, RequestMetadataResponse } from './oauth2client'; +export interface JWTOptions extends OAuth2ClientOptions { + /** + * The service account email address. + */ + email?: string; + /** + * The path to private key file. Not necessary if {@link JWTOptions.key} has been provided. + */ + keyFile?: string; + /** + * The value of key. Not necessary if {@link JWTOptions.keyFile} has been provided. + */ + key?: string; + /** + * The list of requested scopes or a single scope. + */ + keyId?: string; + /** + * The impersonated account's email address. + */ + scopes?: string | string[]; + /** + * The ID of the key. + */ + subject?: string; + /** + * Additional claims, such as target audience. + * + * @example + * ``` + * {target_audience: 'targetAudience'} + * ``` + */ + additionalClaims?: {}; +} +export declare class JWT extends OAuth2Client implements IdTokenProvider { + email?: string; + keyFile?: string; + key?: string; + keyId?: string; + defaultScopes?: string | string[]; + scopes?: string | string[]; + scope?: string; + subject?: string; + gtoken?: GoogleToken; + additionalClaims?: {}; + useJWTAccessWithScope?: boolean; + defaultServicePath?: string; + private access?; + /** + * JWT service account credentials. + * + * Retrieve access token using gtoken. + * + * @param options the + */ + constructor(options?: JWTOptions); + /** + * 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?: string | string[]): JWT; + /** + * Obtains the metadata to be sent with the request. + * + * @param url the URI being authorized. + */ + protected getRequestMetadataAsync(url?: string | null): Promise; + /** + * Fetches an ID token. + * @param targetAudience the audience for the fetched ID token. + */ + fetchIdToken(targetAudience: string): Promise; + /** + * Determine if there are currently scopes available. + */ + private hasUserScopes; + /** + * Are there any default or user scopes defined. + */ + private hasAnyScopes; + /** + * Get the initial access token using gToken. + * @param callback Optional callback. + * @returns Promise that resolves with credentials + */ + authorize(): Promise; + authorize(callback: (err: Error | null, result?: Credentials) => void): void; + private authorizeAsync; + /** + * Refreshes the access token. + * @param refreshToken ignored + * @private + */ + protected refreshTokenNoCache(): Promise; + /** + * Create a gToken if it doesn't already exist. + */ + private createGToken; + /** + * 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: JWTInput): void; + /** + * Create a JWT credentials instance using the given input stream. + * @param inputStream The input stream. + * @param callback Optional callback. + * + * @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}. + */ + fromStream(inputStream: stream.Readable): Promise; + fromStream(inputStream: stream.Readable, callback: (err?: Error | null) => void): void; + private fromStreamAsync; + /** + * Creates a JWT credentials instance using an API Key for authentication. + * @param apiKey The API Key in string form. + */ + fromAPIKey(apiKey: string): void; + /** + * Using the key or keyFile on the JWT client, obtain an object that contains + * the key and the client email. + */ + getCredentials(): Promise; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/jwtclient.js b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/jwtclient.js new file mode 100644 index 0000000000000000000000000000000000000000..d51eab60c41e942c16b51eb5e006267a9d65502d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/jwtclient.js @@ -0,0 +1,300 @@ +"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 { + email; + keyFile; + key; + keyId; + defaultScopes; + scopes; + scope; + subject; + gtoken; + additionalClaims; + useJWTAccessWithScope; + defaultServicePath; + access; + /** + * JWT service account credentials. + * + * Retrieve access token using gtoken. + * + * @param options the + */ + constructor(options = {}) { + super(options); + this.email = options.email; + this.keyFile = options.keyFile; + this.key = options.key; + this.keyId = options.keyId; + this.scopes = options.scopes; + this.subject = options.subject; + this.additionalClaims = options.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(new Headers({ + 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 ?? 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: new 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() { + 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; +//# sourceMappingURL=jwtclient.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/loginticket.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/loginticket.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..33fd407a648d7904313936ccd016d81324a1a3fb --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/loginticket.d.ts @@ -0,0 +1,140 @@ +export declare class LoginTicket { + private envelope?; + private payload?; + /** + * 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?: string, pay?: TokenPayload); + getEnvelope(): string | undefined; + getPayload(): TokenPayload | undefined; + /** + * Create a simple class to extract user ID from an ID Token + * + * @return The user ID + */ + getUserId(): string | null; + /** + * Returns attributes from the login ticket. This can contain + * various information about the user session. + * + * @return The envelope and payload + */ + getAttributes(): { + envelope: string | undefined; + payload: TokenPayload | undefined; + }; +} +export interface TokenPayload { + /** + * The Issuer Identifier for the Issuer of the response. Always + * https://accounts.google.com or accounts.google.com for Google ID tokens. + */ + iss: string; + /** + * Access token hash. Provides validation that the access token is tied to the + * identity token. If the ID token is issued with an access token in the + * server flow, this is always included. This can be used as an alternate + * mechanism to protect against cross-site request forgery attacks, but if you + * follow Step 1 and Step 3 it is not necessary to verify the access token. + */ + at_hash?: string; + /** + * True if the user's e-mail address has been verified; otherwise false. + */ + email_verified?: boolean; + /** + * An identifier for the user, unique among all Google accounts and never + * reused. A Google account can have multiple emails at different points in + * time, but the sub value is never changed. Use sub within your application + * as the unique-identifier key for the user. + */ + sub: string; + /** + * The client_id of the authorized presenter. This claim is only needed when + * the party requesting the ID token is not the same as the audience of the ID + * token. This may be the case at Google for hybrid apps where a web + * application and Android app have a different client_id but share the same + * project. + */ + azp?: string; + /** + * The user's email address. This may not be unique and is not suitable for + * use as a primary key. Provided only if your scope included the string + * "email". + */ + email?: string; + /** + * The URL of the user's profile page. Might be provided when: + * - The request scope included the string "profile" + * - The ID token is returned from a token refresh + * - When profile claims are present, you can use them to update your app's + * user records. Note that this claim is never guaranteed to be present. + */ + profile?: string; + /** + * The URL of the user's profile picture. Might be provided when: + * - The request scope included the string "profile" + * - The ID token is returned from a token refresh + * - When picture claims are present, you can use them to update your app's + * user records. Note that this claim is never guaranteed to be present. + */ + picture?: string; + /** + * The user's full name, in a displayable form. Might be provided when: + * - The request scope included the string "profile" + * - The ID token is returned from a token refresh + * - When name claims are present, you can use them to update your app's user + * records. Note that this claim is never guaranteed to be present. + */ + name?: string; + /** + * The user's given name, in a displayable form. Might be provided when: + * - The request scope included the string "profile" + * - The ID token is returned from a token refresh + * - When name claims are present, you can use them to update your app's user + * records. Note that this claim is never guaranteed to be present. + */ + given_name?: string; + /** + * The user's family name, in a displayable form. Might be provided when: + * - The request scope included the string "profile" + * - The ID token is returned from a token refresh + * - When name claims are present, you can use them to update your app's user + * records. Note that this claim is never guaranteed to be present. + */ + family_name?: string; + /** + * Identifies the audience that this ID token is intended for. It must be one + * of the OAuth 2.0 client IDs of your application. + */ + aud: string; + /** + * The time the ID token was issued, represented in Unix time (integer + * seconds). + */ + iat: number; + /** + * The time the ID token expires, represented in Unix time (integer seconds). + */ + exp: number; + /** + * The value of the nonce supplied by your app in the authentication request. + * You should enforce protection against replay attacks by ensuring it is + * presented only once. + */ + nonce?: string; + /** + * The hosted G Suite domain of the user. Provided only if the user belongs to + * a hosted domain. + */ + hd?: string; + /** + * The user's locale, represented by a BCP 47 language tag. + * Might be provided when a name claim is present. + */ + locale?: string; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/loginticket.js b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/loginticket.js new file mode 100644 index 0000000000000000000000000000000000000000..858e6a5d2a371092f78d3d774b5409407659a994 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/loginticket.js @@ -0,0 +1,60 @@ +"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 { + envelope; + payload; + /** + * 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; +//# sourceMappingURL=loginticket.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/oauth2client.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/oauth2client.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..adce0da181ffe5d56857629236352ba283c67542 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/oauth2client.d.ts @@ -0,0 +1,610 @@ +import { GaxiosError, GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios'; +import * as querystring from 'querystring'; +import { JwkCertificate } from '../crypto/crypto'; +import { AuthClient, AuthClientOptions, GetAccessTokenResponse, BodyResponseCallback } from './authclient'; +import { Credentials } from './credentials'; +import { LoginTicket } from './loginticket'; +/** + * The results from the `generateCodeVerifierAsync` method. To learn more, + * See the sample: + * https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/oauth2-codeVerifier.js + */ +export interface CodeVerifierResults { + /** + * The code verifier that will be used when calling `getToken` to obtain a new + * access token. + */ + codeVerifier: string; + /** + * The code_challenge that should be sent with the `generateAuthUrl` call + * to obtain a verifiable authentication url. + */ + codeChallenge?: string; +} +export interface Certificates { + [index: string]: string | JwkCertificate; +} +export interface PublicKeys { + [index: string]: string; +} +export declare enum CodeChallengeMethod { + Plain = "plain", + S256 = "S256" +} +export declare enum CertificateFormat { + PEM = "PEM", + JWK = "JWK" +} +/** + * The client authentication type. Supported values are basic, post, and none. + * https://datatracker.ietf.org/doc/html/rfc7591#section-2 + */ +export declare enum ClientAuthentication { + ClientSecretPost = "ClientSecretPost", + ClientSecretBasic = "ClientSecretBasic", + None = "None" +} +export interface GetTokenOptions { + code: string; + codeVerifier?: string; + /** + * The client ID for your application. The value passed into the constructor + * will be used if not provided. Must match any client_id option passed to + * a corresponding call to generateAuthUrl. + */ + client_id?: string; + /** + * Determines where the API server redirects the user after the user + * completes the authorization flow. The value passed into the constructor + * will be used if not provided. Must match any redirect_uri option passed to + * a corresponding call to generateAuthUrl. + */ + redirect_uri?: string; +} +export interface TokenInfo { + /** + * The application that is the intended user of the access token. + */ + aud: string; + /** + * This value lets you correlate profile information from multiple Google + * APIs. It is only present in the response if you included the profile scope + * in your request in step 1. The field value is an immutable identifier for + * the logged-in user that can be used to create and manage user sessions in + * your application. The identifier is the same regardless of which client ID + * is used to retrieve it. This enables multiple applications in the same + * organization to correlate profile information. + */ + user_id?: string; + /** + * An array of scopes that the user granted access to. + */ + scopes: string[]; + /** + * The datetime when the token becomes invalid. + */ + expiry_date: number; + /** + * An identifier for the user, unique among all Google accounts and never + * reused. A Google account can have multiple emails at different points in + * time, but the sub value is never changed. Use sub within your application + * as the unique-identifier key for the user. + */ + sub?: string; + /** + * The client_id of the authorized presenter. This claim is only needed when + * the party requesting the ID token is not the same as the audience of the ID + * token. This may be the case at Google for hybrid apps where a web + * application and Android app have a different client_id but share the same + * project. + */ + azp?: string; + /** + * Indicates whether your application can refresh access tokens + * when the user is not present at the browser. Valid parameter values are + * 'online', which is the default value, and 'offline'. Set the value to + * 'offline' if your application needs to refresh access tokens when the user + * is not present at the browser. This value instructs the Google + * authorization server to return a refresh token and an access token the + * first time that your application exchanges an authorization code for + * tokens. + */ + access_type?: string; + /** + * The user's email address. This value may not be unique to this user and + * is not suitable for use as a primary key. Provided only if your scope + * included the email scope value. + */ + email?: string; + /** + * True if the user's e-mail address has been verified; otherwise false. + */ + email_verified?: boolean; +} +export interface GenerateAuthUrlOpts { + /** + * Recommended. Indicates whether your application can refresh access tokens + * when the user is not present at the browser. Valid parameter values are + * 'online', which is the default value, and 'offline'. Set the value to + * 'offline' if your application needs to refresh access tokens when the user + * is not present at the browser. This value instructs the Google + * authorization server to return a refresh token and an access token the + * first time that your application exchanges an authorization code for + * tokens. + */ + access_type?: string; + /** + * The hd (hosted domain) parameter streamlines the login process for G Suite + * hosted accounts. By including the domain of the G Suite user (for example, + * mycollege.edu), you can indicate that the account selection UI should be + * optimized for accounts at that domain. To optimize for G Suite accounts + * generally instead of just one domain, use an asterisk: hd=*. + * Don't rely on this UI optimization to control who can access your app, + * as client-side requests can be modified. Be sure to validate that the + * returned ID token has an hd claim value that matches what you expect + * (e.g. mycolledge.edu). Unlike the request parameter, the ID token claim is + * contained within a security token from Google, so the value can be trusted. + */ + hd?: string; + /** + * The 'response_type' will always be set to 'CODE'. + */ + response_type?: string; + /** + * The client ID for your application. The value passed into the constructor + * will be used if not provided. You can find this value in the API Console. + */ + client_id?: string; + /** + * Determines where the API server redirects the user after the user + * completes the authorization flow. The value must exactly match one of the + * 'redirect_uri' values listed for your project in the API Console. Note that + * the http or https scheme, case, and trailing slash ('/') must all match. + * The value passed into the constructor will be used if not provided. + */ + redirect_uri?: string; + /** + * Required. A space-delimited list of scopes that identify the resources that + * your application could access on the user's behalf. These values inform the + * consent screen that Google displays to the user. Scopes enable your + * application to only request access to the resources that it needs while + * also enabling users to control the amount of access that they grant to your + * application. Thus, there is an inverse relationship between the number of + * scopes requested and the likelihood of obtaining user consent. The + * OAuth 2.0 API Scopes document provides a full list of scopes that you might + * use to access Google APIs. We recommend that your application request + * access to authorization scopes in context whenever possible. By requesting + * access to user data in context, via incremental authorization, you help + * users to more easily understand why your application needs the access it is + * requesting. + */ + scope?: string[] | string; + /** + * Recommended. Specifies any string value that your application uses to + * maintain state between your authorization request and the authorization + * server's response. The server returns the exact value that you send as a + * name=value pair in the hash (#) fragment of the 'redirect_uri' after the + * user consents to or denies your application's access request. You can use + * this parameter for several purposes, such as directing the user to the + * correct resource in your application, sending nonces, and mitigating + * cross-site request forgery. Since your redirect_uri can be guessed, using a + * state value can increase your assurance that an incoming connection is the + * result of an authentication request. If you generate a random string or + * encode the hash of a cookie or another value that captures the client's + * state, you can validate the response to additionally ensure that the + * request and response originated in the same browser, providing protection + * against attacks such as cross-site request forgery. See the OpenID Connect + * documentation for an example of how to create and confirm a state token. + */ + state?: string; + /** + * Optional. Enables applications to use incremental authorization to request + * access to additional scopes in context. If you set this parameter's value + * to true and the authorization request is granted, then the new access token + * will also cover any scopes to which the user previously granted the + * application access. See the incremental authorization section for examples. + */ + include_granted_scopes?: boolean; + /** + * Optional. If your application knows which user is trying to authenticate, + * it can use this parameter to provide a hint to the Google Authentication + * Server. The server uses the hint to simplify the login flow either by + * prefilling the email field in the sign-in form or by selecting the + * appropriate multi-login session. Set the parameter value to an email + * address or sub identifier, which is equivalent to the user's Google ID. + */ + login_hint?: string; + /** + * Optional. A space-delimited, case-sensitive list of prompts to present the + * user. If you don't specify this parameter, the user will be prompted only + * the first time your app requests access. Possible values are: + * + * 'none' - Donot display any authentication or consent screens. Must not be + * specified with other values. + * 'consent' - Prompt the user for consent. + * 'select_account' - Prompt the user to select an account. + */ + prompt?: string; + /** + * Recommended. Specifies what method was used to encode a 'code_verifier' + * that will be used during authorization code exchange. This parameter must + * be used with the 'code_challenge' parameter. The value of the + * 'code_challenge_method' defaults to "plain" if not present in the request + * that includes a 'code_challenge'. The only supported values for this + * parameter are "S256" or "plain". + */ + code_challenge_method?: CodeChallengeMethod; + /** + * Recommended. Specifies an encoded 'code_verifier' that will be used as a + * server-side challenge during authorization code exchange. This parameter + * must be used with the 'code_challenge' parameter described above. + */ + code_challenge?: string; + /** + * A way for developers and/or the auth team to provide a set of key value + * pairs to be added as query parameters to the authorization url. + */ + [key: string]: querystring.ParsedUrlQueryInput[keyof querystring.ParsedUrlQueryInput]; +} +export interface AccessTokenResponse { + access_token: string; + expiry_date: number; +} +export interface GetRefreshHandlerCallback { + (): Promise; +} +export interface GetTokenCallback { + (err: GaxiosError | null, token?: Credentials | null, res?: GaxiosResponse | null): void; +} +export interface GetTokenResponse { + tokens: Credentials; + res: GaxiosResponse | null; +} +export interface GetAccessTokenCallback { + (err: GaxiosError | null, token?: string | null, res?: GaxiosResponse | null): void; +} +export interface RefreshAccessTokenCallback { + (err: GaxiosError | null, credentials?: Credentials | null, res?: GaxiosResponse | null): void; +} +export interface RefreshAccessTokenResponse { + credentials: Credentials; + res: GaxiosResponse | null; +} +export interface RequestMetadataResponse { + headers: Headers; + res?: GaxiosResponse | null; +} +export interface RequestMetadataCallback { + (err: GaxiosError | null, headers?: Headers, res?: GaxiosResponse | null): void; +} +export interface GetFederatedSignonCertsCallback { + (err: GaxiosError | null, certs?: Certificates, response?: GaxiosResponse | null): void; +} +export interface FederatedSignonCertsResponse { + certs: Certificates; + format: CertificateFormat; + res?: GaxiosResponse | null; +} +export interface GetIapPublicKeysCallback { + (err: GaxiosError | null, pubkeys?: PublicKeys, response?: GaxiosResponse | null): void; +} +export interface IapPublicKeysResponse { + pubkeys: PublicKeys; + res?: GaxiosResponse | null; +} +export interface RevokeCredentialsResult { + success: boolean; +} +export interface VerifyIdTokenOptions { + idToken: string; + audience?: string | string[]; + maxExpiry?: number; +} +export interface OAuth2ClientEndpoints { + /** + * The endpoint for viewing access token information + * + * @example + * 'https://oauth2.googleapis.com/tokeninfo' + */ + tokenInfoUrl: string | URL; + /** + * The base URL for auth endpoints. + * + * @example + * 'https://accounts.google.com/o/oauth2/v2/auth' + */ + oauth2AuthBaseUrl: string | URL; + /** + * The base endpoint for token retrieval + * . + * @example + * 'https://oauth2.googleapis.com/token' + */ + oauth2TokenUrl: string | URL; + /** + * The base endpoint to revoke tokens. + * + * @example + * 'https://oauth2.googleapis.com/revoke' + */ + oauth2RevokeUrl: string | URL; + /** + * Sign on certificates in PEM format. + * + * @example + * 'https://www.googleapis.com/oauth2/v1/certs' + */ + oauth2FederatedSignonPemCertsUrl: string | URL; + /** + * Sign on certificates in JWK format. + * + * @example + * 'https://www.googleapis.com/oauth2/v3/certs' + */ + oauth2FederatedSignonJwkCertsUrl: string | URL; + /** + * IAP Public Key URL. + * This URL contains a JSON dictionary that maps the `kid` claims to the public key values. + * + * @example + * 'https://www.gstatic.com/iap/verify/public_key' + */ + oauth2IapPublicKeyUrl: string | URL; +} +/** + * A convenient interface for those looking to pass the OAuth2 Client config via a parsed + * JSON file. + */ +interface OAuth2JSONOptions { + /** + * The authentication client ID. + * + * @alias {@link OAuth2ClientOptions.clientId} + */ + client_id?: string; + /** + * The authentication client secret. + * + * @alias {@link OAuth2ClientOptions.clientSecret} + */ + client_secret?: string; + /** + * The URIs to redirect to after completing the auth request. + * + * @alias {@link OAuth2ClientOptions.redirectUri} + */ + redirect_uris?: string[]; +} +export interface OAuth2ClientOptions extends AuthClientOptions, OAuth2JSONOptions { + /** + * The authentication client ID. + * + * @alias {@link OAuth2JSONOptions.client_id} + */ + clientId?: string; + /** + * The authentication client secret. + * + * @alias {@link OAuth2JSONOptions.client_secret} + */ + clientSecret?: string; + /** + * The URI to redirect to after completing the auth request. + * + * @alias {@link OAuth2JSONOptions.redirect_uris} + */ + redirectUri?: string; + /** + * Customizable endpoints. + */ + endpoints?: Partial; + /** + * The allowed OAuth2 token issuers. + */ + issuers?: string[]; + /** + * The client authentication type. Supported values are basic, post, and none. + * Defaults to post if not provided. + * https://datatracker.ietf.org/doc/html/rfc7591#section-2 + */ + clientAuthentication?: ClientAuthentication; +} +export type RefreshOptions = Pick; +export declare class OAuth2Client extends AuthClient { + private redirectUri?; + private certificateCache; + private certificateExpiry; + private certificateCacheFormat; + protected refreshTokenPromises: Map>; + readonly endpoints: Readonly; + readonly issuers: string[]; + readonly clientAuthentication: ClientAuthentication; + _clientId?: string; + _clientSecret?: string; + refreshHandler?: GetRefreshHandlerCallback; + /** + * An OAuth2 Client for Google APIs. + * + * @param options The OAuth2 Client Options. Passing an `clientId` directly is **@DEPRECATED**. + * @param clientSecret **@DEPRECATED**. Provide a {@link OAuth2ClientOptions `OAuth2ClientOptions`} object in the first parameter instead. + * @param redirectUri **@DEPRECATED**. Provide a {@link OAuth2ClientOptions `OAuth2ClientOptions`} object in the first parameter instead. + */ + constructor(options?: OAuth2ClientOptions | OAuth2ClientOptions['clientId'], + /** + * @deprecated - provide a {@link OAuth2ClientOptions `OAuth2ClientOptions`} object in the first parameter instead + */ + clientSecret?: OAuth2ClientOptions['clientSecret'], + /** + * @deprecated - provide a {@link OAuth2ClientOptions `OAuth2ClientOptions`} object in the first parameter instead + */ + redirectUri?: OAuth2ClientOptions['redirectUri']); + /** + * @deprecated use instance's {@link OAuth2Client.endpoints} + */ + protected static readonly GOOGLE_TOKEN_INFO_URL = "https://oauth2.googleapis.com/tokeninfo"; + /** + * Clock skew - five minutes in seconds + */ + private static readonly CLOCK_SKEW_SECS_; + /** + * The default max Token Lifetime is one day in seconds + */ + private static readonly DEFAULT_MAX_TOKEN_LIFETIME_SECS_; + /** + * Generates URL for consent page landing. + * @param opts Options. + * @return URL to consent page. + */ + generateAuthUrl(opts?: GenerateAuthUrlOpts): string; + generateCodeVerifier(): void; + /** + * 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 + */ + generateCodeVerifierAsync(): Promise; + /** + * Gets the access token for the given code. + * @param code The authorization code. + * @param callback Optional callback fn. + */ + getToken(code: string): Promise; + getToken(options: GetTokenOptions): Promise; + getToken(code: string, callback: GetTokenCallback): void; + getToken(options: GetTokenOptions, callback: GetTokenCallback): void; + private getTokenAsync; + /** + * Refreshes the access token. + * @param refresh_token Existing refresh token. + * @private + */ + protected refreshToken(refreshToken?: string | null): Promise; + protected refreshTokenNoCache(refreshToken?: string | null): Promise; + /** + * Retrieves the access token using refresh token + * + * @param callback callback + */ + refreshAccessToken(): Promise; + refreshAccessToken(callback: RefreshAccessTokenCallback): void; + private refreshAccessTokenAsync; + /** + * Get a non-expired access token, after refreshing if necessary + * + * @param callback Callback to call with the access token + */ + getAccessToken(): Promise; + getAccessToken(callback: GetAccessTokenCallback): void; + private getAccessTokenAsync; + /** + * 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 ' } + */ + getRequestHeaders(url?: string | URL): Promise; + protected getRequestMetadataAsync(url?: string | URL | null): Promise; + /** + * 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: string): string; + /** + * Generates a URL to revoke the given token. + * + * @param token The existing token to be revoked. + */ + getRevokeTokenURL(token: string): URL; + /** + * Revokes the access given to token. + * @param token The existing token to be revoked. + * @param callback Optional callback fn. + */ + revokeToken(token: string): GaxiosPromise; + revokeToken(token: string, callback: BodyResponseCallback): void; + /** + * Revokes access token and clears the credentials object + * @param callback callback + */ + revokeCredentials(): GaxiosPromise; + revokeCredentials(callback: BodyResponseCallback): void; + private revokeCredentialsAsync; + /** + * Provides a request implementation with OAuth 2.0 flow. If credentials have + * a refresh_token, in cases of HTTP 401 and 403 responses, it automatically + * asks for a new access token and replays the unsuccessful request. + * @param opts Request options. + * @param callback callback. + * @return Request object + */ + request(opts: GaxiosOptions): GaxiosPromise; + request(opts: GaxiosOptions, callback: BodyResponseCallback): void; + protected requestAsync(opts: GaxiosOptions, reAuthRetried?: boolean): Promise>; + /** + * Verify id token is token by checking the certs and audience + * @param options that contains all options. + * @param callback Callback supplying GoogleLogin if successful + */ + verifyIdToken(options: VerifyIdTokenOptions): Promise; + verifyIdToken(options: VerifyIdTokenOptions, callback: (err: Error | null, login?: LoginTicket) => void): void; + private verifyIdTokenAsync; + /** + * 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. + */ + getTokenInfo(accessToken: string): Promise; + /** + * Gets federated sign-on certificates to use for verifying identity tokens. + * Returns certs as array structure, where keys are key ids, and values + * are certificates in either PEM or JWK format. + * @param callback Callback supplying the certificates + */ + getFederatedSignonCerts(): Promise; + getFederatedSignonCerts(callback: GetFederatedSignonCertsCallback): void; + getFederatedSignonCertsAsync(): Promise; + /** + * Gets federated sign-on certificates to use for verifying identity tokens. + * Returns certs as array structure, where keys are key ids, and values + * are certificates in either PEM or JWK format. + * @param callback Callback supplying the certificates + */ + getIapPublicKeys(): Promise; + getIapPublicKeys(callback: GetIapPublicKeysCallback): void; + getIapPublicKeysAsync(): Promise; + verifySignedJwtWithCerts(): void; + /** + * 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. + */ + verifySignedJwtWithCertsAsync(jwt: string, certs: Certificates | PublicKeys, requiredAudience?: string | string[], issuers?: string[], maxExpiry?: number): Promise; + /** + * Returns a promise that resolves with AccessTokenResponse type if + * refreshHandler is defined. + * If not, nothing is returned. + */ + private processAndValidateRefreshHandler; + /** + * 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. + */ + protected isTokenExpiring(): boolean; +} +export {}; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/oauth2client.js b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/oauth2client.js new file mode 100644 index 0000000000000000000000000000000000000000..1b8503cc2c02ffb013edff20cb1a4d2900290006 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/oauth2client.js @@ -0,0 +1,820 @@ +"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 util_1 = require("../util"); +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 { + redirectUri; + certificateCache = {}; + certificateExpiry = null; + certificateCacheFormat = CertificateFormat.PEM; + refreshTokenPromises = new Map(); + endpoints; + issuers; + clientAuthentication; + // TODO: refactor tests to make this private + _clientId; + // TODO: refactor tests to make this private + _clientSecret; + refreshHandler; + /** + * An OAuth2 Client for Google APIs. + * + * @param options The OAuth2 Client Options. Passing an `clientId` directly is **@DEPRECATED**. + * @param clientSecret **@DEPRECATED**. Provide a {@link OAuth2ClientOptions `OAuth2ClientOptions`} object in the first parameter instead. + * @param redirectUri **@DEPRECATED**. Provide a {@link OAuth2ClientOptions `OAuth2ClientOptions`} object in the first parameter instead. + */ + constructor(options = {}, + /** + * @deprecated - provide a {@link OAuth2ClientOptions `OAuth2ClientOptions`} object in the first parameter instead + */ + clientSecret, + /** + * @deprecated - provide a {@link OAuth2ClientOptions `OAuth2ClientOptions`} object in the first parameter instead + */ + redirectUri) { + super(typeof options === 'object' ? options : {}); + if (typeof options !== 'object') { + options = { + clientId: options, + clientSecret, + redirectUri, + }; + } + this._clientId = options.clientId || options.client_id; + this._clientSecret = options.clientSecret || options.client_secret; + this.redirectUri = options.redirectUri || options.redirect_uris?.[0]; + 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', + ...options.endpoints, + }; + this.clientAuthentication = + options.clientAuthentication || ClientAuthentication.ClientSecretPost; + this.issuers = options.issuers || [ + 'accounts.google.com', + 'https://accounts.google.com', + this.universeDomain, + ]; + } + /** + * @deprecated use instance's {@link OAuth2Client.endpoints} + */ + static GOOGLE_TOKEN_INFO_URL = 'https://oauth2.googleapis.com/tokeninfo'; + /** + * Clock skew - five minutes in seconds + */ + static CLOCK_SKEW_SECS_ = 300; + /** + * The default max Token Lifetime is one day in seconds + */ + static DEFAULT_MAX_TOKEN_LIFETIME_SECS_ = 86400; + /** + * 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 = new Headers(); + 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.set('authorization', `Basic ${basic.toString('base64')}`); + } + if (this.clientAuthentication === ClientAuthentication.ClientSecretPost) { + values.client_secret = this._clientSecret; + } + const opts = { + ...OAuth2Client.RETRY_CONFIG, + method: 'POST', + url, + data: new URLSearchParams((0, util_1.removeUndefinedValuesInObject)(values)), + headers, + }; + authclient_1.AuthClient.setMethodName(opts, 'getTokenAsync'); + const res = await this.transporter.request(opts); + 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) { + 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 { + const opts = { + ...OAuth2Client.RETRY_CONFIG, + method: 'POST', + url, + data: new URLSearchParams((0, util_1.removeUndefinedValuesInObject)(data)), + }; + authclient_1.AuthClient.setMethodName(opts, 'refreshTokenNoCache'); + // request for new token + res = await this.transporter.request(opts); + } + catch (e) { + if (e instanceof gaxios_1.GaxiosError && + e.message === 'invalid_grant' && + e.response?.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?.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 ' } + */ + async getRequestHeaders(url) { + const headers = (await this.getRequestMetadataAsync(url)).headers; + return headers; + } + async getRequestMetadataAsync(url) { + 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 = new 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?.access_token) { + this.setCredentials(refreshedAccessToken); + const headers = new Headers({ + authorization: 'Bearer ' + this.credentials.access_token, + }); + return { headers: this.addSharedMetadataHeaders(headers) }; + } + } + if (this.apiKey) { + return { headers: new 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 = new 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', + }; + authclient_1.AuthClient.setMethodName(opts, 'revokeToken'); + 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) { + try { + const r = await this.getRequestMetadataAsync(); + opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers); + this.addUserProjectAndAuthHeaders(opts.headers, r.headers); + if (this.apiKey) { + opts.headers.set('X-Goog-Api-Key', this.apiKey); + } + return 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?.access_token) { + this.setCredentials(refreshedAccessToken); + } + return this.requestAsync(opts, true); + } + } + throw e; + } + } + 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;charset=UTF-8', + 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 { + const opts = { + ...OAuth2Client.RETRY_CONFIG, + url, + }; + authclient_1.AuthClient.setMethodName(opts, 'getFederatedSignonCertsAsync'); + res = await this.transporter.request(opts); + } + catch (e) { + if (e instanceof Error) { + e.message = `Failed to retrieve verification certificates: ${e.message}`; + } + throw e; + } + const cacheControl = res?.headers.get('cache-control'); + let cacheAge = -1; + if (cacheControl) { + const maxAge = /max-age=(?[0-9]+)/.exec(cacheControl)?.groups + ?.maxAge; + if (maxAge) { + // Cache results with max-age (in seconds) + cacheAge = Number(maxAge) * 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 { + const opts = { + ...OAuth2Client.RETRY_CONFIG, + url, + }; + authclient_1.AuthClient.setMethodName(opts, 'getIapPublicKeysAsync'); + res = await this.transporter.request(opts); + } + 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; +//# sourceMappingURL=oauth2client.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/oauth2common.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/oauth2common.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4e5b841cfd69489b8e581a2264d99452f57a8e56 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/oauth2common.d.ts @@ -0,0 +1,103 @@ +import { Gaxios, GaxiosOptions } from 'gaxios'; +/** + * OAuth error codes. + * https://tools.ietf.org/html/rfc6749#section-5.2 + */ +type OAuthErrorCode = 'invalid_request' | 'invalid_client' | 'invalid_grant' | 'unauthorized_client' | 'unsupported_grant_type' | 'invalid_scope' | string; +/** + * The standard OAuth error response. + * https://tools.ietf.org/html/rfc6749#section-5.2 + */ +export interface OAuthErrorResponse { + error: OAuthErrorCode; + error_description?: string; + error_uri?: string; +} +/** + * OAuth client authentication types. + * https://tools.ietf.org/html/rfc6749#section-2.3 + */ +export type ConfidentialClientType = 'basic' | 'request-body'; +/** + * Defines the client authentication credentials for basic and request-body + * credentials. + * https://tools.ietf.org/html/rfc6749#section-2.3.1 + */ +export interface ClientAuthentication { + confidentialClientType: ConfidentialClientType; + clientId: string; + clientSecret?: string; +} +export interface OAuthClientAuthHandlerOptions { + /** + * Defines the client authentication credentials for basic and request-body + * credentials. + */ + clientAuthentication?: ClientAuthentication; + /** + * An optional transporter to use. + */ + transporter?: Gaxios; +} +/** + * 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. + */ +export declare abstract class OAuthClientAuthHandler { + #private; + protected transporter: Gaxios; + /** + * Instantiates an OAuth client authentication handler. + * @param options The OAuth Client Auth Handler instance options. Passing an `ClientAuthentication` directly is **@DEPRECATED**. + */ + constructor(options?: ClientAuthentication | OAuthClientAuthHandlerOptions); + /** + * 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. + */ + protected applyClientAuthenticationOptions(opts: GaxiosOptions, bearerToken?: string): void; + /** + * 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. + */ + private injectAuthenticatedHeaders; + /** + * 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. + */ + private injectAuthenticatedRequestBody; + /** + * 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. + */ + protected static get RETRY_CONFIG(): GaxiosOptions; +} +/** + * 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. + */ +export declare function getErrorFromOAuthErrorResponse(resp: OAuthErrorResponse, err?: Error): Error; +export {}; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/oauth2common.js b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/oauth2common.js new file mode 100644 index 0000000000000000000000000000000000000000..f44448a2b387e2d765d0b8a8bc556ff3c34189db --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/oauth2common.js @@ -0,0 +1,189 @@ +"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 gaxios_1 = require("gaxios"); +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 { + #crypto = (0, crypto_1.createCrypto)(); + #clientAuthentication; + transporter; + /** + * Instantiates an OAuth client authentication handler. + * @param options The OAuth Client Auth Handler instance options. Passing an `ClientAuthentication` directly is **@DEPRECATED**. + */ + constructor(options) { + if (options && 'clientId' in options) { + this.#clientAuthentication = options; + this.transporter = new gaxios_1.Gaxios(); + } + else { + this.#clientAuthentication = options?.clientAuthentication; + this.transporter = options?.transporter || new gaxios_1.Gaxios(); + } + } + /** + * 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) { + opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers); + // 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) { + // Bearer token prioritized higher than basic Auth. + if (bearerToken) { + opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers, { + authorization: `Bearer ${bearerToken}`, + }); + } + else if (this.#clientAuthentication?.confidentialClientType === 'basic') { + opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers); + const clientId = this.#clientAuthentication.clientId; + const clientSecret = this.#clientAuthentication.clientSecret || ''; + const base64EncodedCreds = this.#crypto.encodeBase64StringUtf8(`${clientId}:${clientSecret}`); + gaxios_1.Gaxios.mergeHeaders(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) { + if (this.#clientAuthentication?.confidentialClientType === 'request-body') { + const method = (opts.method || 'GET').toUpperCase(); + if (!METHODS_SUPPORTING_REQUEST_BODY.includes(method)) { + throw new Error(`${method} HTTP method does not support ` + + `${this.#clientAuthentication.confidentialClientType} ` + + 'client authentication'); + } + // Get content-type + const headers = new Headers(opts.headers); + const contentType = headers.get('content-type'); + // Inject authenticated request body + if (contentType?.startsWith('application/x-www-form-urlencoded') || + opts.data instanceof URLSearchParams) { + const data = new URLSearchParams(opts.data ?? ''); + data.append('client_id', this.#clientAuthentication.clientId); + data.append('client_secret', this.#clientAuthentication.clientSecret || ''); + opts.data = data; + } + else if (contentType?.startsWith('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'); + } + } + } + /** + * 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, { + value: err[key], + writable: false, + enumerable: true, + }); + } + }); + } + return newError; +} +//# sourceMappingURL=oauth2common.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/passthrough.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/passthrough.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..355da8a40629e596c244a7dc4f59088721c4b8f3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/passthrough.d.ts @@ -0,0 +1,37 @@ +import { GaxiosOptions } from 'gaxios'; +import { AuthClient, GetAccessTokenResponse } from './authclient'; +/** + * An AuthClient without any Authentication information. Useful for: + * - Anonymous access + * - Local Emulators + * - Testing Environments + * + */ +export declare class PassThroughClient extends 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. + */ + request(opts: GaxiosOptions): Promise>; + /** + * A required method of the base class. + * Always will return an empty object. + * + * @returns {} + */ + getAccessToken(): Promise; + /** + * A required method of the base class. + * Always will return an empty object. + * + * @returns {} + */ + getRequestHeaders(): Promise; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/passthrough.js b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/passthrough.js new file mode 100644 index 0000000000000000000000000000000000000000..928bb12cfdd5beed2cea29c04c1493bea30cf7f7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/passthrough.js @@ -0,0 +1,60 @@ +"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 new Headers(); + } +} +exports.PassThroughClient = PassThroughClient; +//# sourceMappingURL=passthrough.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/pluggable-auth-client.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/pluggable-auth-client.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0ba47c7f67a306664af87b97df51c13c0eb7b9cc --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/pluggable-auth-client.d.ts @@ -0,0 +1,141 @@ +import { BaseExternalAccountClient, BaseExternalAccountClientOptions } from './baseexternalclient'; +export { ExecutableError } from './pluggable-auth-handler'; +/** + * Defines the credential source portion of the configuration for PluggableAuthClient. + * + *

Command is the only required field. If timeout_millis is not specified, the library will + * default to a 30-second timeout. + * + *

+ * Sample credential source for Pluggable Auth Client:
+ * {
+ *   ...
+ *   "credential_source": {
+ *     "executable": {
+ *       "command": "/path/to/get/credentials.sh --arg1=value1 --arg2=value2",
+ *       "timeout_millis": 5000,
+ *       "output_file": "/path/to/generated/cached/credentials"
+ *     }
+ *   }
+ * }
+ * 
+ */ +export interface PluggableAuthClientOptions extends BaseExternalAccountClientOptions { + credential_source: { + executable: { + /** + * The command used to retrieve the 3rd party token. + */ + command: string; + /** + * The timeout for executable to run in milliseconds. If none is provided it + * will be set to the default timeout of 30 seconds. + */ + timeout_millis?: number; + /** + * An optional output file location that will be checked for a cached response + * from a previous run of the executable. + */ + output_file?: string; + }; + }; +} +/** + * 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. + */ +export declare class PluggableAuthClient extends BaseExternalAccountClient { + /** + * The command used to retrieve the third party token. + */ + private readonly command; + /** + * The timeout in milliseconds for running executable, + * set to default if none provided. + */ + private readonly timeoutMillis; + /** + * The path to file to check for cached executable response. + */ + private readonly outputFile?; + /** + * Executable and output file handler. + */ + private readonly handler; + /** + * 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. + */ + constructor(options: PluggableAuthClientOptions); + /** + * 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. + */ + retrieveSubjectToken(): Promise; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/pluggable-auth-client.js b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/pluggable-auth-client.js new file mode 100644 index 0000000000000000000000000000000000000000..e9cf39ff8114b7bbc5f1099fcc8844cb1d753329 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/pluggable-auth-client.js @@ -0,0 +1,220 @@ +"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"); +var pluggable_auth_handler_2 = require("./pluggable-auth-handler"); +Object.defineProperty(exports, "ExecutableError", { enumerable: true, get: function () { return pluggable_auth_handler_2.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 { + /** + * The command used to retrieve the third party token. + */ + command; + /** + * The timeout in milliseconds for running executable, + * set to default if none provided. + */ + timeoutMillis; + /** + * The path to file to check for cached executable response. + */ + outputFile; + /** + * Executable and output file handler. + */ + handler; + /** + * 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. + */ + constructor(options) { + super(options); + 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 pluggable_auth_handler_1.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; +//# sourceMappingURL=pluggable-auth-client.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d881b237c85bf0f9875015db18dfdccfa372ff54 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.d.ts @@ -0,0 +1,61 @@ +import { ExecutableResponse } from './executable-response'; +/** + * Error thrown from the executable run by PluggableAuthClient. + */ +export declare class ExecutableError extends Error { + /** + * The exit code returned by the executable. + */ + readonly code: string; + constructor(message: string, code: string); +} +/** + * Defines the options used for the PluggableAuthHandler class. + */ +export interface PluggableAuthHandlerOptions { + /** + * The command used to retrieve the third party token. + */ + command: string; + /** + * The timeout in milliseconds for running executable, + * set to default if none provided. + */ + timeoutMillis: number; + /** + * The path to file to check for cached executable response. + */ + outputFile?: string; +} +/** + * A handler used to retrieve 3rd party token responses from user defined + * executables and cached file output for the PluggableAuthClient class. + */ +export declare class PluggableAuthHandler { + private readonly commandComponents; + private readonly timeoutMillis; + private readonly outputFile?; + /** + * Instantiates a PluggableAuthHandler instance using the provided + * PluggableAuthHandlerOptions object. + */ + constructor(options: PluggableAuthHandlerOptions); + /** + * 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: Map): Promise; + /** + * 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. + */ + retrieveCachedResponse(): Promise; + /** + * Parses given command string into component array, splitting on spaces unless + * spaces are between quotation marks. + */ + private static parseCommand; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.js b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.js new file mode 100644 index 0000000000000000000000000000000000000000..c2ddc19fc50cbe06f0b3b89b755d043e8e67b66f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.js @@ -0,0 +1,174 @@ +"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 = exports.ExecutableError = void 0; +const executable_response_1 = require("./executable-response"); +const childProcess = require("child_process"); +const fs = require("fs"); +/** + * Error thrown from the executable run by PluggableAuthClient. + */ +class ExecutableError extends Error { + /** + * The exit code returned by the executable. + */ + code; + 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; +/** + * A handler used to retrieve 3rd party token responses from user defined + * executables and cached file output for the PluggableAuthClient class. + */ +class PluggableAuthHandler { + commandComponents; + timeoutMillis; + outputFile; + /** + * 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 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 { + // 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; +//# sourceMappingURL=pluggable-auth-handler.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/refreshclient.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/refreshclient.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fdf22b7cd3f241f62a2af78e3c86cf3c7ea139cc --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/refreshclient.d.ts @@ -0,0 +1,75 @@ +import * as stream from 'stream'; +import { JWTInput } from './credentials'; +import { GetTokenResponse, OAuth2Client, OAuth2ClientOptions } from './oauth2client'; +export declare const USER_REFRESH_ACCOUNT_TYPE = "authorized_user"; +export interface UserRefreshClientOptions extends OAuth2ClientOptions { + /** + * The authentication client ID. + */ + clientId?: string; + /** + * The authentication client secret. + */ + clientSecret?: string; + /** + * The authentication refresh token. + */ + refreshToken?: string; +} +export declare class UserRefreshClient extends OAuth2Client { + _refreshToken?: string | null; + /** + * The User Refresh Token client. + * + * @param optionsOrClientId The User Refresh Token client options. Passing an `clientId` directly is **@DEPRECATED**. + * @param clientSecret **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead. + * @param refreshToken **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead. + * @param eagerRefreshThresholdMillis **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead. + * @param forceRefreshOnFailure **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead. + */ + constructor(optionsOrClientId?: string | UserRefreshClientOptions, + /** + * @deprecated - provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead + */ + clientSecret?: UserRefreshClientOptions['clientSecret'], + /** + * @deprecated - provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead + */ + refreshToken?: UserRefreshClientOptions['refreshToken'], + /** + * @deprecated - provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead + */ + eagerRefreshThresholdMillis?: UserRefreshClientOptions['eagerRefreshThresholdMillis'], + /** + * @deprecated - provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead + */ + forceRefreshOnFailure?: UserRefreshClientOptions['forceRefreshOnFailure']); + /** + * Refreshes the access token. + * @param refreshToken An ignored refreshToken.. + * @param callback Optional callback. + */ + protected refreshTokenNoCache(): Promise; + fetchIdToken(targetAudience: string): Promise; + /** + * Create a UserRefreshClient credentials instance using the given input + * options. + * @param json The input object. + */ + fromJSON(json: JWTInput): void; + /** + * Create a UserRefreshClient credentials instance using the given input + * stream. + * @param inputStream The input stream. + * @param callback Optional callback. + */ + fromStream(inputStream: stream.Readable): Promise; + fromStream(inputStream: stream.Readable, callback: (err?: Error) => void): void; + private fromStreamAsync; + /** + * Create a UserRefreshClient credentials instance using the given input + * options. + * @param json The input object. + */ + static fromJSON(json: JWTInput): UserRefreshClient; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/refreshclient.js b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/refreshclient.js new file mode 100644 index 0000000000000000000000000000000000000000..0c1b8747d956bc8760a2f867f348b4131d3ed3ac --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/refreshclient.js @@ -0,0 +1,159 @@ +"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 authclient_1 = require("./authclient"); +exports.USER_REFRESH_ACCOUNT_TYPE = 'authorized_user'; +class UserRefreshClient extends oauth2client_1.OAuth2Client { + // TODO: refactor tests to make this private + // In a future gts release, the _propertyName rule will be lifted. + // This is also a hard one because `this.refreshToken` is a function. + _refreshToken; + /** + * The User Refresh Token client. + * + * @param optionsOrClientId The User Refresh Token client options. Passing an `clientId` directly is **@DEPRECATED**. + * @param clientSecret **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead. + * @param refreshToken **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead. + * @param eagerRefreshThresholdMillis **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead. + * @param forceRefreshOnFailure **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead. + */ + constructor(optionsOrClientId, + /** + * @deprecated - provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead + */ + clientSecret, + /** + * @deprecated - provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead + */ + refreshToken, + /** + * @deprecated - provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead + */ + eagerRefreshThresholdMillis, + /** + * @deprecated - provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead + */ + 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() { + return super.refreshTokenNoCache(this._refreshToken); + } + async fetchIdToken(targetAudience) { + const opts = { + ...UserRefreshClient.RETRY_CONFIG, + url: this.endpoints.oauth2TokenUrl, + method: 'POST', + data: new URLSearchParams({ + client_id: this._clientId, + client_secret: this._clientSecret, + grant_type: 'refresh_token', + refresh_token: this._refreshToken, + target_audience: targetAudience, + }), + }; + authclient_1.AuthClient.setMethodName(opts, 'fetchIdToken'); + const res = await this.transporter.request(opts); + 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; +//# sourceMappingURL=refreshclient.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/stscredentials.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/stscredentials.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c2d89570e3044a928f892798c906433145479c52 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/stscredentials.d.ts @@ -0,0 +1,125 @@ +import { GaxiosResponse } from 'gaxios'; +import { HeadersInit } from './authclient'; +import { ClientAuthentication, OAuthClientAuthHandler, OAuthClientAuthHandlerOptions } from './oauth2common'; +/** + * Defines the interface needed to initialize an StsCredentials instance. + * The interface does not directly map to the spec and instead is converted + * to be compliant with the JavaScript style guide. This is because this is + * instantiated internally. + * StsCredentials implement the OAuth 2.0 token exchange based on + * https://tools.ietf.org/html/rfc8693. + * Request options are defined in + * https://tools.ietf.org/html/rfc8693#section-2.1 + */ +export interface StsCredentialsOptions { + /** + * REQUIRED. The value "urn:ietf:params:oauth:grant-type:token-exchange" + * indicates that a token exchange is being performed. + */ + grantType: string; + /** + * OPTIONAL. A URI that indicates the target service or resource where the + * client intends to use the requested security token. + */ + resource?: string; + /** + * OPTIONAL. The logical name of the target service where the client + * intends to use the requested security token. This serves a purpose + * similar to the "resource" parameter but with the client providing a + * logical name for the target service. + */ + audience?: string; + /** + * OPTIONAL. A list of space-delimited, case-sensitive strings, as defined + * in Section 3.3 of [RFC6749], that allow the client to specify the desired + * scope of the requested security token in the context of the service or + * resource where the token will be used. + */ + scope?: string[]; + /** + * OPTIONAL. An identifier, as described in Section 3 of [RFC8693], eg. + * "urn:ietf:params:oauth:token-type:access_token" for the type of the + * requested security token. + */ + requestedTokenType?: string; + /** + * REQUIRED. A security token that represents the identity of the party on + * behalf of whom the request is being made. + */ + subjectToken: string; + /** + * REQUIRED. An identifier, as described in Section 3 of [RFC8693], that + * indicates the type of the security token in the "subject_token" parameter. + */ + subjectTokenType: string; + actingParty?: { + /** + * OPTIONAL. A security token that represents the identity of the acting + * party. Typically, this will be the party that is authorized to use the + * requested security token and act on behalf of the subject. + */ + actorToken: string; + /** + * An identifier, as described in Section 3, that indicates the type of the + * security token in the "actor_token" parameter. This is REQUIRED when the + * "actor_token" parameter is present in the request but MUST NOT be + * included otherwise. + */ + actorTokenType: string; + }; +} +/** + * Defines the OAuth 2.0 token exchange successful response based on + * https://tools.ietf.org/html/rfc8693#section-2.2.1 + */ +export interface StsSuccessfulResponse { + access_token: string; + issued_token_type: string; + token_type: string; + expires_in?: number; + refresh_token?: string; + scope?: string; + res?: GaxiosResponse | null; +} +export interface StsCredentialsConstructionOptions extends OAuthClientAuthHandlerOptions { + /** + * The client authentication credentials if available. + */ + clientAuthentication?: ClientAuthentication; + /** + * The token exchange endpoint. + */ + tokenExchangeEndpoint: string | URL; +} +/** + * Implements the OAuth 2.0 token exchange based on + * https://tools.ietf.org/html/rfc8693 + */ +export declare class StsCredentials extends OAuthClientAuthHandler { + #private; + /** + * Initializes an STS credentials instance. + * + * @param options The STS credentials instance options. Passing an `tokenExchangeEndpoint` directly is **@DEPRECATED**. + * @param clientAuthentication **@DEPRECATED**. Provide a {@link StsCredentialsConstructionOptions `StsCredentialsConstructionOptions`} object in the first parameter instead. + */ + constructor(options?: StsCredentialsConstructionOptions | string | URL, + /** + * @deprecated - provide a {@link StsCredentialsConstructionOptions `StsCredentialsConstructionOptions`} object in the first parameter instead + */ + clientAuthentication?: ClientAuthentication); + /** + * 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. + */ + exchangeToken(stsCredentialsOptions: StsCredentialsOptions, headers?: HeadersInit, options?: Parameters[0]): Promise; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/stscredentials.js b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/stscredentials.js new file mode 100644 index 0000000000000000000000000000000000000000..c75f473dc55e0961f389525e5eaafb67721b2301 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/stscredentials.js @@ -0,0 +1,106 @@ +"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 authclient_1 = require("./authclient"); +const oauth2common_1 = require("./oauth2common"); +const util_1 = require("../util"); +/** + * Implements the OAuth 2.0 token exchange based on + * https://tools.ietf.org/html/rfc8693 + */ +class StsCredentials extends oauth2common_1.OAuthClientAuthHandler { + #tokenExchangeEndpoint; + /** + * Initializes an STS credentials instance. + * + * @param options The STS credentials instance options. Passing an `tokenExchangeEndpoint` directly is **@DEPRECATED**. + * @param clientAuthentication **@DEPRECATED**. Provide a {@link StsCredentialsConstructionOptions `StsCredentialsConstructionOptions`} object in the first parameter instead. + */ + constructor(options = { + tokenExchangeEndpoint: '', + }, + /** + * @deprecated - provide a {@link StsCredentialsConstructionOptions `StsCredentialsConstructionOptions`} object in the first parameter instead + */ + clientAuthentication) { + if (typeof options !== 'object' || options instanceof URL) { + options = { + tokenExchangeEndpoint: options, + clientAuthentication, + }; + } + super(options); + this.#tokenExchangeEndpoint = options.tokenExchangeEndpoint; + } + /** + * 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, headers, options) { + const values = { + grant_type: stsCredentialsOptions.grantType, + resource: stsCredentialsOptions.resource, + audience: stsCredentialsOptions.audience, + scope: stsCredentialsOptions.scope?.join(' '), + requested_token_type: stsCredentialsOptions.requestedTokenType, + subject_token: stsCredentialsOptions.subjectToken, + subject_token_type: stsCredentialsOptions.subjectTokenType, + actor_token: stsCredentialsOptions.actingParty?.actorToken, + actor_token_type: stsCredentialsOptions.actingParty?.actorTokenType, + // Non-standard GCP-specific options. + options: options && JSON.stringify(options), + }; + const opts = { + ...StsCredentials.RETRY_CONFIG, + url: this.#tokenExchangeEndpoint.toString(), + method: 'POST', + headers, + data: new URLSearchParams((0, util_1.removeUndefinedValuesInObject)(values)), + }; + authclient_1.AuthClient.setMethodName(opts, 'exchangeToken'); + // 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; +//# sourceMappingURL=stscredentials.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1c6d088395e397c8d58bf516cb9e5deeb83fd16d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.d.ts @@ -0,0 +1,57 @@ +import { ExternalAccountSupplierContext } from './baseexternalclient'; +import { GaxiosOptions } from 'gaxios'; +import { SubjectTokenFormatType, SubjectTokenSupplier } from './identitypoolclient'; +/** + * Interface that defines options used to build a {@link UrlSubjectTokenSupplier} + */ +export interface UrlSubjectTokenSupplierOptions { + /** + * The URL to call to retrieve the subject token. This is typically a local + * metadata server. + */ + url: string; + /** + * The token file or URL response type (JSON or text). + */ + formatType: SubjectTokenFormatType; + /** + * For JSON response types, this is the subject_token field name. For Azure, + * this is access_token. For text response types, this is ignored. + */ + subjectTokenFieldName?: string; + /** + * The optional additional headers to send with the request to the metadata + * server url. + */ + headers?: { + [key: string]: string; + }; + /** + * Additional gaxios options to use for the request to the specified URL. + */ + additionalGaxiosOptions?: GaxiosOptions; +} +/** + * Internal subject token supplier implementation used when a URL + * is configured in the credential configuration used to build an {@link IdentityPoolClient} + */ +export declare class UrlSubjectTokenSupplier implements SubjectTokenSupplier { + private readonly url; + private readonly headers?; + private readonly formatType; + private readonly subjectTokenFieldName?; + private readonly additionalGaxiosOptions?; + /** + * Instantiates a URL subject token supplier. + * @param opts The URL subject token supplier options to build the supplier with. + */ + constructor(opts: UrlSubjectTokenSupplierOptions); + /** + * 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. + */ + getSubjectToken(context: ExternalAccountSupplierContext): Promise; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.js b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.js new file mode 100644 index 0000000000000000000000000000000000000000..76af8b8e5f5cb3bac72d20cae471bf30e55c87c1 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.js @@ -0,0 +1,70 @@ +"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; +const authclient_1 = require("./authclient"); +/** + * Internal subject token supplier implementation used when a URL + * is configured in the credential configuration used to build an {@link IdentityPoolClient} + */ +class UrlSubjectTokenSupplier { + url; + headers; + formatType; + subjectTokenFieldName; + additionalGaxiosOptions; + /** + * 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, + }; + authclient_1.AuthClient.setMethodName(opts, 'getSubjectToken'); + 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; +//# sourceMappingURL=urlsubjecttokensupplier.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/crypto/browser/crypto.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/crypto/browser/crypto.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..40a1b24d0043d39d318872394d33247ed75cefcb --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/crypto/browser/crypto.d.ts @@ -0,0 +1,27 @@ +import { Crypto, JwkCertificate } from '../shared'; +export declare class BrowserCrypto implements Crypto { + constructor(); + sha256DigestBase64(str: string): Promise; + randomBytesBase64(count: number): string; + private static padBase64; + verify(pubkey: JwkCertificate, data: string, signature: string): Promise; + sign(privateKey: JwkCertificate, data: string): Promise; + decodeBase64StringUtf8(base64: string): string; + encodeBase64StringUtf8(text: string): string; + /** + * 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. + */ + sha256DigestHex(str: string): Promise; + /** + * 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. + */ + signWithHmacSha256(key: string | ArrayBuffer, msg: string): Promise; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/crypto/browser/crypto.js b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/crypto/browser/crypto.js new file mode 100644 index 0000000000000000000000000000000000000000..1c35c0372560382dca0ba4a85e0377ba89126a08 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/crypto/browser/crypto.js @@ -0,0 +1,127 @@ +"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 shared_1 = require("../shared"); +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, shared_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; +//# sourceMappingURL=crypto.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/crypto/crypto.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/crypto/crypto.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..10d8d753d1e6e2fa596b2131c098855f708f5809 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/crypto/crypto.d.ts @@ -0,0 +1,8 @@ +import { Crypto } from './shared'; +export * from './shared'; +export interface CryptoSigner { + update(data: string): void; + sign(key: string, outputFormat: string): string; +} +export declare function createCrypto(): Crypto; +export declare function hasBrowserCrypto(): boolean; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/crypto/crypto.js b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/crypto/crypto.js new file mode 100644 index 0000000000000000000000000000000000000000..794b528bab0d676350d516ed78b17dab21696efe --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/crypto/crypto.js @@ -0,0 +1,54 @@ +"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 */ +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.createCrypto = createCrypto; +exports.hasBrowserCrypto = hasBrowserCrypto; +const crypto_1 = require("./browser/crypto"); +const crypto_2 = require("./node/crypto"); +__exportStar(require("./shared"), exports); +// Crypto interface will provide required crypto functions. +// Use `createCrypto()` factory function to create an instance +// of Crypto. It will either use Node.js `crypto` module, or +// use browser's SubtleCrypto interface. Since most of the +// SubtleCrypto methods return promises, we must make those +// methods return promises here as well, even though in Node.js +// they are synchronous. +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'); +} +//# sourceMappingURL=crypto.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/crypto/node/crypto.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/crypto/node/crypto.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ccd6dbb5ea41d4f63c26b5246de509849b36e632 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/crypto/node/crypto.d.ts @@ -0,0 +1,25 @@ +import { Crypto } from '../shared'; +export declare class NodeCrypto implements Crypto { + sha256DigestBase64(str: string): Promise; + randomBytesBase64(count: number): string; + verify(pubkey: string, data: string | Buffer, signature: string): Promise; + sign(privateKey: string, data: string | Buffer): Promise; + decodeBase64StringUtf8(base64: string): string; + encodeBase64StringUtf8(text: string): string; + /** + * 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. + */ + sha256DigestHex(str: string): Promise; + /** + * 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. + */ + signWithHmacSha256(key: string | ArrayBuffer, msg: string): Promise; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/crypto/node/crypto.js b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/crypto/node/crypto.js new file mode 100644 index 0000000000000000000000000000000000000000..38e36331a765e3fa9c6cd144e01644b3710e9367 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/crypto/node/crypto.js @@ -0,0 +1,83 @@ +"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); +} +//# sourceMappingURL=crypto.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/crypto/shared.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/crypto/shared.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c18f698434241cba6728ecdd66f4d6d007ba37a6 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/crypto/shared.d.ts @@ -0,0 +1,47 @@ +/** + * Crypto interface will provide required crypto functions. + * Use `createCrypto()` factory function to create an instance + * of Crypto. It will either use Node.js `crypto` module, or + * use browser's SubtleCrypto interface. Since most of the + * SubtleCrypto methods return promises, we must make those + * methods return promises here as well, even though in Node.js + * they are synchronous. + */ +export interface Crypto { + sha256DigestBase64(str: string): Promise; + randomBytesBase64(n: number): string; + verify(pubkey: string | JwkCertificate, data: string | Buffer, signature: string): Promise; + sign(privateKey: string | JwkCertificate, data: string | Buffer): Promise; + decodeBase64StringUtf8(base64: string): string; + encodeBase64StringUtf8(text: string): string; + /** + * 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. + */ + sha256DigestHex(str: string): Promise; + /** + * 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. + */ + signWithHmacSha256(key: string | ArrayBuffer, msg: string): Promise; +} +export interface JwkCertificate { + kty: string; + alg: string; + use?: string; + kid: string; + n: string; + e: string; +} +/** + * Converts an ArrayBuffer to a hexadecimal string. + * @param arrayBuffer The ArrayBuffer to convert to hexadecimal string. + * @return The hexadecimal encoding of the ArrayBuffer. + */ +export declare function fromArrayBufferToHex(arrayBuffer: ArrayBuffer): string; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/crypto/shared.js b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/crypto/shared.js new file mode 100644 index 0000000000000000000000000000000000000000..ad3396721ebb8511a7f3668305deb2d3057266dd --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/crypto/shared.js @@ -0,0 +1,32 @@ +"use strict"; +// Copyright 2025 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.fromArrayBufferToHex = fromArrayBufferToHex; +/** + * 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(''); +} +//# sourceMappingURL=shared.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/index.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1379de9c106537feda2f3dafe08e2a9a1e929446 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/index.d.ts @@ -0,0 +1,36 @@ +import { GoogleAuth } from './auth/googleauth'; +export * as gcpMetadata from 'gcp-metadata'; +export * as gaxios from 'gaxios'; +import { AuthClient } from './auth/authclient'; +export { AuthClient, DEFAULT_UNIVERSE } from './auth/authclient'; +export { Compute, ComputeOptions } from './auth/computeclient'; +export { CredentialBody, CredentialRequest, Credentials, JWTInput, } from './auth/credentials'; +export { GCPEnv } from './auth/envDetect'; +export { GoogleAuthOptions, ProjectIdCallback } from './auth/googleauth'; +export { IAMAuth, RequestMetadata } from './auth/iam'; +export { IdTokenClient, IdTokenProvider } from './auth/idtokenclient'; +export { Claims, JWTAccess } from './auth/jwtaccess'; +export { JWT, JWTOptions } from './auth/jwtclient'; +export { Impersonated, ImpersonatedOptions } from './auth/impersonated'; +export { Certificates, CodeChallengeMethod, CodeVerifierResults, GenerateAuthUrlOpts, GetTokenOptions, OAuth2Client, OAuth2ClientOptions, RefreshOptions, TokenInfo, VerifyIdTokenOptions, ClientAuthentication, } from './auth/oauth2client'; +export { LoginTicket, TokenPayload } from './auth/loginticket'; +export { UserRefreshClient, UserRefreshClientOptions, } from './auth/refreshclient'; +export { AwsClient, AwsClientOptions, AwsSecurityCredentialsSupplier, } from './auth/awsclient'; +export { AwsSecurityCredentials, AwsRequestSigner, } from './auth/awsrequestsigner'; +export { IdentityPoolClient, IdentityPoolClientOptions, SubjectTokenSupplier, } from './auth/identitypoolclient'; +export { ExternalAccountClient, ExternalAccountClientOptions, } from './auth/externalclient'; +export { BaseExternalAccountClient, BaseExternalAccountClientOptions, SharedExternalAccountClientOptions, ExternalAccountSupplierContext, IamGenerateAccessTokenResponse, } from './auth/baseexternalclient'; +export { CredentialAccessBoundary, DownscopedClient, } from './auth/downscopedclient'; +export { PluggableAuthClient, PluggableAuthClientOptions, ExecutableError, } from './auth/pluggable-auth-client'; +export { PassThroughClient } from './auth/passthrough'; +type ALL_EXPORTS = (typeof import('./'))[keyof typeof import('./')]; +/** + * A union type for all {@link AuthClient `AuthClient`} constructors. + */ +export type AnyAuthClientConstructor = Extract; +/** + * A union type for all {@link AuthClient `AuthClient`}s. + */ +export type AnyAuthClient = InstanceType; +declare const auth: GoogleAuth; +export { auth, GoogleAuth }; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/index.js new file mode 100644 index 0000000000000000000000000000000000000000..b589b8581aaedaec6412c3a197e8e2cc495d288b --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/index.js @@ -0,0 +1,67 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GoogleAuth = exports.auth = 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; } }); +const auth = new googleauth_1.GoogleAuth(); +exports.auth = auth; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/shared.cjs b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/shared.cjs new file mode 100644 index 0000000000000000000000000000000000000000..8fb472b6de6e2c56d9cc76b38bd3dae63f214946 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/shared.cjs @@ -0,0 +1,22 @@ +"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.USER_AGENT = exports.PRODUCT_NAME = exports.pkg = void 0; +const pkg = require('../../package.json'); +exports.pkg = pkg; +const PRODUCT_NAME = 'google-api-nodejs-client'; +exports.PRODUCT_NAME = PRODUCT_NAME; +const USER_AGENT = `${PRODUCT_NAME}/${pkg.version}`; +exports.USER_AGENT = USER_AGENT; +//# sourceMappingURL=shared.cjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/shared.d.cts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/shared.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..50fa3df9de13408efec818cfb57b3641f4fda2df --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/shared.d.cts @@ -0,0 +1,7 @@ +declare const pkg: { + name: string; + version: string; +}; +declare const PRODUCT_NAME = "google-api-nodejs-client"; +declare const USER_AGENT: string; +export { pkg, PRODUCT_NAME, USER_AGENT }; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/util.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/util.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9f14b34c1c2a7ab945e8a67a30c62936aac3507e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/util.d.ts @@ -0,0 +1,151 @@ +/** + * A utility for converting snake_case to camelCase. + * + * For, for example `my_snake_string` becomes `mySnakeString`. + */ +export type SnakeToCamel = S extends `${infer FirstWord}_${infer Remainder}` ? `${FirstWord}${Capitalize>}` : S; +/** + * A utility for converting an type's keys from snake_case + * to camelCase, if the keys are strings. + * + * For example: + * + * ```ts + * { + * my_snake_string: boolean; + * myCamelString: string; + * my_snake_obj: { + * my_snake_obj_string: string; + * }; + * } + * ``` + * + * becomes: + * + * ```ts + * { + * mySnakeString: boolean; + * myCamelString: string; + * mySnakeObj: { + * mySnakeObjString: string; + * } + * } + * ``` + * + * @remarks + * + * The generated documentation for the camelCase'd properties won't be available + * until {@link https://github.com/microsoft/TypeScript/issues/50715} has been + * resolved. + */ +export type SnakeToCamelObject = { + [K in keyof T as SnakeToCamel]: T[K] extends {} ? SnakeToCamelObject : T[K]; +}; +/** + * A utility for adding camelCase versions of a type's snake_case keys, if the + * keys are strings, preserving any existing keys. + * + * For example: + * + * ```ts + * { + * my_snake_boolean: boolean; + * myCamelString: string; + * my_snake_obj: { + * my_snake_obj_string: string; + * }; + * } + * ``` + * + * becomes: + * + * ```ts + * { + * my_snake_boolean: boolean; + * mySnakeBoolean: boolean; + * myCamelString: string; + * my_snake_obj: { + * my_snake_obj_string: string; + * }; + * mySnakeObj: { + * mySnakeObjString: string; + * } + * } + * ``` + * @remarks + * + * The generated documentation for the camelCase'd properties won't be available + * until {@link https://github.com/microsoft/TypeScript/issues/50715} has been + * resolved. + * + * Tracking: {@link https://github.com/googleapis/google-auth-library-nodejs/issues/1686} + */ +export type OriginalAndCamel = { + [K in keyof T as K | SnakeToCamel]: T[K] extends {} ? OriginalAndCamel : T[K]; +}; +/** + * Returns the camel case of a provided string. + * + * @remarks + * + * Match any `_` and not `_` pair, then return the uppercase of the not `_` + * character. + * + * @param str the string to convert + * @returns the camelCase'd string + */ +export declare function snakeToCamel(str: T): SnakeToCamel; +/** + * 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 + */ +export declare function originalOrCamelOptions(obj?: T): { + get: & string>(key: K) => OriginalAndCamel[K]; +}; +export interface LRUCacheOptions { + /** + * The maximum number of items to cache. + */ + capacity: number; + /** + * An optional max age for items in milliseconds. + */ + maxAge?: number; +} +/** + * A simple LRU cache utility. + * Not meant for external usage. + * + * @experimental + */ +export declare class LRUCache { + #private; + readonly capacity: number; + maxAge?: number; + constructor(options: LRUCacheOptions); + /** + * Add an item to the cache. + * + * @param key the key to upsert + * @param value the value of the key + */ + set(key: string, value: T): void; + /** + * Get an item from the cache. + * + * @param key the key to retrieve + */ + get(key: string): T | undefined; +} +export declare function removeUndefinedValuesInObject(object: { + [key: string]: unknown; +}): { + [key: string]: unknown; +}; +/** + * Helper to check if a path points to a valid file. + */ +export declare function isValidFile(filePath: string): Promise; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/util.js b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/util.js new file mode 100644 index 0000000000000000000000000000000000000000..43228942e0c82fae4962ed38b5043e60bb492a2c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/google-auth-library/build/src/util.js @@ -0,0 +1,176 @@ +"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.LRUCache = void 0; +exports.snakeToCamel = snakeToCamel; +exports.originalOrCamelOptions = originalOrCamelOptions; +exports.removeUndefinedValuesInObject = removeUndefinedValuesInObject; +exports.isValidFile = isValidFile; +exports.getWellKnownCertificateConfigFileLocation = getWellKnownCertificateConfigFileLocation; +const fs = require("fs"); +const os = require("os"); +const path = require("path"); +const WELL_KNOWN_CERTIFICATE_CONFIG_FILE = 'certificate_config.json'; +const CLOUDSDK_CONFIG_DIRECTORY = 'gcloud'; +/** + * Returns the camel case of a provided string. + * + * @remarks + * + * Match any `_` and not `_` pair, then return the uppercase of the not `_` + * character. + * + * @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) { + const o = (obj || {}); + return o[key] ?? o[snakeToCamel(key)]; + } + return { get }; +} +/** + * A simple LRU cache utility. + * Not meant for external usage. + * + * @experimental + */ +class LRUCache { + capacity; + /** + * 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} + */ + #cache = new Map(); + maxAge; + constructor(options) { + this.capacity = options.capacity; + this.maxAge = options.maxAge; + } + /** + * Moves the key to the end of the cache. + * + * @param key the key to move + * @param value the value of the key + */ + #moveToEnd(key, value) { + this.#cache.delete(key); + this.#cache.set(key, { + value, + lastAccessed: Date.now(), + }); + } + /** + * Add an item to the cache. + * + * @param key the key to upsert + * @param value the value of the key + */ + set(key, value) { + this.#moveToEnd(key, value); + this.#evict(); + } + /** + * Get an item from the cache. + * + * @param key the key to retrieve + */ + get(key) { + const item = this.#cache.get(key); + if (!item) + return; + this.#moveToEnd(key, item.value); + this.#evict(); + return item.value; + } + /** + * Maintain the cache based on capacity and TTL. + */ + #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 = this.#cache.entries().next(); + while (!oldestItem.done && + (this.#cache.size > this.capacity || // too many + oldestItem.value[1].lastAccessed < cutoffDate) // too old + ) { + this.#cache.delete(oldestItem.value[0]); + oldestItem = this.#cache.entries().next(); + } + } +} +exports.LRUCache = LRUCache; +// Given and object remove fields where value is undefined. +function removeUndefinedValuesInObject(object) { + Object.entries(object).forEach(([key, value]) => { + if (value === undefined || value === 'undefined') { + delete object[key]; + } + }); + return object; +} +/** + * Helper to check if a path points to a valid file. + */ +async function isValidFile(filePath) { + try { + const stats = await fs.promises.lstat(filePath); + return stats.isFile(); + } + catch (e) { + return false; + } +} +/** + * Determines the well-known gcloud location for the certificate config file. + * @returns The platform-specific path to the configuration file. + * @internal + */ +function getWellKnownCertificateConfigFileLocation() { + const configDir = process.env.CLOUDSDK_CONFIG || + (_isWindows() + ? path.join(process.env.APPDATA || '', CLOUDSDK_CONFIG_DIRECTORY) + : path.join(process.env.HOME || '', '.config', CLOUDSDK_CONFIG_DIRECTORY)); + return path.join(configDir, WELL_KNOWN_CERTIFICATE_CONFIG_FILE); +} +/** + * Checks if the current operating system is Windows. + * @returns True if the OS is Windows, false otherwise. + * @internal + */ +function _isWindows() { + return os.platform().startsWith('win'); +} +//# sourceMappingURL=util.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/bin/cli.js b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/bin/cli.js new file mode 100644 index 0000000000000000000000000000000000000000..a80d9390b802d8f3a1bc1882fc84b6ae039d108f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/bin/cli.js @@ -0,0 +1,179 @@ +#!/usr/bin/env node +import { createReadStream, createWriteStream, readFileSync, renameSync } from 'node:fs' +import { dirname, join } from 'node:path' +import { pipeline as pipelineCallback } from 'node:stream' +import { fileURLToPath } from 'node:url' +import { promisify } from 'node:util' +import { jsonrepairTransform } from '../lib/esm/stream.js' + +const pipeline = promisify(pipelineCallback) +const __filename = fileURLToPath(import.meta.url) +const __dirname = dirname(__filename) + +function processArgs(args) { + const options = { + version: false, + help: false, + overwrite: false, + bufferSize: undefined, + inputFile: null, + outputFile: null + } + + // we skip the first two args, since they contain node and the script path + let i = 2 + while (i < args.length) { + const arg = args[i] + + switch (arg) { + case '-v': + case '--version': + options.version = true + break + + case '-h': + case '--help': + options.help = true + break + + case '--overwrite': + options.overwrite = true + break + + case '--buffer': + i++ + options.bufferSize = parseSize(args[i]) + break + + case '-o': + case '--output': + i++ + options.outputFile = args[i] + break + + default: + if (options.inputFile == null) { + options.inputFile = arg + } else { + throw new Error(`Unexpected argument "${arg}"`) + } + } + + i++ + } + + return options +} + +async function run(options) { + if (options.version) { + outputVersion() + return + } + + if (options.help) { + outputHelp() + return + } + + if (options.overwrite) { + if (!options.inputFile) { + console.error('Error: cannot use --overwrite: no input file provided') + process.exit(1) + } + if (options.outputFile) { + console.error('Error: cannot use --overwrite: there is also an --output provided') + process.exit(1) + } + + const dateStr = new Date().toISOString().replace(/\W/g, '-') + const tempFileSuffix = `.repair-${dateStr}.json` + const tempFile = options.inputFile + tempFileSuffix + + try { + const readStream = createReadStream(options.inputFile) + const writeStream = createWriteStream(tempFile) + await pipeline( + readStream, + jsonrepairTransform({ bufferSize: options.bufferSize }), + writeStream + ) + renameSync(tempFile, options.inputFile) + } catch (err) { + process.stderr.write(err.toString()) + process.exit(1) + } + + return + } + + try { + const readStream = options.inputFile ? createReadStream(options.inputFile) : process.stdin + const writeStream = options.outputFile ? createWriteStream(options.outputFile) : process.stdout + await pipeline(readStream, jsonrepairTransform({ bufferSize: options.bufferSize }), writeStream) + } catch (err) { + process.stderr.write(err.toString()) + process.exit(1) + } +} + +function outputVersion() { + const file = join(__dirname, '../package.json') + const pkg = JSON.parse(String(readFileSync(file, 'utf-8'))) + + console.log(pkg.version) +} + +function parseSize(size) { + // match + const match = size.match(/^(\d+)([KMG]?)$/) + if (!match) { + throw new Error(`Buffer size "${size}" not recognized. Examples: 65536, 512K, 2M`) + } + + const num = Number.parseInt(match[1]) + const suffix = match[2] // K, M, or G + + switch (suffix) { + case 'K': + return num * 1024 + case 'M': + return num * 1024 * 1024 + case 'G': + return num * 1024 * 1024 * 1024 + default: + return num + } +} + +const help = ` +jsonrepair +https://github.com/josdejong/jsonrepair + +Repair invalid JSON documents. When a document could not be repaired, the output will be left unchanged. + +Usage: + jsonrepair [filename] {OPTIONS} + +Options: + --version, -v Show application version + --help, -h Show this message + --output, -o Output file + --overwrite Overwrite the input file + --buffer Buffer size in bytes, for example 64K (default) or 1M + +Example usage: + jsonrepair broken.json # Repair a file, output to console + jsonrepair broken.json > repaired.json # Repair a file, output to file + jsonrepair broken.json --output repaired.json # Repair a file, output to file + jsonrepair broken.json --overwrite # Repair a file, replace the file itself + cat broken.json | jsonrepair # Repair data from an input stream + cat broken.json | jsonrepair > repaired.json # Repair data from an input stream, output to file +` + +function outputHelp() { + console.log(help) +} + +const options = processArgs(process.argv) +await run(options) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/index.js new file mode 100644 index 0000000000000000000000000000000000000000..5adad596c53126d1d0ff90a52033b9219a564c13 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/index.js @@ -0,0 +1,20 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "JSONRepairError", { + enumerable: true, + get: function () { + return _JSONRepairError.JSONRepairError; + } +}); +Object.defineProperty(exports, "jsonrepair", { + enumerable: true, + get: function () { + return _jsonrepair.jsonrepair; + } +}); +var _jsonrepair = require("./regular/jsonrepair.js"); +var _JSONRepairError = require("./utils/JSONRepairError.js"); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/index.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..6e0c022eec3a90217cdc28dd104709c23892b85d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["_jsonrepair","require","_JSONRepairError"],"sources":["../../src/index.ts"],"sourcesContent":["// Cross-platform, non-streaming JavaScript API\nexport { jsonrepair } from './regular/jsonrepair.js'\nexport { JSONRepairError } from './utils/JSONRepairError.js'\n"],"mappings":";;;;;;;;;;;;;;;;;AACA,IAAAA,WAAA,GAAAC,OAAA;AACA,IAAAC,gBAAA,GAAAD,OAAA","ignoreList":[]} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/package.json b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/package.json new file mode 100644 index 0000000000000000000000000000000000000000..5bbefffbabee392d1855491b84dc0a716b6a3bf2 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/regular/jsonrepair.js b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/regular/jsonrepair.js new file mode 100644 index 0000000000000000000000000000000000000000..d37ed12be69d1bfdee26077250388e7e7d090f80 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/regular/jsonrepair.js @@ -0,0 +1,745 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.jsonrepair = jsonrepair; +var _JSONRepairError = require("../utils/JSONRepairError.js"); +var _stringUtils = require("../utils/stringUtils.js"); +const controlCharacters = { + '\b': '\\b', + '\f': '\\f', + '\n': '\\n', + '\r': '\\r', + '\t': '\\t' +}; + +// map with all escape characters +const escapeCharacters = { + '"': '"', + '\\': '\\', + '/': '/', + b: '\b', + f: '\f', + n: '\n', + r: '\r', + t: '\t' + // note that \u is handled separately in parseString() +}; + +/** + * Repair a string containing an invalid JSON document. + * For example changes JavaScript notation into JSON notation. + * + * Example: + * + * try { + * const json = "{name: 'John'}" + * const repaired = jsonrepair(json) + * console.log(repaired) + * // '{"name": "John"}' + * } catch (err) { + * console.error(err) + * } + * + */ +function jsonrepair(text) { + let i = 0; // current index in text + let output = ''; // generated output + + parseMarkdownCodeBlock(['```', '[```', '{```']); + const processed = parseValue(); + if (!processed) { + throwUnexpectedEnd(); + } + parseMarkdownCodeBlock(['```', '```]', '```}']); + const processedComma = parseCharacter(','); + if (processedComma) { + parseWhitespaceAndSkipComments(); + } + if ((0, _stringUtils.isStartOfValue)(text[i]) && (0, _stringUtils.endsWithCommaOrNewline)(output)) { + // start of a new value after end of the root level object: looks like + // newline delimited JSON -> turn into a root level array + if (!processedComma) { + // repair missing comma + output = (0, _stringUtils.insertBeforeLastWhitespace)(output, ','); + } + parseNewlineDelimitedJSON(); + } else if (processedComma) { + // repair: remove trailing comma + output = (0, _stringUtils.stripLastOccurrence)(output, ','); + } + + // repair redundant end quotes + while (text[i] === '}' || text[i] === ']') { + i++; + parseWhitespaceAndSkipComments(); + } + if (i >= text.length) { + // reached the end of the document properly + return output; + } + throwUnexpectedCharacter(); + function parseValue() { + parseWhitespaceAndSkipComments(); + const processed = parseObject() || parseArray() || parseString() || parseNumber() || parseKeywords() || parseUnquotedString(false) || parseRegex(); + parseWhitespaceAndSkipComments(); + return processed; + } + function parseWhitespaceAndSkipComments() { + let skipNewline = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; + const start = i; + let changed = parseWhitespace(skipNewline); + do { + changed = parseComment(); + if (changed) { + changed = parseWhitespace(skipNewline); + } + } while (changed); + return i > start; + } + function parseWhitespace(skipNewline) { + const _isWhiteSpace = skipNewline ? _stringUtils.isWhitespace : _stringUtils.isWhitespaceExceptNewline; + let whitespace = ''; + while (true) { + if (_isWhiteSpace(text, i)) { + whitespace += text[i]; + i++; + } else if ((0, _stringUtils.isSpecialWhitespace)(text, i)) { + // repair special whitespace + whitespace += ' '; + i++; + } else { + break; + } + } + if (whitespace.length > 0) { + output += whitespace; + return true; + } + return false; + } + function parseComment() { + // find a block comment '/* ... */' + if (text[i] === '/' && text[i + 1] === '*') { + // repair block comment by skipping it + while (i < text.length && !atEndOfBlockComment(text, i)) { + i++; + } + i += 2; + return true; + } + + // find a line comment '// ...' + if (text[i] === '/' && text[i + 1] === '/') { + // repair line comment by skipping it + while (i < text.length && text[i] !== '\n') { + i++; + } + return true; + } + return false; + } + function parseMarkdownCodeBlock(blocks) { + // find and skip over a Markdown fenced code block: + // ``` ... ``` + // or + // ```json ... ``` + if (skipMarkdownCodeBlock(blocks)) { + if ((0, _stringUtils.isFunctionNameCharStart)(text[i])) { + // strip the optional language specifier like "json" + while (i < text.length && (0, _stringUtils.isFunctionNameChar)(text[i])) { + i++; + } + } + parseWhitespaceAndSkipComments(); + return true; + } + return false; + } + function skipMarkdownCodeBlock(blocks) { + for (const block of blocks) { + const end = i + block.length; + if (text.slice(i, end) === block) { + i = end; + return true; + } + } + return false; + } + function parseCharacter(char) { + if (text[i] === char) { + output += text[i]; + i++; + return true; + } + return false; + } + function skipCharacter(char) { + if (text[i] === char) { + i++; + return true; + } + return false; + } + function skipEscapeCharacter() { + return skipCharacter('\\'); + } + + /** + * Skip ellipsis like "[1,2,3,...]" or "[1,2,3,...,9]" or "[...,7,8,9]" + * or a similar construct in objects. + */ + function skipEllipsis() { + parseWhitespaceAndSkipComments(); + if (text[i] === '.' && text[i + 1] === '.' && text[i + 2] === '.') { + // repair: remove the ellipsis (three dots) and optionally a comma + i += 3; + parseWhitespaceAndSkipComments(); + skipCharacter(','); + return true; + } + return false; + } + + /** + * Parse an object like '{"key": "value"}' + */ + function parseObject() { + if (text[i] === '{') { + output += '{'; + i++; + parseWhitespaceAndSkipComments(); + + // repair: skip leading comma like in {, message: "hi"} + if (skipCharacter(',')) { + parseWhitespaceAndSkipComments(); + } + let initial = true; + while (i < text.length && text[i] !== '}') { + let processedComma; + if (!initial) { + processedComma = parseCharacter(','); + if (!processedComma) { + // repair missing comma + output = (0, _stringUtils.insertBeforeLastWhitespace)(output, ','); + } + parseWhitespaceAndSkipComments(); + } else { + processedComma = true; + initial = false; + } + skipEllipsis(); + const processedKey = parseString() || parseUnquotedString(true); + if (!processedKey) { + if (text[i] === '}' || text[i] === '{' || text[i] === ']' || text[i] === '[' || text[i] === undefined) { + // repair trailing comma + output = (0, _stringUtils.stripLastOccurrence)(output, ','); + } else { + throwObjectKeyExpected(); + } + break; + } + parseWhitespaceAndSkipComments(); + const processedColon = parseCharacter(':'); + const truncatedText = i >= text.length; + if (!processedColon) { + if ((0, _stringUtils.isStartOfValue)(text[i]) || truncatedText) { + // repair missing colon + output = (0, _stringUtils.insertBeforeLastWhitespace)(output, ':'); + } else { + throwColonExpected(); + } + } + const processedValue = parseValue(); + if (!processedValue) { + if (processedColon || truncatedText) { + // repair missing object value + output += 'null'; + } else { + throwColonExpected(); + } + } + } + if (text[i] === '}') { + output += '}'; + i++; + } else { + // repair missing end bracket + output = (0, _stringUtils.insertBeforeLastWhitespace)(output, '}'); + } + return true; + } + return false; + } + + /** + * Parse an array like '["item1", "item2", ...]' + */ + function parseArray() { + if (text[i] === '[') { + output += '['; + i++; + parseWhitespaceAndSkipComments(); + + // repair: skip leading comma like in [,1,2,3] + if (skipCharacter(',')) { + parseWhitespaceAndSkipComments(); + } + let initial = true; + while (i < text.length && text[i] !== ']') { + if (!initial) { + const processedComma = parseCharacter(','); + if (!processedComma) { + // repair missing comma + output = (0, _stringUtils.insertBeforeLastWhitespace)(output, ','); + } + } else { + initial = false; + } + skipEllipsis(); + const processedValue = parseValue(); + if (!processedValue) { + // repair trailing comma + output = (0, _stringUtils.stripLastOccurrence)(output, ','); + break; + } + } + if (text[i] === ']') { + output += ']'; + i++; + } else { + // repair missing closing array bracket + output = (0, _stringUtils.insertBeforeLastWhitespace)(output, ']'); + } + return true; + } + return false; + } + + /** + * Parse and repair Newline Delimited JSON (NDJSON): + * multiple JSON objects separated by a newline character + */ + function parseNewlineDelimitedJSON() { + // repair NDJSON + let initial = true; + let processedValue = true; + while (processedValue) { + if (!initial) { + // parse optional comma, insert when missing + const processedComma = parseCharacter(','); + if (!processedComma) { + // repair: add missing comma + output = (0, _stringUtils.insertBeforeLastWhitespace)(output, ','); + } + } else { + initial = false; + } + processedValue = parseValue(); + } + if (!processedValue) { + // repair: remove trailing comma + output = (0, _stringUtils.stripLastOccurrence)(output, ','); + } + + // repair: wrap the output inside array brackets + output = `[\n${output}\n]`; + } + + /** + * Parse a string enclosed by double quotes "...". Can contain escaped quotes + * Repair strings enclosed in single quotes or special quotes + * Repair an escaped string + * + * The function can run in two stages: + * - First, it assumes the string has a valid end quote + * - If it turns out that the string does not have a valid end quote followed + * by a delimiter (which should be the case), the function runs again in a + * more conservative way, stopping the string at the first next delimiter + * and fixing the string by inserting a quote there, or stopping at a + * stop index detected in the first iteration. + */ + function parseString() { + let stopAtDelimiter = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + let stopAtIndex = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : -1; + let skipEscapeChars = text[i] === '\\'; + if (skipEscapeChars) { + // repair: remove the first escape character + i++; + skipEscapeChars = true; + } + if ((0, _stringUtils.isQuote)(text[i])) { + // double quotes are correct JSON, + // single quotes come from JavaScript for example, we assume it will have a correct single end quote too + // otherwise, we will match any double-quote-like start with a double-quote-like end, + // or any single-quote-like start with a single-quote-like end + const isEndQuote = (0, _stringUtils.isDoubleQuote)(text[i]) ? _stringUtils.isDoubleQuote : (0, _stringUtils.isSingleQuote)(text[i]) ? _stringUtils.isSingleQuote : (0, _stringUtils.isSingleQuoteLike)(text[i]) ? _stringUtils.isSingleQuoteLike : _stringUtils.isDoubleQuoteLike; + const iBefore = i; + const oBefore = output.length; + let str = '"'; + i++; + while (true) { + if (i >= text.length) { + // end of text, we are missing an end quote + + const iPrev = prevNonWhitespaceIndex(i - 1); + if (!stopAtDelimiter && (0, _stringUtils.isDelimiter)(text.charAt(iPrev))) { + // if the text ends with a delimiter, like ["hello], + // so the missing end quote should be inserted before this delimiter + // retry parsing the string, stopping at the first next delimiter + i = iBefore; + output = output.substring(0, oBefore); + return parseString(true); + } + + // repair missing quote + str = (0, _stringUtils.insertBeforeLastWhitespace)(str, '"'); + output += str; + return true; + } + if (i === stopAtIndex) { + // use the stop index detected in the first iteration, and repair end quote + str = (0, _stringUtils.insertBeforeLastWhitespace)(str, '"'); + output += str; + return true; + } + if (isEndQuote(text[i])) { + // end quote + // let us check what is before and after the quote to verify whether this is a legit end quote + const iQuote = i; + const oQuote = str.length; + str += '"'; + i++; + output += str; + parseWhitespaceAndSkipComments(false); + if (stopAtDelimiter || i >= text.length || (0, _stringUtils.isDelimiter)(text[i]) || (0, _stringUtils.isQuote)(text[i]) || (0, _stringUtils.isDigit)(text[i])) { + // The quote is followed by the end of the text, a delimiter, + // or a next value. So the quote is indeed the end of the string. + parseConcatenatedString(); + return true; + } + const iPrevChar = prevNonWhitespaceIndex(iQuote - 1); + const prevChar = text.charAt(iPrevChar); + if (prevChar === ',') { + // A comma followed by a quote, like '{"a":"b,c,"d":"e"}'. + // We assume that the quote is a start quote, and that the end quote + // should have been located right before the comma but is missing. + i = iBefore; + output = output.substring(0, oBefore); + return parseString(false, iPrevChar); + } + if ((0, _stringUtils.isDelimiter)(prevChar)) { + // This is not the right end quote: it is preceded by a delimiter, + // and NOT followed by a delimiter. So, there is an end quote missing + // parse the string again and then stop at the first next delimiter + i = iBefore; + output = output.substring(0, oBefore); + return parseString(true); + } + + // revert to right after the quote but before any whitespace, and continue parsing the string + output = output.substring(0, oBefore); + i = iQuote + 1; + + // repair unescaped quote + str = `${str.substring(0, oQuote)}\\${str.substring(oQuote)}`; + } else if (stopAtDelimiter && (0, _stringUtils.isUnquotedStringDelimiter)(text[i])) { + // we're in the mode to stop the string at the first delimiter + // because there is an end quote missing + + // test start of an url like "https://..." (this would be parsed as a comment) + if (text[i - 1] === ':' && _stringUtils.regexUrlStart.test(text.substring(iBefore + 1, i + 2))) { + while (i < text.length && _stringUtils.regexUrlChar.test(text[i])) { + str += text[i]; + i++; + } + } + + // repair missing quote + str = (0, _stringUtils.insertBeforeLastWhitespace)(str, '"'); + output += str; + parseConcatenatedString(); + return true; + } else if (text[i] === '\\') { + // handle escaped content like \n or \u2605 + const char = text.charAt(i + 1); + const escapeChar = escapeCharacters[char]; + if (escapeChar !== undefined) { + str += text.slice(i, i + 2); + i += 2; + } else if (char === 'u') { + let j = 2; + while (j < 6 && (0, _stringUtils.isHex)(text[i + j])) { + j++; + } + if (j === 6) { + str += text.slice(i, i + 6); + i += 6; + } else if (i + j >= text.length) { + // repair invalid or truncated unicode char at the end of the text + // by removing the unicode char and ending the string here + i = text.length; + } else { + throwInvalidUnicodeCharacter(); + } + } else { + // repair invalid escape character: remove it + str += char; + i += 2; + } + } else { + // handle regular characters + const char = text.charAt(i); + if (char === '"' && text[i - 1] !== '\\') { + // repair unescaped double quote + str += `\\${char}`; + i++; + } else if ((0, _stringUtils.isControlCharacter)(char)) { + // unescaped control character + str += controlCharacters[char]; + i++; + } else { + if (!(0, _stringUtils.isValidStringCharacter)(char)) { + throwInvalidCharacter(char); + } + str += char; + i++; + } + } + if (skipEscapeChars) { + // repair: skipped escape character (nothing to do) + skipEscapeCharacter(); + } + } + } + return false; + } + + /** + * Repair concatenated strings like "hello" + "world", change this into "helloworld" + */ + function parseConcatenatedString() { + let processed = false; + parseWhitespaceAndSkipComments(); + while (text[i] === '+') { + processed = true; + i++; + parseWhitespaceAndSkipComments(); + + // repair: remove the end quote of the first string + output = (0, _stringUtils.stripLastOccurrence)(output, '"', true); + const start = output.length; + const parsedStr = parseString(); + if (parsedStr) { + // repair: remove the start quote of the second string + output = (0, _stringUtils.removeAtIndex)(output, start, 1); + } else { + // repair: remove the + because it is not followed by a string + output = (0, _stringUtils.insertBeforeLastWhitespace)(output, '"'); + } + } + return processed; + } + + /** + * Parse a number like 2.4 or 2.4e6 + */ + function parseNumber() { + const start = i; + if (text[i] === '-') { + i++; + if (atEndOfNumber()) { + repairNumberEndingWithNumericSymbol(start); + return true; + } + if (!(0, _stringUtils.isDigit)(text[i])) { + i = start; + return false; + } + } + + // Note that in JSON leading zeros like "00789" are not allowed. + // We will allow all leading zeros here though and at the end of parseNumber + // check against trailing zeros and repair that if needed. + // Leading zeros can have meaning, so we should not clear them. + while ((0, _stringUtils.isDigit)(text[i])) { + i++; + } + if (text[i] === '.') { + i++; + if (atEndOfNumber()) { + repairNumberEndingWithNumericSymbol(start); + return true; + } + if (!(0, _stringUtils.isDigit)(text[i])) { + i = start; + return false; + } + while ((0, _stringUtils.isDigit)(text[i])) { + i++; + } + } + if (text[i] === 'e' || text[i] === 'E') { + i++; + if (text[i] === '-' || text[i] === '+') { + i++; + } + if (atEndOfNumber()) { + repairNumberEndingWithNumericSymbol(start); + return true; + } + if (!(0, _stringUtils.isDigit)(text[i])) { + i = start; + return false; + } + while ((0, _stringUtils.isDigit)(text[i])) { + i++; + } + } + + // if we're not at the end of the number by this point, allow this to be parsed as another type + if (!atEndOfNumber()) { + i = start; + return false; + } + if (i > start) { + // repair a number with leading zeros like "00789" + const num = text.slice(start, i); + const hasInvalidLeadingZero = /^0\d/.test(num); + output += hasInvalidLeadingZero ? `"${num}"` : num; + return true; + } + return false; + } + + /** + * Parse keywords true, false, null + * Repair Python keywords True, False, None + */ + function parseKeywords() { + return parseKeyword('true', 'true') || parseKeyword('false', 'false') || parseKeyword('null', 'null') || + // repair Python keywords True, False, None + parseKeyword('True', 'true') || parseKeyword('False', 'false') || parseKeyword('None', 'null'); + } + function parseKeyword(name, value) { + if (text.slice(i, i + name.length) === name) { + output += value; + i += name.length; + return true; + } + return false; + } + + /** + * Repair an unquoted string by adding quotes around it + * Repair a MongoDB function call like NumberLong("2") + * Repair a JSONP function call like callback({...}); + */ + function parseUnquotedString(isKey) { + // note that the symbol can end with whitespaces: we stop at the next delimiter + // also, note that we allow strings to contain a slash / in order to support repairing regular expressions + const start = i; + if ((0, _stringUtils.isFunctionNameCharStart)(text[i])) { + while (i < text.length && (0, _stringUtils.isFunctionNameChar)(text[i])) { + i++; + } + let j = i; + while ((0, _stringUtils.isWhitespace)(text, j)) { + j++; + } + if (text[j] === '(') { + // repair a MongoDB function call like NumberLong("2") + // repair a JSONP function call like callback({...}); + i = j + 1; + parseValue(); + if (text[i] === ')') { + // repair: skip close bracket of function call + i++; + if (text[i] === ';') { + // repair: skip semicolon after JSONP call + i++; + } + } + return true; + } + } + while (i < text.length && !(0, _stringUtils.isUnquotedStringDelimiter)(text[i]) && !(0, _stringUtils.isQuote)(text[i]) && (!isKey || text[i] !== ':')) { + i++; + } + + // test start of an url like "https://..." (this would be parsed as a comment) + if (text[i - 1] === ':' && _stringUtils.regexUrlStart.test(text.substring(start, i + 2))) { + while (i < text.length && _stringUtils.regexUrlChar.test(text[i])) { + i++; + } + } + if (i > start) { + // repair unquoted string + // also, repair undefined into null + + // first, go back to prevent getting trailing whitespaces in the string + while ((0, _stringUtils.isWhitespace)(text, i - 1) && i > 0) { + i--; + } + const symbol = text.slice(start, i); + output += symbol === 'undefined' ? 'null' : JSON.stringify(symbol); + if (text[i] === '"') { + // we had a missing start quote, but now we encountered the end quote, so we can skip that one + i++; + } + return true; + } + } + function parseRegex() { + if (text[i] === '/') { + const start = i; + i++; + while (i < text.length && (text[i] !== '/' || text[i - 1] === '\\')) { + i++; + } + i++; + output += `"${text.substring(start, i)}"`; + return true; + } + } + function prevNonWhitespaceIndex(start) { + let prev = start; + while (prev > 0 && (0, _stringUtils.isWhitespace)(text, prev)) { + prev--; + } + return prev; + } + function atEndOfNumber() { + return i >= text.length || (0, _stringUtils.isDelimiter)(text[i]) || (0, _stringUtils.isWhitespace)(text, i); + } + function repairNumberEndingWithNumericSymbol(start) { + // repair numbers cut off at the end + // this will only be called when we end after a '.', '-', or 'e' and does not + // change the number more than it needs to make it valid JSON + output += `${text.slice(start, i)}0`; + } + function throwInvalidCharacter(char) { + throw new _JSONRepairError.JSONRepairError(`Invalid character ${JSON.stringify(char)}`, i); + } + function throwUnexpectedCharacter() { + throw new _JSONRepairError.JSONRepairError(`Unexpected character ${JSON.stringify(text[i])}`, i); + } + function throwUnexpectedEnd() { + throw new _JSONRepairError.JSONRepairError('Unexpected end of json string', text.length); + } + function throwObjectKeyExpected() { + throw new _JSONRepairError.JSONRepairError('Object key expected', i); + } + function throwColonExpected() { + throw new _JSONRepairError.JSONRepairError('Colon expected', i); + } + function throwInvalidUnicodeCharacter() { + const chars = text.slice(i, i + 6); + throw new _JSONRepairError.JSONRepairError(`Invalid unicode character "${chars}"`, i); + } +} +function atEndOfBlockComment(text, i) { + return text[i] === '*' && text[i + 1] === '/'; +} +//# sourceMappingURL=jsonrepair.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/regular/jsonrepair.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/regular/jsonrepair.js.map new file mode 100644 index 0000000000000000000000000000000000000000..0a5ece808e290ad70e662ce8c20f64cc204885b8 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/regular/jsonrepair.js.map @@ -0,0 +1 @@ +{"version":3,"file":"jsonrepair.js","names":["_JSONRepairError","require","_stringUtils","controlCharacters","escapeCharacters","b","f","n","r","t","jsonrepair","text","i","output","parseMarkdownCodeBlock","processed","parseValue","throwUnexpectedEnd","processedComma","parseCharacter","parseWhitespaceAndSkipComments","isStartOfValue","endsWithCommaOrNewline","insertBeforeLastWhitespace","parseNewlineDelimitedJSON","stripLastOccurrence","length","throwUnexpectedCharacter","parseObject","parseArray","parseString","parseNumber","parseKeywords","parseUnquotedString","parseRegex","skipNewline","arguments","undefined","start","changed","parseWhitespace","parseComment","_isWhiteSpace","isWhitespace","isWhitespaceExceptNewline","whitespace","isSpecialWhitespace","atEndOfBlockComment","blocks","skipMarkdownCodeBlock","isFunctionNameCharStart","isFunctionNameChar","block","end","slice","char","skipCharacter","skipEscapeCharacter","skipEllipsis","initial","processedKey","throwObjectKeyExpected","processedColon","truncatedText","throwColonExpected","processedValue","stopAtDelimiter","stopAtIndex","skipEscapeChars","isQuote","isEndQuote","isDoubleQuote","isSingleQuote","isSingleQuoteLike","isDoubleQuoteLike","iBefore","oBefore","str","iPrev","prevNonWhitespaceIndex","isDelimiter","charAt","substring","iQuote","oQuote","isDigit","parseConcatenatedString","iPrevChar","prevChar","isUnquotedStringDelimiter","regexUrlStart","test","regexUrlChar","escapeChar","j","isHex","throwInvalidUnicodeCharacter","isControlCharacter","isValidStringCharacter","throwInvalidCharacter","parsedStr","removeAtIndex","atEndOfNumber","repairNumberEndingWithNumericSymbol","num","hasInvalidLeadingZero","parseKeyword","name","value","isKey","symbol","JSON","stringify","prev","JSONRepairError","chars"],"sources":["../../../src/regular/jsonrepair.ts"],"sourcesContent":["import { JSONRepairError } from '../utils/JSONRepairError.js'\nimport {\n endsWithCommaOrNewline,\n insertBeforeLastWhitespace,\n isControlCharacter,\n isDelimiter,\n isDigit,\n isDoubleQuote,\n isDoubleQuoteLike,\n isFunctionNameChar,\n isFunctionNameCharStart,\n isHex,\n isQuote,\n isSingleQuote,\n isSingleQuoteLike,\n isSpecialWhitespace,\n isStartOfValue,\n isUnquotedStringDelimiter,\n isValidStringCharacter,\n isWhitespace,\n isWhitespaceExceptNewline,\n regexUrlChar,\n regexUrlStart,\n removeAtIndex,\n stripLastOccurrence\n} from '../utils/stringUtils.js'\n\nconst controlCharacters: { [key: string]: string } = {\n '\\b': '\\\\b',\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t'\n}\n\n// map with all escape characters\nconst escapeCharacters: { [key: string]: string } = {\n '\"': '\"',\n '\\\\': '\\\\',\n '/': '/',\n b: '\\b',\n f: '\\f',\n n: '\\n',\n r: '\\r',\n t: '\\t'\n // note that \\u is handled separately in parseString()\n}\n\n/**\n * Repair a string containing an invalid JSON document.\n * For example changes JavaScript notation into JSON notation.\n *\n * Example:\n *\n * try {\n * const json = \"{name: 'John'}\"\n * const repaired = jsonrepair(json)\n * console.log(repaired)\n * // '{\"name\": \"John\"}'\n * } catch (err) {\n * console.error(err)\n * }\n *\n */\nexport function jsonrepair(text: string): string {\n let i = 0 // current index in text\n let output = '' // generated output\n\n parseMarkdownCodeBlock(['```', '[```', '{```'])\n\n const processed = parseValue()\n if (!processed) {\n throwUnexpectedEnd()\n }\n\n parseMarkdownCodeBlock(['```', '```]', '```}'])\n\n const processedComma = parseCharacter(',')\n if (processedComma) {\n parseWhitespaceAndSkipComments()\n }\n\n if (isStartOfValue(text[i]) && endsWithCommaOrNewline(output)) {\n // start of a new value after end of the root level object: looks like\n // newline delimited JSON -> turn into a root level array\n if (!processedComma) {\n // repair missing comma\n output = insertBeforeLastWhitespace(output, ',')\n }\n\n parseNewlineDelimitedJSON()\n } else if (processedComma) {\n // repair: remove trailing comma\n output = stripLastOccurrence(output, ',')\n }\n\n // repair redundant end quotes\n while (text[i] === '}' || text[i] === ']') {\n i++\n parseWhitespaceAndSkipComments()\n }\n\n if (i >= text.length) {\n // reached the end of the document properly\n return output\n }\n\n throwUnexpectedCharacter()\n\n function parseValue(): boolean {\n parseWhitespaceAndSkipComments()\n const processed =\n parseObject() ||\n parseArray() ||\n parseString() ||\n parseNumber() ||\n parseKeywords() ||\n parseUnquotedString(false) ||\n parseRegex()\n parseWhitespaceAndSkipComments()\n\n return processed\n }\n\n function parseWhitespaceAndSkipComments(skipNewline = true): boolean {\n const start = i\n\n let changed = parseWhitespace(skipNewline)\n do {\n changed = parseComment()\n if (changed) {\n changed = parseWhitespace(skipNewline)\n }\n } while (changed)\n\n return i > start\n }\n\n function parseWhitespace(skipNewline: boolean): boolean {\n const _isWhiteSpace = skipNewline ? isWhitespace : isWhitespaceExceptNewline\n let whitespace = ''\n\n while (true) {\n if (_isWhiteSpace(text, i)) {\n whitespace += text[i]\n i++\n } else if (isSpecialWhitespace(text, i)) {\n // repair special whitespace\n whitespace += ' '\n i++\n } else {\n break\n }\n }\n\n if (whitespace.length > 0) {\n output += whitespace\n return true\n }\n\n return false\n }\n\n function parseComment(): boolean {\n // find a block comment '/* ... */'\n if (text[i] === '/' && text[i + 1] === '*') {\n // repair block comment by skipping it\n while (i < text.length && !atEndOfBlockComment(text, i)) {\n i++\n }\n i += 2\n\n return true\n }\n\n // find a line comment '// ...'\n if (text[i] === '/' && text[i + 1] === '/') {\n // repair line comment by skipping it\n while (i < text.length && text[i] !== '\\n') {\n i++\n }\n\n return true\n }\n\n return false\n }\n\n function parseMarkdownCodeBlock(blocks: string[]): boolean {\n // find and skip over a Markdown fenced code block:\n // ``` ... ```\n // or\n // ```json ... ```\n if (skipMarkdownCodeBlock(blocks)) {\n if (isFunctionNameCharStart(text[i])) {\n // strip the optional language specifier like \"json\"\n while (i < text.length && isFunctionNameChar(text[i])) {\n i++\n }\n }\n\n parseWhitespaceAndSkipComments()\n\n return true\n }\n\n return false\n }\n\n function skipMarkdownCodeBlock(blocks: string[]): boolean {\n for (const block of blocks) {\n const end = i + block.length\n if (text.slice(i, end) === block) {\n i = end\n return true\n }\n }\n\n return false\n }\n\n function parseCharacter(char: string): boolean {\n if (text[i] === char) {\n output += text[i]\n i++\n return true\n }\n\n return false\n }\n\n function skipCharacter(char: string): boolean {\n if (text[i] === char) {\n i++\n return true\n }\n\n return false\n }\n\n function skipEscapeCharacter(): boolean {\n return skipCharacter('\\\\')\n }\n\n /**\n * Skip ellipsis like \"[1,2,3,...]\" or \"[1,2,3,...,9]\" or \"[...,7,8,9]\"\n * or a similar construct in objects.\n */\n function skipEllipsis(): boolean {\n parseWhitespaceAndSkipComments()\n\n if (text[i] === '.' && text[i + 1] === '.' && text[i + 2] === '.') {\n // repair: remove the ellipsis (three dots) and optionally a comma\n i += 3\n parseWhitespaceAndSkipComments()\n skipCharacter(',')\n\n return true\n }\n\n return false\n }\n\n /**\n * Parse an object like '{\"key\": \"value\"}'\n */\n function parseObject(): boolean {\n if (text[i] === '{') {\n output += '{'\n i++\n parseWhitespaceAndSkipComments()\n\n // repair: skip leading comma like in {, message: \"hi\"}\n if (skipCharacter(',')) {\n parseWhitespaceAndSkipComments()\n }\n\n let initial = true\n while (i < text.length && text[i] !== '}') {\n let processedComma: boolean\n if (!initial) {\n processedComma = parseCharacter(',')\n if (!processedComma) {\n // repair missing comma\n output = insertBeforeLastWhitespace(output, ',')\n }\n parseWhitespaceAndSkipComments()\n } else {\n processedComma = true\n initial = false\n }\n\n skipEllipsis()\n\n const processedKey = parseString() || parseUnquotedString(true)\n if (!processedKey) {\n if (\n text[i] === '}' ||\n text[i] === '{' ||\n text[i] === ']' ||\n text[i] === '[' ||\n text[i] === undefined\n ) {\n // repair trailing comma\n output = stripLastOccurrence(output, ',')\n } else {\n throwObjectKeyExpected()\n }\n break\n }\n\n parseWhitespaceAndSkipComments()\n const processedColon = parseCharacter(':')\n const truncatedText = i >= text.length\n if (!processedColon) {\n if (isStartOfValue(text[i]) || truncatedText) {\n // repair missing colon\n output = insertBeforeLastWhitespace(output, ':')\n } else {\n throwColonExpected()\n }\n }\n const processedValue = parseValue()\n if (!processedValue) {\n if (processedColon || truncatedText) {\n // repair missing object value\n output += 'null'\n } else {\n throwColonExpected()\n }\n }\n }\n\n if (text[i] === '}') {\n output += '}'\n i++\n } else {\n // repair missing end bracket\n output = insertBeforeLastWhitespace(output, '}')\n }\n\n return true\n }\n\n return false\n }\n\n /**\n * Parse an array like '[\"item1\", \"item2\", ...]'\n */\n function parseArray(): boolean {\n if (text[i] === '[') {\n output += '['\n i++\n parseWhitespaceAndSkipComments()\n\n // repair: skip leading comma like in [,1,2,3]\n if (skipCharacter(',')) {\n parseWhitespaceAndSkipComments()\n }\n\n let initial = true\n while (i < text.length && text[i] !== ']') {\n if (!initial) {\n const processedComma = parseCharacter(',')\n if (!processedComma) {\n // repair missing comma\n output = insertBeforeLastWhitespace(output, ',')\n }\n } else {\n initial = false\n }\n\n skipEllipsis()\n\n const processedValue = parseValue()\n if (!processedValue) {\n // repair trailing comma\n output = stripLastOccurrence(output, ',')\n break\n }\n }\n\n if (text[i] === ']') {\n output += ']'\n i++\n } else {\n // repair missing closing array bracket\n output = insertBeforeLastWhitespace(output, ']')\n }\n\n return true\n }\n\n return false\n }\n\n /**\n * Parse and repair Newline Delimited JSON (NDJSON):\n * multiple JSON objects separated by a newline character\n */\n function parseNewlineDelimitedJSON() {\n // repair NDJSON\n let initial = true\n let processedValue = true\n while (processedValue) {\n if (!initial) {\n // parse optional comma, insert when missing\n const processedComma = parseCharacter(',')\n if (!processedComma) {\n // repair: add missing comma\n output = insertBeforeLastWhitespace(output, ',')\n }\n } else {\n initial = false\n }\n\n processedValue = parseValue()\n }\n\n if (!processedValue) {\n // repair: remove trailing comma\n output = stripLastOccurrence(output, ',')\n }\n\n // repair: wrap the output inside array brackets\n output = `[\\n${output}\\n]`\n }\n\n /**\n * Parse a string enclosed by double quotes \"...\". Can contain escaped quotes\n * Repair strings enclosed in single quotes or special quotes\n * Repair an escaped string\n *\n * The function can run in two stages:\n * - First, it assumes the string has a valid end quote\n * - If it turns out that the string does not have a valid end quote followed\n * by a delimiter (which should be the case), the function runs again in a\n * more conservative way, stopping the string at the first next delimiter\n * and fixing the string by inserting a quote there, or stopping at a\n * stop index detected in the first iteration.\n */\n function parseString(stopAtDelimiter = false, stopAtIndex = -1): boolean {\n let skipEscapeChars = text[i] === '\\\\'\n if (skipEscapeChars) {\n // repair: remove the first escape character\n i++\n skipEscapeChars = true\n }\n\n if (isQuote(text[i])) {\n // double quotes are correct JSON,\n // single quotes come from JavaScript for example, we assume it will have a correct single end quote too\n // otherwise, we will match any double-quote-like start with a double-quote-like end,\n // or any single-quote-like start with a single-quote-like end\n const isEndQuote = isDoubleQuote(text[i])\n ? isDoubleQuote\n : isSingleQuote(text[i])\n ? isSingleQuote\n : isSingleQuoteLike(text[i])\n ? isSingleQuoteLike\n : isDoubleQuoteLike\n\n const iBefore = i\n const oBefore = output.length\n\n let str = '\"'\n i++\n\n while (true) {\n if (i >= text.length) {\n // end of text, we are missing an end quote\n\n const iPrev = prevNonWhitespaceIndex(i - 1)\n if (!stopAtDelimiter && isDelimiter(text.charAt(iPrev))) {\n // if the text ends with a delimiter, like [\"hello],\n // so the missing end quote should be inserted before this delimiter\n // retry parsing the string, stopping at the first next delimiter\n i = iBefore\n output = output.substring(0, oBefore)\n\n return parseString(true)\n }\n\n // repair missing quote\n str = insertBeforeLastWhitespace(str, '\"')\n output += str\n\n return true\n }\n\n if (i === stopAtIndex) {\n // use the stop index detected in the first iteration, and repair end quote\n str = insertBeforeLastWhitespace(str, '\"')\n output += str\n\n return true\n }\n\n if (isEndQuote(text[i])) {\n // end quote\n // let us check what is before and after the quote to verify whether this is a legit end quote\n const iQuote = i\n const oQuote = str.length\n str += '\"'\n i++\n output += str\n\n parseWhitespaceAndSkipComments(false)\n\n if (\n stopAtDelimiter ||\n i >= text.length ||\n isDelimiter(text[i]) ||\n isQuote(text[i]) ||\n isDigit(text[i])\n ) {\n // The quote is followed by the end of the text, a delimiter,\n // or a next value. So the quote is indeed the end of the string.\n parseConcatenatedString()\n\n return true\n }\n\n const iPrevChar = prevNonWhitespaceIndex(iQuote - 1)\n const prevChar = text.charAt(iPrevChar)\n\n if (prevChar === ',') {\n // A comma followed by a quote, like '{\"a\":\"b,c,\"d\":\"e\"}'.\n // We assume that the quote is a start quote, and that the end quote\n // should have been located right before the comma but is missing.\n i = iBefore\n output = output.substring(0, oBefore)\n\n return parseString(false, iPrevChar)\n }\n\n if (isDelimiter(prevChar)) {\n // This is not the right end quote: it is preceded by a delimiter,\n // and NOT followed by a delimiter. So, there is an end quote missing\n // parse the string again and then stop at the first next delimiter\n i = iBefore\n output = output.substring(0, oBefore)\n\n return parseString(true)\n }\n\n // revert to right after the quote but before any whitespace, and continue parsing the string\n output = output.substring(0, oBefore)\n i = iQuote + 1\n\n // repair unescaped quote\n str = `${str.substring(0, oQuote)}\\\\${str.substring(oQuote)}`\n } else if (stopAtDelimiter && isUnquotedStringDelimiter(text[i])) {\n // we're in the mode to stop the string at the first delimiter\n // because there is an end quote missing\n\n // test start of an url like \"https://...\" (this would be parsed as a comment)\n if (text[i - 1] === ':' && regexUrlStart.test(text.substring(iBefore + 1, i + 2))) {\n while (i < text.length && regexUrlChar.test(text[i])) {\n str += text[i]\n i++\n }\n }\n\n // repair missing quote\n str = insertBeforeLastWhitespace(str, '\"')\n output += str\n\n parseConcatenatedString()\n\n return true\n } else if (text[i] === '\\\\') {\n // handle escaped content like \\n or \\u2605\n const char = text.charAt(i + 1)\n const escapeChar = escapeCharacters[char]\n if (escapeChar !== undefined) {\n str += text.slice(i, i + 2)\n i += 2\n } else if (char === 'u') {\n let j = 2\n while (j < 6 && isHex(text[i + j])) {\n j++\n }\n\n if (j === 6) {\n str += text.slice(i, i + 6)\n i += 6\n } else if (i + j >= text.length) {\n // repair invalid or truncated unicode char at the end of the text\n // by removing the unicode char and ending the string here\n i = text.length\n } else {\n throwInvalidUnicodeCharacter()\n }\n } else {\n // repair invalid escape character: remove it\n str += char\n i += 2\n }\n } else {\n // handle regular characters\n const char = text.charAt(i)\n\n if (char === '\"' && text[i - 1] !== '\\\\') {\n // repair unescaped double quote\n str += `\\\\${char}`\n i++\n } else if (isControlCharacter(char)) {\n // unescaped control character\n str += controlCharacters[char]\n i++\n } else {\n if (!isValidStringCharacter(char)) {\n throwInvalidCharacter(char)\n }\n str += char\n i++\n }\n }\n\n if (skipEscapeChars) {\n // repair: skipped escape character (nothing to do)\n skipEscapeCharacter()\n }\n }\n }\n\n return false\n }\n\n /**\n * Repair concatenated strings like \"hello\" + \"world\", change this into \"helloworld\"\n */\n function parseConcatenatedString(): boolean {\n let processed = false\n\n parseWhitespaceAndSkipComments()\n while (text[i] === '+') {\n processed = true\n i++\n parseWhitespaceAndSkipComments()\n\n // repair: remove the end quote of the first string\n output = stripLastOccurrence(output, '\"', true)\n const start = output.length\n const parsedStr = parseString()\n if (parsedStr) {\n // repair: remove the start quote of the second string\n output = removeAtIndex(output, start, 1)\n } else {\n // repair: remove the + because it is not followed by a string\n output = insertBeforeLastWhitespace(output, '\"')\n }\n }\n\n return processed\n }\n\n /**\n * Parse a number like 2.4 or 2.4e6\n */\n function parseNumber(): boolean {\n const start = i\n if (text[i] === '-') {\n i++\n if (atEndOfNumber()) {\n repairNumberEndingWithNumericSymbol(start)\n return true\n }\n if (!isDigit(text[i])) {\n i = start\n return false\n }\n }\n\n // Note that in JSON leading zeros like \"00789\" are not allowed.\n // We will allow all leading zeros here though and at the end of parseNumber\n // check against trailing zeros and repair that if needed.\n // Leading zeros can have meaning, so we should not clear them.\n while (isDigit(text[i])) {\n i++\n }\n\n if (text[i] === '.') {\n i++\n if (atEndOfNumber()) {\n repairNumberEndingWithNumericSymbol(start)\n return true\n }\n if (!isDigit(text[i])) {\n i = start\n return false\n }\n while (isDigit(text[i])) {\n i++\n }\n }\n\n if (text[i] === 'e' || text[i] === 'E') {\n i++\n if (text[i] === '-' || text[i] === '+') {\n i++\n }\n if (atEndOfNumber()) {\n repairNumberEndingWithNumericSymbol(start)\n return true\n }\n if (!isDigit(text[i])) {\n i = start\n return false\n }\n while (isDigit(text[i])) {\n i++\n }\n }\n\n // if we're not at the end of the number by this point, allow this to be parsed as another type\n if (!atEndOfNumber()) {\n i = start\n return false\n }\n\n if (i > start) {\n // repair a number with leading zeros like \"00789\"\n const num = text.slice(start, i)\n const hasInvalidLeadingZero = /^0\\d/.test(num)\n\n output += hasInvalidLeadingZero ? `\"${num}\"` : num\n return true\n }\n\n return false\n }\n\n /**\n * Parse keywords true, false, null\n * Repair Python keywords True, False, None\n */\n function parseKeywords(): boolean {\n return (\n parseKeyword('true', 'true') ||\n parseKeyword('false', 'false') ||\n parseKeyword('null', 'null') ||\n // repair Python keywords True, False, None\n parseKeyword('True', 'true') ||\n parseKeyword('False', 'false') ||\n parseKeyword('None', 'null')\n )\n }\n\n function parseKeyword(name: string, value: string): boolean {\n if (text.slice(i, i + name.length) === name) {\n output += value\n i += name.length\n return true\n }\n\n return false\n }\n\n /**\n * Repair an unquoted string by adding quotes around it\n * Repair a MongoDB function call like NumberLong(\"2\")\n * Repair a JSONP function call like callback({...});\n */\n function parseUnquotedString(isKey: boolean) {\n // note that the symbol can end with whitespaces: we stop at the next delimiter\n // also, note that we allow strings to contain a slash / in order to support repairing regular expressions\n const start = i\n\n if (isFunctionNameCharStart(text[i])) {\n while (i < text.length && isFunctionNameChar(text[i])) {\n i++\n }\n\n let j = i\n while (isWhitespace(text, j)) {\n j++\n }\n\n if (text[j] === '(') {\n // repair a MongoDB function call like NumberLong(\"2\")\n // repair a JSONP function call like callback({...});\n i = j + 1\n\n parseValue()\n\n if (text[i] === ')') {\n // repair: skip close bracket of function call\n i++\n if (text[i] === ';') {\n // repair: skip semicolon after JSONP call\n i++\n }\n }\n\n return true\n }\n }\n\n while (\n i < text.length &&\n !isUnquotedStringDelimiter(text[i]) &&\n !isQuote(text[i]) &&\n (!isKey || text[i] !== ':')\n ) {\n i++\n }\n\n // test start of an url like \"https://...\" (this would be parsed as a comment)\n if (text[i - 1] === ':' && regexUrlStart.test(text.substring(start, i + 2))) {\n while (i < text.length && regexUrlChar.test(text[i])) {\n i++\n }\n }\n\n if (i > start) {\n // repair unquoted string\n // also, repair undefined into null\n\n // first, go back to prevent getting trailing whitespaces in the string\n while (isWhitespace(text, i - 1) && i > 0) {\n i--\n }\n\n const symbol = text.slice(start, i)\n output += symbol === 'undefined' ? 'null' : JSON.stringify(symbol)\n\n if (text[i] === '\"') {\n // we had a missing start quote, but now we encountered the end quote, so we can skip that one\n i++\n }\n\n return true\n }\n }\n\n function parseRegex() {\n if (text[i] === '/') {\n const start = i\n i++\n\n while (i < text.length && (text[i] !== '/' || text[i - 1] === '\\\\')) {\n i++\n }\n i++\n\n output += `\"${text.substring(start, i)}\"`\n\n return true\n }\n }\n\n function prevNonWhitespaceIndex(start: number): number {\n let prev = start\n\n while (prev > 0 && isWhitespace(text, prev)) {\n prev--\n }\n\n return prev\n }\n\n function atEndOfNumber() {\n return i >= text.length || isDelimiter(text[i]) || isWhitespace(text, i)\n }\n\n function repairNumberEndingWithNumericSymbol(start: number) {\n // repair numbers cut off at the end\n // this will only be called when we end after a '.', '-', or 'e' and does not\n // change the number more than it needs to make it valid JSON\n output += `${text.slice(start, i)}0`\n }\n\n function throwInvalidCharacter(char: string) {\n throw new JSONRepairError(`Invalid character ${JSON.stringify(char)}`, i)\n }\n\n function throwUnexpectedCharacter() {\n throw new JSONRepairError(`Unexpected character ${JSON.stringify(text[i])}`, i)\n }\n\n function throwUnexpectedEnd() {\n throw new JSONRepairError('Unexpected end of json string', text.length)\n }\n\n function throwObjectKeyExpected() {\n throw new JSONRepairError('Object key expected', i)\n }\n\n function throwColonExpected() {\n throw new JSONRepairError('Colon expected', i)\n }\n\n function throwInvalidUnicodeCharacter() {\n const chars = text.slice(i, i + 6)\n throw new JSONRepairError(`Invalid unicode character \"${chars}\"`, i)\n }\n}\n\nfunction atEndOfBlockComment(text: string, i: number) {\n return text[i] === '*' && text[i + 1] === '/'\n}\n"],"mappings":";;;;;;AAAA,IAAAA,gBAAA,GAAAC,OAAA;AACA,IAAAC,YAAA,GAAAD,OAAA;AA0BA,MAAME,iBAA4C,GAAG;EACnD,IAAI,EAAE,KAAK;EACX,IAAI,EAAE,KAAK;EACX,IAAI,EAAE,KAAK;EACX,IAAI,EAAE,KAAK;EACX,IAAI,EAAE;AACR,CAAC;;AAED;AACA,MAAMC,gBAA2C,GAAG;EAClD,GAAG,EAAE,GAAG;EACR,IAAI,EAAE,IAAI;EACV,GAAG,EAAE,GAAG;EACRC,CAAC,EAAE,IAAI;EACPC,CAAC,EAAE,IAAI;EACPC,CAAC,EAAE,IAAI;EACPC,CAAC,EAAE,IAAI;EACPC,CAAC,EAAE;EACH;AACF,CAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASC,UAAUA,CAACC,IAAY,EAAU;EAC/C,IAAIC,CAAC,GAAG,CAAC,EAAC;EACV,IAAIC,MAAM,GAAG,EAAE,EAAC;;EAEhBC,sBAAsB,CAAC,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;EAE/C,MAAMC,SAAS,GAAGC,UAAU,CAAC,CAAC;EAC9B,IAAI,CAACD,SAAS,EAAE;IACdE,kBAAkB,CAAC,CAAC;EACtB;EAEAH,sBAAsB,CAAC,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;EAE/C,MAAMI,cAAc,GAAGC,cAAc,CAAC,GAAG,CAAC;EAC1C,IAAID,cAAc,EAAE;IAClBE,8BAA8B,CAAC,CAAC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AAgB,EAAEtG,CAAC,CAAC;EAChD;EAEA,SAASoF,4BAA4BA,CAAA,EAAG;IACtC,MAAMmB,KAAK,GAAGxG,IAAI,CAAC2C,KAAK,CAAC1C,CAAC,EAAEA,CAAC,GAAG,CAAC,CAAC;IAClC,MAAM,IAAIsG,gCAAe,CAAC,8BAA8BC,KAAK,GAAG,EAAEvG,CAAC,CAAC;EACtE;AACF;AAEA,SAASmC,mBAAmBA,CAACpC,IAAY,EAAEC,CAAS,EAAE;EACpD,OAAOD,IAAI,CAACC,CAAC,CAAC,KAAK,GAAG,IAAID,IAAI,CAACC,CAAC,GAAG,CAAC,CAAC,KAAK,GAAG;AAC/C","ignoreList":[]} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/stream.js b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/stream.js new file mode 100644 index 0000000000000000000000000000000000000000..40b7bf5bbb51a0fb2bb3f66bbfdfdb898b9706f5 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/stream.js @@ -0,0 +1,13 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "jsonrepairTransform", { + enumerable: true, + get: function () { + return _stream.jsonrepairTransform; + } +}); +var _stream = require("./streaming/stream.js"); +//# sourceMappingURL=stream.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/stream.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/stream.js.map new file mode 100644 index 0000000000000000000000000000000000000000..e15e649619a0277e8dd6cf6e0f071cd0305666ce --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/stream.js.map @@ -0,0 +1 @@ +{"version":3,"file":"stream.js","names":["_stream","require"],"sources":["../../src/stream.ts"],"sourcesContent":["// Node.js streaming API\nexport { type JsonRepairTransformOptions, jsonrepairTransform } from './streaming/stream.js'\n"],"mappings":";;;;;;;;;;;AACA,IAAAA,OAAA,GAAAC,OAAA","ignoreList":[]} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/streaming/buffer/InputBuffer.js b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/streaming/buffer/InputBuffer.js new file mode 100644 index 0000000000000000000000000000000000000000..2b3b186ec3c4c92914e7bf326d699a679768aa16 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/streaming/buffer/InputBuffer.js @@ -0,0 +1,75 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.createInputBuffer = createInputBuffer; +function createInputBuffer() { + let buffer = ''; + let offset = 0; + let currentLength = 0; + let closed = false; + function ensure(index) { + if (index < offset) { + throw new Error(`${indexOutOfRangeMessage} (index: ${index}, offset: ${offset})`); + } + if (index >= currentLength) { + if (!closed) { + throw new Error(`${indexOutOfRangeMessage} (index: ${index})`); + } + } + } + function push(chunk) { + buffer += chunk; + currentLength += chunk.length; + } + function flush(position) { + if (position > currentLength) { + return; + } + buffer = buffer.substring(position - offset); + offset = position; + } + function charAt(index) { + ensure(index); + return buffer.charAt(index - offset); + } + function charCodeAt(index) { + ensure(index); + return buffer.charCodeAt(index - offset); + } + function substring(start, end) { + ensure(end - 1); // -1 because end is excluded + ensure(start); + return buffer.slice(start - offset, end - offset); + } + function length() { + if (!closed) { + throw new Error('Cannot get length: input is not yet closed'); + } + return currentLength; + } + function isEnd(index) { + if (!closed) { + ensure(index); + } + return index >= currentLength; + } + function close() { + closed = true; + } + return { + push, + flush, + charAt, + charCodeAt, + substring, + length, + currentLength: () => currentLength, + currentBufferSize: () => buffer.length, + isEnd, + close + }; +} +const indexOutOfRangeMessage = 'Index out of range, please configure a larger buffer size'; +//# sourceMappingURL=InputBuffer.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/streaming/buffer/InputBuffer.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/streaming/buffer/InputBuffer.js.map new file mode 100644 index 0000000000000000000000000000000000000000..aae31a745a1cf09c9e1ba658d0c7c941da114dbb --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/streaming/buffer/InputBuffer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"InputBuffer.js","names":["createInputBuffer","buffer","offset","currentLength","closed","ensure","index","Error","indexOutOfRangeMessage","push","chunk","length","flush","position","substring","charAt","charCodeAt","start","end","slice","isEnd","close","currentBufferSize"],"sources":["../../../../src/streaming/buffer/InputBuffer.ts"],"sourcesContent":["export interface InputBuffer {\n push: (chunk: string) => void\n flush: (position: number) => void\n charAt: (index: number) => string\n charCodeAt: (index: number) => number\n substring: (start: number, end: number) => string\n length: () => number\n currentLength: () => number\n currentBufferSize: () => number\n isEnd: (index: number) => boolean\n close: () => void\n}\n\nexport function createInputBuffer(): InputBuffer {\n let buffer = ''\n let offset = 0\n let currentLength = 0\n let closed = false\n\n function ensure(index: number) {\n if (index < offset) {\n throw new Error(`${indexOutOfRangeMessage} (index: ${index}, offset: ${offset})`)\n }\n\n if (index >= currentLength) {\n if (!closed) {\n throw new Error(`${indexOutOfRangeMessage} (index: ${index})`)\n }\n }\n }\n\n function push(chunk: string) {\n buffer += chunk\n currentLength += chunk.length\n }\n\n function flush(position: number) {\n if (position > currentLength) {\n return\n }\n\n buffer = buffer.substring(position - offset)\n offset = position\n }\n\n function charAt(index: number): string {\n ensure(index)\n\n return buffer.charAt(index - offset)\n }\n\n function charCodeAt(index: number): number {\n ensure(index)\n\n return buffer.charCodeAt(index - offset)\n }\n\n function substring(start: number, end: number): string {\n ensure(end - 1) // -1 because end is excluded\n ensure(start)\n\n return buffer.slice(start - offset, end - offset)\n }\n\n function length(): number {\n if (!closed) {\n throw new Error('Cannot get length: input is not yet closed')\n }\n\n return currentLength\n }\n\n function isEnd(index: number): boolean {\n if (!closed) {\n ensure(index)\n }\n\n return index >= currentLength\n }\n\n function close() {\n closed = true\n }\n\n return {\n push,\n flush,\n charAt,\n charCodeAt,\n substring,\n length,\n currentLength: () => currentLength,\n currentBufferSize: () => buffer.length,\n isEnd,\n close\n }\n}\n\nconst indexOutOfRangeMessage = 'Index out of range, please configure a larger buffer size'\n"],"mappings":";;;;;;AAaO,SAASA,iBAAiBA,CAAA,EAAgB;EAC/C,IAAIC,MAAM,GAAG,EAAE;EACf,IAAIC,MAAM,GAAG,CAAC;EACd,IAAIC,aAAa,GAAG,CAAC;EACrB,IAAIC,MAAM,GAAG,KAAK;EAElB,SAASC,MAAMA,CAACC,KAAa,EAAE;IAC7B,IAAIA,KAAK,GAAGJ,MAAM,EAAE;MAClB,MAAM,IAAIK,KAAK,CAAC,GAAGC,sBAAsB,YAAYF,KAAK,aAAaJ,MAAM,GAAG,CAAC;IACnF;IAEA,IAAII,KAAK,IAAIH,aAAa,EAAE;MAC1B,IAAI,CAACC,MAAM,EAAE;QACX,MAAM,IAAIG,KAAK,CAAC,GAAGC,sBAAsB,YAAYF,KAAK,GAAG,CAAC;MAChE;IACF;EACF;EAEA,SAASG,IAAIA,CAACC,KAAa,EAAE;IAC3BT,MAAM,IAAIS,KAAK;IACfP,aAAa,IAAIO,KAAK,CAACC,MAAM;EAC/B;EAEA,SAASC,KAAKA,CAACC,QAAgB,EAAE;IAC/B,IAAIA,QAAQ,GAAGV,aAAa,EAAE;MAC5B;IACF;IAEAF,MAAM,GAAGA,MAAM,CAACa,SAAS,CAACD,QAAQ,GAAGX,MAAM,CAAC;IAC5CA,MAAM,GAAGW,QAAQ;EACnB;EAEA,SAASE,MAAMA,CAACT,KAAa,EAAU;IACrCD,MAAM,CAACC,KAAK,CAAC;IAEb,OAAOL,MAAM,CAACc,MAAM,CAACT,KAAK,GAAGJ,MAAM,CAAC;EACtC;EAEA,SAASc,UAAUA,CAACV,KAAa,EAAU;IACzCD,MAAM,CAACC,KAAK,CAAC;IAEb,OAAOL,MAAM,CAACe,UAAU,CAACV,KAAK,GAAGJ,MAAM,CAAC;EAC1C;EAEA,SAASY,SAASA,CAACG,KAAa,EAAEC,GAAW,EAAU;IACrDb,MAAM,CAACa,GAAG,GAAG,CAAC,CAAC,EAAC;IAChBb,MAAM,CAACY,KAAK,CAAC;IAEb,OAAOhB,MAAM,CAACkB,KAAK,CAACF,KAAK,GAAGf,MAAM,EAAEgB,GAAG,GAAGhB,MAAM,CAAC;EACnD;EAEA,SAASS,MAAMA,CAAA,EAAW;IACxB,IAAI,CAACP,MAAM,EAAE;MACX,MAAM,IAAIG,KAAK,CAAC,4CAA4C,CAAC;IAC/D;IAEA,OAAOJ,aAAa;EACtB;EAEA,SAASiB,KAAKA,CAACd,KAAa,EAAW;IACrC,IAAI,CAACF,MAAM,EAAE;MACXC,MAAM,CAACC,KAAK,CAAC;IACf;IAEA,OAAOA,KAAK,IAAIH,aAAa;EAC/B;EAEA,SAASkB,KAAKA,CAAA,EAAG;IACfjB,MAAM,GAAG,IAAI;EACf;EAEA,OAAO;IACLK,IAAI;IACJG,KAAK;IACLG,MAAM;IACNC,UAAU;IACVF,SAAS;IACTH,MAAM;IACNR,aAAa,EAAEA,CAAA,KAAMA,aAAa;IAClCmB,iBAAiB,EAAEA,CAAA,KAAMrB,MAAM,CAACU,MAAM;IACtCS,KAAK;IACLC;EACF,CAAC;AACH;AAEA,MAAMb,sBAAsB,GAAG,2DAA2D","ignoreList":[]} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/streaming/buffer/OutputBuffer.js b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/streaming/buffer/OutputBuffer.js new file mode 100644 index 0000000000000000000000000000000000000000..ec00531d09d67c8a7d26045cab8f1d424e886cd0 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/streaming/buffer/OutputBuffer.js @@ -0,0 +1,117 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.createOutputBuffer = createOutputBuffer; +var _stringUtils = require("../../utils/stringUtils.js"); +function createOutputBuffer(_ref) { + let { + write, + chunkSize, + bufferSize + } = _ref; + let buffer = ''; + let offset = 0; + function flushChunks() { + let minSize = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : bufferSize; + while (buffer.length >= minSize + chunkSize) { + const chunk = buffer.substring(0, chunkSize); + write(chunk); + offset += chunkSize; + buffer = buffer.substring(chunkSize); + } + } + function flush() { + flushChunks(0); + if (buffer.length > 0) { + write(buffer); + offset += buffer.length; + buffer = ''; + } + } + function push(text) { + buffer += text; + flushChunks(); + } + function unshift(text) { + if (offset > 0) { + throw new Error(`Cannot unshift: ${flushedMessage}`); + } + buffer = text + buffer; + flushChunks(); + } + function remove(start, end) { + if (start < offset) { + throw new Error(`Cannot remove: ${flushedMessage}`); + } + if (end !== undefined) { + buffer = buffer.substring(0, start - offset) + buffer.substring(end - offset); + } else { + buffer = buffer.substring(0, start - offset); + } + } + function insertAt(index, text) { + if (index < offset) { + throw new Error(`Cannot insert: ${flushedMessage}`); + } + buffer = buffer.substring(0, index - offset) + text + buffer.substring(index - offset); + } + function length() { + return offset + buffer.length; + } + function stripLastOccurrence(textToStrip) { + let stripRemainingText = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + const bufferIndex = buffer.lastIndexOf(textToStrip); + if (bufferIndex !== -1) { + if (stripRemainingText) { + buffer = buffer.substring(0, bufferIndex); + } else { + buffer = buffer.substring(0, bufferIndex) + buffer.substring(bufferIndex + textToStrip.length); + } + } + } + function insertBeforeLastWhitespace(textToInsert) { + let bufferIndex = buffer.length; // index relative to the start of the buffer, not taking `offset` into account + + if (!(0, _stringUtils.isWhitespace)(buffer, bufferIndex - 1)) { + // no trailing whitespaces + push(textToInsert); + return; + } + while ((0, _stringUtils.isWhitespace)(buffer, bufferIndex - 1)) { + bufferIndex--; + } + if (bufferIndex <= 0) { + throw new Error(`Cannot insert: ${flushedMessage}`); + } + buffer = buffer.substring(0, bufferIndex) + textToInsert + buffer.substring(bufferIndex); + flushChunks(); + } + function endsWithIgnoringWhitespace(char) { + let i = buffer.length - 1; + while (i > 0) { + if (char === buffer.charAt(i)) { + return true; + } + if (!(0, _stringUtils.isWhitespace)(buffer, i)) { + return false; + } + i--; + } + return false; + } + return { + push, + unshift, + remove, + insertAt, + length, + flush, + stripLastOccurrence, + insertBeforeLastWhitespace, + endsWithIgnoringWhitespace + }; +} +const flushedMessage = 'start of the output is already flushed from the buffer'; +//# sourceMappingURL=OutputBuffer.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/streaming/buffer/OutputBuffer.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/streaming/buffer/OutputBuffer.js.map new file mode 100644 index 0000000000000000000000000000000000000000..0de4cb7c5aa5f7b2e9801d877f1d3e9b82df3615 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/streaming/buffer/OutputBuffer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"OutputBuffer.js","names":["_stringUtils","require","createOutputBuffer","_ref","write","chunkSize","bufferSize","buffer","offset","flushChunks","minSize","arguments","length","undefined","chunk","substring","flush","push","text","unshift","Error","flushedMessage","remove","start","end","insertAt","index","stripLastOccurrence","textToStrip","stripRemainingText","bufferIndex","lastIndexOf","insertBeforeLastWhitespace","textToInsert","isWhitespace","endsWithIgnoringWhitespace","char","i","charAt"],"sources":["../../../../src/streaming/buffer/OutputBuffer.ts"],"sourcesContent":["import { isWhitespace } from '../../utils/stringUtils.js'\n\nexport interface OutputBuffer {\n push: (text: string) => void\n unshift: (text: string) => void\n remove: (start: number, end?: number) => void\n insertAt: (index: number, text: string) => void\n length: () => number\n flush: () => void\n\n stripLastOccurrence: (textToStrip: string, stripRemainingText?: boolean) => void\n insertBeforeLastWhitespace: (textToInsert: string) => void\n endsWithIgnoringWhitespace: (char: string) => boolean\n}\n\nexport interface OutputBufferOptions {\n write: (chunk: string) => void\n chunkSize: number\n bufferSize: number\n}\n\nexport function createOutputBuffer({\n write,\n chunkSize,\n bufferSize\n}: OutputBufferOptions): OutputBuffer {\n let buffer = ''\n let offset = 0\n\n function flushChunks(minSize = bufferSize) {\n while (buffer.length >= minSize + chunkSize) {\n const chunk = buffer.substring(0, chunkSize)\n write(chunk)\n offset += chunkSize\n buffer = buffer.substring(chunkSize)\n }\n }\n\n function flush() {\n flushChunks(0)\n\n if (buffer.length > 0) {\n write(buffer)\n offset += buffer.length\n buffer = ''\n }\n }\n\n function push(text: string) {\n buffer += text\n flushChunks()\n }\n\n function unshift(text: string) {\n if (offset > 0) {\n throw new Error(`Cannot unshift: ${flushedMessage}`)\n }\n\n buffer = text + buffer\n flushChunks()\n }\n\n function remove(start: number, end?: number) {\n if (start < offset) {\n throw new Error(`Cannot remove: ${flushedMessage}`)\n }\n\n if (end !== undefined) {\n buffer = buffer.substring(0, start - offset) + buffer.substring(end - offset)\n } else {\n buffer = buffer.substring(0, start - offset)\n }\n }\n\n function insertAt(index: number, text: string) {\n if (index < offset) {\n throw new Error(`Cannot insert: ${flushedMessage}`)\n }\n\n buffer = buffer.substring(0, index - offset) + text + buffer.substring(index - offset)\n }\n\n function length(): number {\n return offset + buffer.length\n }\n\n function stripLastOccurrence(textToStrip: string, stripRemainingText = false) {\n const bufferIndex = buffer.lastIndexOf(textToStrip)\n\n if (bufferIndex !== -1) {\n if (stripRemainingText) {\n buffer = buffer.substring(0, bufferIndex)\n } else {\n buffer =\n buffer.substring(0, bufferIndex) + buffer.substring(bufferIndex + textToStrip.length)\n }\n }\n }\n\n function insertBeforeLastWhitespace(textToInsert: string) {\n let bufferIndex = buffer.length // index relative to the start of the buffer, not taking `offset` into account\n\n if (!isWhitespace(buffer, bufferIndex - 1)) {\n // no trailing whitespaces\n push(textToInsert)\n return\n }\n\n while (isWhitespace(buffer, bufferIndex - 1)) {\n bufferIndex--\n }\n\n if (bufferIndex <= 0) {\n throw new Error(`Cannot insert: ${flushedMessage}`)\n }\n\n buffer = buffer.substring(0, bufferIndex) + textToInsert + buffer.substring(bufferIndex)\n flushChunks()\n }\n\n function endsWithIgnoringWhitespace(char: string): boolean {\n let i = buffer.length - 1\n\n while (i > 0) {\n if (char === buffer.charAt(i)) {\n return true\n }\n\n if (!isWhitespace(buffer, i)) {\n return false\n }\n\n i--\n }\n\n return false\n }\n\n return {\n push,\n unshift,\n remove,\n insertAt,\n length,\n flush,\n\n stripLastOccurrence,\n insertBeforeLastWhitespace,\n endsWithIgnoringWhitespace\n }\n}\n\nconst flushedMessage = 'start of the output is already flushed from the buffer'\n"],"mappings":";;;;;;AAAA,IAAAA,YAAA,GAAAC,OAAA;AAqBO,SAASC,kBAAkBA,CAAAC,IAAA,EAII;EAAA,IAJH;IACjCC,KAAK;IACLC,SAAS;IACTC;EACmB,CAAC,GAAAH,IAAA;EACpB,IAAII,MAAM,GAAG,EAAE;EACf,IAAIC,MAAM,GAAG,CAAC;EAEd,SAASC,WAAWA,CAAA,EAAuB;IAAA,IAAtBC,OAAO,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAGL,UAAU;IACvC,OAAOC,MAAM,CAACK,MAAM,IAAIF,OAAO,GAAGL,SAAS,EAAE;MAC3C,MAAMS,KAAK,GAAGP,MAAM,CAACQ,SAAS,CAAC,CAAC,EAAEV,SAAS,CAAC;MAC5CD,KAAK,CAACU,KAAK,CAAC;MACZN,MAAM,IAAIH,SAAS;MACnBE,MAAM,GAAGA,MAAM,CAACQ,SAAS,CAACV,SAAS,CAAC;IACtC;EACF;EAEA,SAASW,KAAKA,CAAA,EAAG;IACfP,WAAW,CAAC,CAAC,CAAC;IAEd,IAAIF,MAAM,CAACK,MAAM,GAAG,CAAC,EAAE;MACrBR,KAAK,CAACG,MAAM,CAAC;MACbC,MAAM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OyB,CAAC,GAAG,CAAC,EAAE;MACZ,IAAID,IAAI,KAAK7B,MAAM,CAAC+B,MAAM,CAACD,CAAC,CAAC,EAAE;QAC7B,OAAO,IAAI;MACb;MAEA,IAAI,CAAC,IAAAH,yBAAY,EAAC3B,MAAM,EAAE8B,CAAC,CAAC,EAAE;QAC5B,OAAO,KAAK;MACd;MAEAA,CAAC,EAAE;IACL;IAEA,OAAO,KAAK;EACd;EAEA,OAAO;IACLpB,IAAI;IACJE,OAAO;IACPG,MAAM;IACNG,QAAQ;IACRb,MAAM;IACNI,KAAK;IAELW,mBAAmB;IACnBK,0BAA0B;IAC1BG;EACF,CAAC;AACH;AAEA,MAAMd,cAAc,GAAG,wDAAwD","ignoreList":[]} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/streaming/core.js b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/streaming/core.js new file mode 100644 index 0000000000000000000000000000000000000000..f2f2eb520e96588da23d8bc2dc4c86e5c2e9b733 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/streaming/core.js @@ -0,0 +1,824 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.jsonrepairCore = jsonrepairCore; +var _JSONRepairError = require("../utils/JSONRepairError.js"); +var _stringUtils = require("../utils/stringUtils.js"); +var _InputBuffer = require("./buffer/InputBuffer.js"); +var _OutputBuffer = require("./buffer/OutputBuffer.js"); +var _stack = require("./stack.js"); +const controlCharacters = { + '\b': '\\b', + '\f': '\\f', + '\n': '\\n', + '\r': '\\r', + '\t': '\\t' +}; + +// map with all escape characters +const escapeCharacters = { + '"': '"', + '\\': '\\', + '/': '/', + b: '\b', + f: '\f', + n: '\n', + r: '\r', + t: '\t' + // note that \u is handled separately in parseString() +}; +function jsonrepairCore(_ref) { + let { + onData, + bufferSize = 65536, + chunkSize = 65536 + } = _ref; + const input = (0, _InputBuffer.createInputBuffer)(); + const output = (0, _OutputBuffer.createOutputBuffer)({ + write: onData, + bufferSize, + chunkSize + }); + let i = 0; + let iFlushed = 0; + const stack = (0, _stack.createStack)(); + function flushInputBuffer() { + while (iFlushed < i - bufferSize - chunkSize) { + iFlushed += chunkSize; + input.flush(iFlushed); + } + } + function transform(chunk) { + input.push(chunk); + while (i < input.currentLength() - bufferSize && parse()) { + // loop until there is nothing more to process + } + flushInputBuffer(); + } + function flush() { + input.close(); + while (parse()) { + // loop until there is nothing more to process + } + output.flush(); + } + function parse() { + parseWhitespaceAndSkipComments(); + switch (stack.type) { + case _stack.StackType.object: + { + switch (stack.caret) { + case _stack.Caret.beforeKey: + return skipEllipsis() || parseObjectKey() || parseUnexpectedColon() || parseRepairTrailingComma() || parseRepairObjectEndOrComma(); + case _stack.Caret.beforeValue: + return parseValue() || parseRepairMissingObjectValue(); + case _stack.Caret.afterValue: + return parseObjectComma() || parseObjectEnd() || parseRepairObjectEndOrComma(); + default: + return false; + } + } + case _stack.StackType.array: + { + switch (stack.caret) { + case _stack.Caret.beforeValue: + return skipEllipsis() || parseValue() || parseRepairTrailingComma() || parseRepairArrayEnd(); + case _stack.Caret.afterValue: + return parseArrayComma() || parseArrayEnd() || parseRepairMissingComma() || parseRepairArrayEnd(); + default: + return false; + } + } + case _stack.StackType.ndJson: + { + switch (stack.caret) { + case _stack.Caret.beforeValue: + return parseValue() || parseRepairTrailingComma(); + case _stack.Caret.afterValue: + return parseArrayComma() || parseRepairMissingComma() || parseRepairNdJsonEnd(); + default: + return false; + } + } + case _stack.StackType.functionCall: + { + switch (stack.caret) { + case _stack.Caret.beforeValue: + return parseValue(); + case _stack.Caret.afterValue: + return parseFunctionCallEnd(); + default: + return false; + } + } + case _stack.StackType.root: + { + switch (stack.caret) { + case _stack.Caret.beforeValue: + return parseRootStart(); + case _stack.Caret.afterValue: + return parseRootEnd(); + default: + return false; + } + } + default: + return false; + } + } + function parseValue() { + return parseObjectStart() || parseArrayStart() || parseString() || parseNumber() || parseKeywords() || parseRepairUnquotedString() || parseRepairRegex(); + } + function parseObjectStart() { + if (parseCharacter('{')) { + parseWhitespaceAndSkipComments(); + skipEllipsis(); + if (skipCharacter(',')) { + parseWhitespaceAndSkipComments(); + } + if (parseCharacter('}')) { + return stack.update(_stack.Caret.afterValue); + } + return stack.push(_stack.StackType.object, _stack.Caret.beforeKey); + } + return false; + } + function parseArrayStart() { + if (parseCharacter('[')) { + parseWhitespaceAndSkipComments(); + skipEllipsis(); + if (skipCharacter(',')) { + parseWhitespaceAndSkipComments(); + } + if (parseCharacter(']')) { + return stack.update(_stack.Caret.afterValue); + } + return stack.push(_stack.StackType.array, _stack.Caret.beforeValue); + } + return false; + } + function parseRepairUnquotedString() { + let j = i; + if ((0, _stringUtils.isFunctionNameCharStart)(input.charAt(j))) { + while (!input.isEnd(j) && (0, _stringUtils.isFunctionNameChar)(input.charAt(j))) { + j++; + } + let k = j; + while ((0, _stringUtils.isWhitespace)(input, k)) { + k++; + } + if (input.charAt(k) === '(') { + // repair a MongoDB function call like NumberLong("2") + // repair a JSONP function call like callback({...}); + k++; + i = k; + return stack.push(_stack.StackType.functionCall, _stack.Caret.beforeValue); + } + } + j = findNextDelimiter(false, j); + if (j !== null) { + // test start of an url like "https://..." (this would be parsed as a comment) + if (input.charAt(j - 1) === ':' && _stringUtils.regexUrlStart.test(input.substring(i, j + 2))) { + while (!input.isEnd(j) && _stringUtils.regexUrlChar.test(input.charAt(j))) { + j++; + } + } + const symbol = input.substring(i, j); + i = j; + output.push(symbol === 'undefined' ? 'null' : JSON.stringify(symbol)); + if (input.charAt(i) === '"') { + // we had a missing start quote, but now we encountered the end quote, so we can skip that one + i++; + } + return stack.update(_stack.Caret.afterValue); + } + return false; + } + function parseRepairRegex() { + if (input.charAt(i) === '/') { + const start = i; + i++; + while (!input.isEnd(i) && (input.charAt(i) !== '/' || input.charAt(i - 1) === '\\')) { + i++; + } + i++; + output.push(`"${input.substring(start, i)}"`); + return stack.update(_stack.Caret.afterValue); + } + } + function parseRepairMissingObjectValue() { + // repair missing object value + output.push('null'); + return stack.update(_stack.Caret.afterValue); + } + function parseRepairTrailingComma() { + // repair trailing comma + if (output.endsWithIgnoringWhitespace(',')) { + output.stripLastOccurrence(','); + return stack.update(_stack.Caret.afterValue); + } + return false; + } + function parseUnexpectedColon() { + if (input.charAt(i) === ':') { + throwObjectKeyExpected(); + } + return false; + } + function parseUnexpectedEnd() { + if (input.isEnd(i)) { + throwUnexpectedEnd(); + } else { + throwUnexpectedCharacter(); + } + return false; + } + function parseObjectKey() { + const parsedKey = parseString() || parseUnquotedKey(); + if (parsedKey) { + parseWhitespaceAndSkipComments(); + if (parseCharacter(':')) { + // expect a value after the : + return stack.update(_stack.Caret.beforeValue); + } + const truncatedText = input.isEnd(i); + if ((0, _stringUtils.isStartOfValue)(input.charAt(i)) || truncatedText) { + // repair missing colon + output.insertBeforeLastWhitespace(':'); + return stack.update(_stack.Caret.beforeValue); + } + throwColonExpected(); + } + return false; + } + function parseObjectComma() { + if (parseCharacter(',')) { + return stack.update(_stack.Caret.beforeKey); + } + return false; + } + function parseObjectEnd() { + if (parseCharacter('}')) { + return stack.pop(); + } + return false; + } + function parseRepairObjectEndOrComma() { + // repair missing object end and trailing comma + if (input.charAt(i) === '{') { + output.stripLastOccurrence(','); + output.insertBeforeLastWhitespace('}'); + return stack.pop(); + } + + // repair missing comma + if (!input.isEnd(i) && (0, _stringUtils.isStartOfValue)(input.charAt(i))) { + output.insertBeforeLastWhitespace(','); + return stack.update(_stack.Caret.beforeKey); + } + + // repair missing closing brace + output.insertBeforeLastWhitespace('}'); + return stack.pop(); + } + function parseArrayComma() { + if (parseCharacter(',')) { + return stack.update(_stack.Caret.beforeValue); + } + return false; + } + function parseArrayEnd() { + if (parseCharacter(']')) { + return stack.pop(); + } + return false; + } + function parseRepairMissingComma() { + // repair missing comma + if (!input.isEnd(i) && (0, _stringUtils.isStartOfValue)(input.charAt(i))) { + output.insertBeforeLastWhitespace(','); + return stack.update(_stack.Caret.beforeValue); + } + return false; + } + function parseRepairArrayEnd() { + // repair missing closing bracket + output.insertBeforeLastWhitespace(']'); + return stack.pop(); + } + function parseRepairNdJsonEnd() { + if (input.isEnd(i)) { + output.push('\n]'); + return stack.pop(); + } + throwUnexpectedEnd(); + return false; // just to make TS happy + } + function parseFunctionCallEnd() { + if (skipCharacter(')')) { + skipCharacter(';'); + } + return stack.pop(); + } + function parseRootStart() { + parseMarkdownCodeBlock(['```', '[```', '{```']); + return parseValue() || parseUnexpectedEnd(); + } + function parseRootEnd() { + parseMarkdownCodeBlock(['```', '```]', '```}']); + const parsedComma = parseCharacter(','); + parseWhitespaceAndSkipComments(); + if ((0, _stringUtils.isStartOfValue)(input.charAt(i)) && (output.endsWithIgnoringWhitespace(',') || output.endsWithIgnoringWhitespace('\n'))) { + // start of a new value after end of the root level object: looks like + // newline delimited JSON -> turn into a root level array + if (!parsedComma) { + // repair missing comma + output.insertBeforeLastWhitespace(','); + } + output.unshift('[\n'); + return stack.push(_stack.StackType.ndJson, _stack.Caret.beforeValue); + } + if (parsedComma) { + // repair: remove trailing comma + output.stripLastOccurrence(','); + return stack.update(_stack.Caret.afterValue); + } + + // repair redundant end braces and brackets + while (input.charAt(i) === '}' || input.charAt(i) === ']') { + i++; + parseWhitespaceAndSkipComments(); + } + if (!input.isEnd(i)) { + throwUnexpectedCharacter(); + } + return false; + } + function parseWhitespaceAndSkipComments() { + let skipNewline = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; + const start = i; + let changed = parseWhitespace(skipNewline); + do { + changed = parseComment(); + if (changed) { + changed = parseWhitespace(skipNewline); + } + } while (changed); + return i > start; + } + function parseWhitespace(skipNewline) { + const _isWhiteSpace = skipNewline ? _stringUtils.isWhitespace : _stringUtils.isWhitespaceExceptNewline; + let whitespace = ''; + while (true) { + if (_isWhiteSpace(input, i)) { + whitespace += input.charAt(i); + i++; + } else if ((0, _stringUtils.isSpecialWhitespace)(input, i)) { + // repair special whitespace + whitespace += ' '; + i++; + } else { + break; + } + } + if (whitespace.length > 0) { + output.push(whitespace); + return true; + } + return false; + } + function parseComment() { + // find a block comment '/* ... */' + if (input.charAt(i) === '/' && input.charAt(i + 1) === '*') { + // repair block comment by skipping it + while (!input.isEnd(i) && !atEndOfBlockComment(i)) { + i++; + } + i += 2; + return true; + } + + // find a line comment '// ...' + if (input.charAt(i) === '/' && input.charAt(i + 1) === '/') { + // repair line comment by skipping it + while (!input.isEnd(i) && input.charAt(i) !== '\n') { + i++; + } + return true; + } + return false; + } + function parseMarkdownCodeBlock(blocks) { + // find and skip over a Markdown fenced code block: + // ``` ... ``` + // or + // ```json ... ``` + if (skipMarkdownCodeBlock(blocks)) { + if ((0, _stringUtils.isFunctionNameCharStart)(input.charAt(i))) { + // strip the optional language specifier like "json" + while (!input.isEnd(i) && (0, _stringUtils.isFunctionNameChar)(input.charAt(i))) { + i++; + } + } + parseWhitespaceAndSkipComments(); + return true; + } + return false; + } + function skipMarkdownCodeBlock(blocks) { + for (const block of blocks) { + const end = i + block.length; + if (input.substring(i, end) === block) { + i = end; + return true; + } + } + return false; + } + function parseCharacter(char) { + if (input.charAt(i) === char) { + output.push(input.charAt(i)); + i++; + return true; + } + return false; + } + function skipCharacter(char) { + if (input.charAt(i) === char) { + i++; + return true; + } + return false; + } + function skipEscapeCharacter() { + return skipCharacter('\\'); + } + + /** + * Skip ellipsis like "[1,2,3,...]" or "[1,2,3,...,9]" or "[...,7,8,9]" + * or a similar construct in objects. + */ + function skipEllipsis() { + parseWhitespaceAndSkipComments(); + if (input.charAt(i) === '.' && input.charAt(i + 1) === '.' && input.charAt(i + 2) === '.') { + // repair: remove the ellipsis (three dots) and optionally a comma + i += 3; + parseWhitespaceAndSkipComments(); + skipCharacter(','); + return true; + } + return false; + } + + /** + * Parse a string enclosed by double quotes "...". Can contain escaped quotes + * Repair strings enclosed in single quotes or special quotes + * Repair an escaped string + * + * The function can run in two stages: + * - First, it assumes the string has a valid end quote + * - If it turns out that the string does not have a valid end quote followed + * by a delimiter (which should be the case), the function runs again in a + * more conservative way, stopping the string at the first next delimiter + * and fixing the string by inserting a quote there, or stopping at a + * stop index detected in the first iteration. + */ + function parseString() { + let stopAtDelimiter = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + let stopAtIndex = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : -1; + let skipEscapeChars = input.charAt(i) === '\\'; + if (skipEscapeChars) { + // repair: remove the first escape character + i++; + skipEscapeChars = true; + } + if ((0, _stringUtils.isQuote)(input.charAt(i))) { + // double quotes are correct JSON, + // single quotes come from JavaScript for example, we assume it will have a correct single end quote too + // otherwise, we will match any double-quote-like start with a double-quote-like end, + // or any single-quote-like start with a single-quote-like end + const isEndQuote = (0, _stringUtils.isDoubleQuote)(input.charAt(i)) ? _stringUtils.isDoubleQuote : (0, _stringUtils.isSingleQuote)(input.charAt(i)) ? _stringUtils.isSingleQuote : (0, _stringUtils.isSingleQuoteLike)(input.charAt(i)) ? _stringUtils.isSingleQuoteLike : _stringUtils.isDoubleQuoteLike; + const iBefore = i; + const oBefore = output.length(); + output.push('"'); + i++; + while (true) { + if (input.isEnd(i)) { + // end of text, we have a missing quote somewhere + + const iPrev = prevNonWhitespaceIndex(i - 1); + if (!stopAtDelimiter && (0, _stringUtils.isDelimiter)(input.charAt(iPrev))) { + // if the text ends with a delimiter, like ["hello], + // so the missing end quote should be inserted before this delimiter + // retry parsing the string, stopping at the first next delimiter + i = iBefore; + output.remove(oBefore); + return parseString(true); + } + + // repair missing quote + output.insertBeforeLastWhitespace('"'); + return stack.update(_stack.Caret.afterValue); + } + if (i === stopAtIndex) { + // use the stop index detected in the first iteration, and repair end quote + output.insertBeforeLastWhitespace('"'); + return stack.update(_stack.Caret.afterValue); + } + if (isEndQuote(input.charAt(i))) { + // end quote + // let us check what is before and after the quote to verify whether this is a legit end quote + const iQuote = i; + const oQuote = output.length(); + output.push('"'); + i++; + parseWhitespaceAndSkipComments(false); + if (stopAtDelimiter || input.isEnd(i) || (0, _stringUtils.isDelimiter)(input.charAt(i)) || (0, _stringUtils.isQuote)(input.charAt(i)) || (0, _stringUtils.isDigit)(input.charAt(i))) { + // The quote is followed by the end of the text, a delimiter, or a next value + // so the quote is indeed the end of the string + parseConcatenatedString(); + return stack.update(_stack.Caret.afterValue); + } + const iPrevChar = prevNonWhitespaceIndex(iQuote - 1); + const prevChar = input.charAt(iPrevChar); + if (prevChar === ',') { + // A comma followed by a quote, like '{"a":"b,c,"d":"e"}'. + // We assume that the quote is a start quote, and that the end quote + // should have been located right before the comma but is missing. + i = iBefore; + output.remove(oBefore); + return parseString(false, iPrevChar); + } + if ((0, _stringUtils.isDelimiter)(prevChar)) { + // This is not the right end quote: it is preceded by a delimiter, + // and NOT followed by a delimiter. So, there is an end quote missing + // parse the string again and then stop at the first next delimiter + i = iBefore; + output.remove(oBefore); + return parseString(true); + } + + // revert to right after the quote but before any whitespace, and continue parsing the string + output.remove(oQuote + 1); + i = iQuote + 1; + + // repair unescaped quote + output.insertAt(oQuote, '\\'); + } else if (stopAtDelimiter && (0, _stringUtils.isUnquotedStringDelimiter)(input.charAt(i))) { + // we're in the mode to stop the string at the first delimiter + // because there is an end quote missing + + // test start of an url like "https://..." (this would be parsed as a comment) + if (input.charAt(i - 1) === ':' && _stringUtils.regexUrlStart.test(input.substring(iBefore + 1, i + 2))) { + while (!input.isEnd(i) && _stringUtils.regexUrlChar.test(input.charAt(i))) { + output.push(input.charAt(i)); + i++; + } + } + + // repair missing quote + output.insertBeforeLastWhitespace('"'); + parseConcatenatedString(); + return stack.update(_stack.Caret.afterValue); + } else if (input.charAt(i) === '\\') { + // handle escaped content like \n or \u2605 + const char = input.charAt(i + 1); + const escapeChar = escapeCharacters[char]; + if (escapeChar !== undefined) { + output.push(input.substring(i, i + 2)); + i += 2; + } else if (char === 'u') { + let j = 2; + while (j < 6 && (0, _stringUtils.isHex)(input.charAt(i + j))) { + j++; + } + if (j === 6) { + output.push(input.substring(i, i + 6)); + i += 6; + } else if (input.isEnd(i + j)) { + // repair invalid or truncated unicode char at the end of the text + // by removing the unicode char and ending the string here + i += j; + } else { + throwInvalidUnicodeCharacter(); + } + } else { + // repair invalid escape character: remove it + output.push(char); + i += 2; + } + } else { + // handle regular characters + const char = input.charAt(i); + if (char === '"' && input.charAt(i - 1) !== '\\') { + // repair unescaped double quote + output.push(`\\${char}`); + i++; + } else if ((0, _stringUtils.isControlCharacter)(char)) { + // unescaped control character + output.push(controlCharacters[char]); + i++; + } else { + if (!(0, _stringUtils.isValidStringCharacter)(char)) { + throwInvalidCharacter(char); + } + output.push(char); + i++; + } + } + if (skipEscapeChars) { + // repair: skipped escape character (nothing to do) + skipEscapeCharacter(); + } + } + } + return false; + } + + /** + * Repair concatenated strings like "hello" + "world", change this into "helloworld" + */ + function parseConcatenatedString() { + let parsed = false; + parseWhitespaceAndSkipComments(); + while (input.charAt(i) === '+') { + parsed = true; + i++; + parseWhitespaceAndSkipComments(); + + // repair: remove the end quote of the first string + output.stripLastOccurrence('"', true); + const start = output.length(); + const parsedStr = parseString(); + if (parsedStr) { + // repair: remove the start quote of the second string + output.remove(start, start + 1); + } else { + // repair: remove the + because it is not followed by a string + output.insertBeforeLastWhitespace('"'); + } + } + return parsed; + } + + /** + * Parse a number like 2.4 or 2.4e6 + */ + function parseNumber() { + const start = i; + if (input.charAt(i) === '-') { + i++; + if (atEndOfNumber()) { + repairNumberEndingWithNumericSymbol(start); + return stack.update(_stack.Caret.afterValue); + } + if (!(0, _stringUtils.isDigit)(input.charAt(i))) { + i = start; + return false; + } + } + + // Note that in JSON leading zeros like "00789" are not allowed. + // We will allow all leading zeros here though and at the end of parseNumber + // check against trailing zeros and repair that if needed. + // Leading zeros can have meaning, so we should not clear them. + while ((0, _stringUtils.isDigit)(input.charAt(i))) { + i++; + } + if (input.charAt(i) === '.') { + i++; + if (atEndOfNumber()) { + repairNumberEndingWithNumericSymbol(start); + return stack.update(_stack.Caret.afterValue); + } + if (!(0, _stringUtils.isDigit)(input.charAt(i))) { + i = start; + return false; + } + while ((0, _stringUtils.isDigit)(input.charAt(i))) { + i++; + } + } + if (input.charAt(i) === 'e' || input.charAt(i) === 'E') { + i++; + if (input.charAt(i) === '-' || input.charAt(i) === '+') { + i++; + } + if (atEndOfNumber()) { + repairNumberEndingWithNumericSymbol(start); + return stack.update(_stack.Caret.afterValue); + } + if (!(0, _stringUtils.isDigit)(input.charAt(i))) { + i = start; + return false; + } + while ((0, _stringUtils.isDigit)(input.charAt(i))) { + i++; + } + } + + // if we're not at the end of the number by this point, allow this to be parsed as another type + if (!atEndOfNumber()) { + i = start; + return false; + } + if (i > start) { + // repair a number with leading zeros like "00789" + const num = input.substring(start, i); + const hasInvalidLeadingZero = /^0\d/.test(num); + output.push(hasInvalidLeadingZero ? `"${num}"` : num); + return stack.update(_stack.Caret.afterValue); + } + return false; + } + + /** + * Parse keywords true, false, null + * Repair Python keywords True, False, None + */ + function parseKeywords() { + return parseKeyword('true', 'true') || parseKeyword('false', 'false') || parseKeyword('null', 'null') || + // repair Python keywords True, False, None + parseKeyword('True', 'true') || parseKeyword('False', 'false') || parseKeyword('None', 'null'); + } + function parseKeyword(name, value) { + if (input.substring(i, i + name.length) === name) { + output.push(value); + i += name.length; + return stack.update(_stack.Caret.afterValue); + } + return false; + } + function parseUnquotedKey() { + let end = findNextDelimiter(true, i); + if (end !== null) { + // first, go back to prevent getting trailing whitespaces in the string + while ((0, _stringUtils.isWhitespace)(input, end - 1) && end > i) { + end--; + } + const symbol = input.substring(i, end); + output.push(JSON.stringify(symbol)); + i = end; + if (input.charAt(i) === '"') { + // we had a missing start quote, but now we encountered the end quote, so we can skip that one + i++; + } + return stack.update(_stack.Caret.afterValue); // we do not have a state Caret.afterKey, therefore we use afterValue here + } + return false; + } + function findNextDelimiter(isKey, start) { + // note that the symbol can end with whitespaces: we stop at the next delimiter + // also, note that we allow strings to contain a slash / in order to support repairing regular expressions + let j = start; + while (!input.isEnd(j) && !(0, _stringUtils.isUnquotedStringDelimiter)(input.charAt(j)) && !(0, _stringUtils.isQuote)(input.charAt(j)) && (!isKey || input.charAt(j) !== ':')) { + j++; + } + return j > i ? j : null; + } + function prevNonWhitespaceIndex(start) { + let prev = start; + while (prev > 0 && (0, _stringUtils.isWhitespace)(input, prev)) { + prev--; + } + return prev; + } + function atEndOfNumber() { + return input.isEnd(i) || (0, _stringUtils.isDelimiter)(input.charAt(i)) || (0, _stringUtils.isWhitespace)(input, i); + } + function repairNumberEndingWithNumericSymbol(start) { + // repair numbers cut off at the end + // this will only be called when we end after a '.', '-', or 'e' and does not + // change the number more than it needs to make it valid JSON + output.push(`${input.substring(start, i)}0`); + } + function throwInvalidCharacter(char) { + throw new _JSONRepairError.JSONRepairError(`Invalid character ${JSON.stringify(char)}`, i); + } + function throwUnexpectedCharacter() { + throw new _JSONRepairError.JSONRepairError(`Unexpected character ${JSON.stringify(input.charAt(i))}`, i); + } + function throwUnexpectedEnd() { + throw new _JSONRepairError.JSONRepairError('Unexpected end of json string', i); + } + function throwObjectKeyExpected() { + throw new _JSONRepairError.JSONRepairError('Object key expected', i); + } + function throwColonExpected() { + throw new _JSONRepairError.JSONRepairError('Colon expected', i); + } + function throwInvalidUnicodeCharacter() { + const chars = input.substring(i, i + 6); + throw new _JSONRepairError.JSONRepairError(`Invalid unicode character "${chars}"`, i); + } + function atEndOfBlockComment(i) { + return input.charAt(i) === '*' && input.charAt(i + 1) === '/'; + } + return { + transform, + flush + }; +} +//# sourceMappingURL=core.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/streaming/core.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/streaming/core.js.map new file mode 100644 index 0000000000000000000000000000000000000000..6dba9598fba3bd33217b2041ae4ce87f5e321fab --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/streaming/core.js.map @@ -0,0 +1 @@ +{"version":3,"file":"core.js","names":["_JSONRepairError","require","_stringUtils","_InputBuffer","_OutputBuffer","_stack","controlCharacters","escapeCharacters","b","f","n","r","t","jsonrepairCore","_ref","onData","bufferSize","chunkSize","input","createInputBuffer","output","createOutputBuffer","write","i","iFlushed","stack","createStack","flushInputBuffer","flush","transform","chunk","push","currentLength","parse","close","parseWhitespaceAndSkipComments","type","StackType","object","caret","Caret","beforeKey","skipEllipsis","parseObjectKey","parseUnexpectedColon","parseRepairTrailingComma","parseRepairObjectEndOrComma","beforeValue","parseValue","parseRepairMissingObjectValue","afterValue","parseObjectComma","parseObjectEnd","array","parseRepairArrayEnd","parseArrayComma","parseArrayEnd","parseRepairMissingComma","ndJson","parseRepairNdJsonEnd","functionCall","parseFunctionCallEnd","root","parseRootStart","parseRootEnd","parseObjectStart","parseArrayStart","parseString","parseNumber","parseKeywords","parseRepairUnquotedString","parseRepairRegex","parseCharacter","skipCharacter","update","j","isFunctionNameCharStart","charAt","isEnd","isFunctionNameChar","k","isWhitespace","findNextDelimiter","regexUrlStart","test","substring","regexUrlChar","symbol","JSON","stringify","start","endsWithIgnoringWhitespace","stripLastOccurrence","throwObjectKeyExpected","parseUnexpectedEnd","throwUnexpectedEnd","throwUnexpectedCharacter","parsedKey","parseUnquotedKey","truncatedText","isStartOfValue","insertBeforeLastWhitespace","throwColonExpected","pop","parseMarkdownCodeBlock","parsedComma","unshift","skipNewline","arguments","length","undefined","changed","parseWhitespace","parseComment","_isWhiteSpace","isWhitespaceExceptNewline","whitespace","isSpecialWhitespace","atEndOfBlockComment","blocks","skipMarkdownCodeBlock","block","end","char","skipEscapeCharacter","stopAtDelimiter","stopAtIndex","skipEscapeChars","isQuote","isEndQuote","isDoubleQuote","isSingleQuote","isSingleQuoteLike","isDoubleQuoteLike","iBefore","oBefore","iPrev","prevNonWhitespaceIndex","isDelimiter","remove","iQuote","oQuote","isDigit","parseConcatenatedString","iPrevChar","prevChar","insertAt","isUnquotedStringDelimiter","escapeChar","isHex","throwInvalidUnicodeCharacter","isControlCharacter","isValidStringCharacter","throwInvalidCharacter","parsed","parsedStr","atEndOfNumber","repairNumberEndingWithNumericSymbol","num","hasInvalidLeadingZero","parseKeyword","name","value","isKey","prev","JSONRepairError","chars"],"sources":["../../../src/streaming/core.ts"],"sourcesContent":["import { JSONRepairError } from '../utils/JSONRepairError.js'\nimport {\n isControlCharacter,\n isDelimiter,\n isDigit,\n isDoubleQuote,\n isDoubleQuoteLike,\n isFunctionNameChar,\n isFunctionNameCharStart,\n isHex,\n isQuote,\n isSingleQuote,\n isSingleQuoteLike,\n isSpecialWhitespace,\n isStartOfValue,\n isUnquotedStringDelimiter,\n isValidStringCharacter,\n isWhitespace,\n isWhitespaceExceptNewline,\n regexUrlChar,\n regexUrlStart\n} from '../utils/stringUtils.js'\nimport { createInputBuffer } from './buffer/InputBuffer.js'\nimport { createOutputBuffer } from './buffer/OutputBuffer.js'\nimport { Caret, createStack, StackType } from './stack.js'\n\nconst controlCharacters: { [key: string]: string } = {\n '\\b': '\\\\b',\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t'\n}\n\n// map with all escape characters\nconst escapeCharacters: { [key: string]: string } = {\n '\"': '\"',\n '\\\\': '\\\\',\n '/': '/',\n b: '\\b',\n f: '\\f',\n n: '\\n',\n r: '\\r',\n t: '\\t'\n // note that \\u is handled separately in parseString()\n}\n\nexport interface JsonRepairCoreOptions {\n onData: (chunk: string) => void\n chunkSize?: number\n bufferSize?: number\n}\n\nexport interface JsonRepairCore {\n transform: (chunk: string) => void\n flush: () => void\n}\n\nexport function jsonrepairCore({\n onData,\n bufferSize = 65536,\n chunkSize = 65536\n}: JsonRepairCoreOptions): JsonRepairCore {\n const input = createInputBuffer()\n\n const output = createOutputBuffer({\n write: onData,\n bufferSize,\n chunkSize\n })\n\n let i = 0\n let iFlushed = 0\n const stack = createStack()\n\n function flushInputBuffer() {\n while (iFlushed < i - bufferSize - chunkSize) {\n iFlushed += chunkSize\n input.flush(iFlushed)\n }\n }\n\n function transform(chunk: string) {\n input.push(chunk)\n\n while (i < input.currentLength() - bufferSize && parse()) {\n // loop until there is nothing more to process\n }\n\n flushInputBuffer()\n }\n\n function flush() {\n input.close()\n\n while (parse()) {\n // loop until there is nothing more to process\n }\n\n output.flush()\n }\n\n function parse(): boolean {\n parseWhitespaceAndSkipComments()\n\n switch (stack.type) {\n case StackType.object: {\n switch (stack.caret) {\n case Caret.beforeKey:\n return (\n skipEllipsis() ||\n parseObjectKey() ||\n parseUnexpectedColon() ||\n parseRepairTrailingComma() ||\n parseRepairObjectEndOrComma()\n )\n case Caret.beforeValue:\n return parseValue() || parseRepairMissingObjectValue()\n case Caret.afterValue:\n return parseObjectComma() || parseObjectEnd() || parseRepairObjectEndOrComma()\n default:\n return false\n }\n }\n\n case StackType.array: {\n switch (stack.caret) {\n case Caret.beforeValue:\n return (\n skipEllipsis() || parseValue() || parseRepairTrailingComma() || parseRepairArrayEnd()\n )\n case Caret.afterValue:\n return (\n parseArrayComma() ||\n parseArrayEnd() ||\n parseRepairMissingComma() ||\n parseRepairArrayEnd()\n )\n default:\n return false\n }\n }\n\n case StackType.ndJson: {\n switch (stack.caret) {\n case Caret.beforeValue:\n return parseValue() || parseRepairTrailingComma()\n case Caret.afterValue:\n return parseArrayComma() || parseRepairMissingComma() || parseRepairNdJsonEnd()\n default:\n return false\n }\n }\n\n case StackType.functionCall: {\n switch (stack.caret) {\n case Caret.beforeValue:\n return parseValue()\n case Caret.afterValue:\n return parseFunctionCallEnd()\n default:\n return false\n }\n }\n\n case StackType.root: {\n switch (stack.caret) {\n case Caret.beforeValue:\n return parseRootStart()\n case Caret.afterValue:\n return parseRootEnd()\n default:\n return false\n }\n }\n\n default:\n return false\n }\n }\n\n function parseValue(): boolean {\n return (\n parseObjectStart() ||\n parseArrayStart() ||\n parseString() ||\n parseNumber() ||\n parseKeywords() ||\n parseRepairUnquotedString() ||\n parseRepairRegex()\n )\n }\n\n function parseObjectStart(): boolean {\n if (parseCharacter('{')) {\n parseWhitespaceAndSkipComments()\n\n skipEllipsis()\n\n if (skipCharacter(',')) {\n parseWhitespaceAndSkipComments()\n }\n\n if (parseCharacter('}')) {\n return stack.update(Caret.afterValue)\n }\n\n return stack.push(StackType.object, Caret.beforeKey)\n }\n\n return false\n }\n\n function parseArrayStart(): boolean {\n if (parseCharacter('[')) {\n parseWhitespaceAndSkipComments()\n\n skipEllipsis()\n\n if (skipCharacter(',')) {\n parseWhitespaceAndSkipComments()\n }\n\n if (parseCharacter(']')) {\n return stack.update(Caret.afterValue)\n }\n\n return stack.push(StackType.array, Caret.beforeValue)\n }\n\n return false\n }\n\n function parseRepairUnquotedString(): boolean {\n let j = i\n\n if (isFunctionNameCharStart(input.charAt(j))) {\n while (!input.isEnd(j) && isFunctionNameChar(input.charAt(j))) {\n j++\n }\n\n let k = j\n while (isWhitespace(input, k)) {\n k++\n }\n\n if (input.charAt(k) === '(') {\n // repair a MongoDB function call like NumberLong(\"2\")\n // repair a JSONP function call like callback({...});\n k++\n i = k\n return stack.push(StackType.functionCall, Caret.beforeValue)\n }\n }\n\n j = findNextDelimiter(false, j)\n if (j !== null) {\n // test start of an url like \"https://...\" (this would be parsed as a comment)\n if (input.charAt(j - 1) === ':' && regexUrlStart.test(input.substring(i, j + 2))) {\n while (!input.isEnd(j) && regexUrlChar.test(input.charAt(j))) {\n j++\n }\n }\n\n const symbol = input.substring(i, j)\n i = j\n\n output.push(symbol === 'undefined' ? 'null' : JSON.stringify(symbol))\n\n if (input.charAt(i) === '\"') {\n // we had a missing start quote, but now we encountered the end quote, so we can skip that one\n i++\n }\n\n return stack.update(Caret.afterValue)\n }\n\n return false\n }\n\n function parseRepairRegex() {\n if (input.charAt(i) === '/') {\n const start = i\n i++\n\n while (!input.isEnd(i) && (input.charAt(i) !== '/' || input.charAt(i - 1) === '\\\\')) {\n i++\n }\n i++\n\n output.push(`\"${input.substring(start, i)}\"`)\n\n return stack.update(Caret.afterValue)\n }\n }\n\n function parseRepairMissingObjectValue(): boolean {\n // repair missing object value\n output.push('null')\n return stack.update(Caret.afterValue)\n }\n\n function parseRepairTrailingComma(): boolean {\n // repair trailing comma\n if (output.endsWithIgnoringWhitespace(',')) {\n output.stripLastOccurrence(',')\n return stack.update(Caret.afterValue)\n }\n\n return false\n }\n\n function parseUnexpectedColon(): boolean {\n if (input.charAt(i) === ':') {\n throwObjectKeyExpected()\n }\n\n return false\n }\n\n function parseUnexpectedEnd(): boolean {\n if (input.isEnd(i)) {\n throwUnexpectedEnd()\n } else {\n throwUnexpectedCharacter()\n }\n\n return false\n }\n\n function parseObjectKey(): boolean {\n const parsedKey = parseString() || parseUnquotedKey()\n if (parsedKey) {\n parseWhitespaceAndSkipComments()\n\n if (parseCharacter(':')) {\n // expect a value after the :\n return stack.update(Caret.beforeValue)\n }\n\n const truncatedText = input.isEnd(i)\n if (isStartOfValue(input.charAt(i)) || truncatedText) {\n // repair missing colon\n output.insertBeforeLastWhitespace(':')\n return stack.update(Caret.beforeValue)\n }\n\n throwColonExpected()\n }\n\n return false\n }\n\n function parseObjectComma(): boolean {\n if (parseCharacter(',')) {\n return stack.update(Caret.beforeKey)\n }\n\n return false\n }\n\n function parseObjectEnd(): boolean {\n if (parseCharacter('}')) {\n return stack.pop()\n }\n\n return false\n }\n\n function parseRepairObjectEndOrComma(): true {\n // repair missing object end and trailing comma\n if (input.charAt(i) === '{') {\n output.stripLastOccurrence(',')\n output.insertBeforeLastWhitespace('}')\n return stack.pop()\n }\n\n // repair missing comma\n if (!input.isEnd(i) && isStartOfValue(input.charAt(i))) {\n output.insertBeforeLastWhitespace(',')\n return stack.update(Caret.beforeKey)\n }\n\n // repair missing closing brace\n output.insertBeforeLastWhitespace('}')\n return stack.pop()\n }\n\n function parseArrayComma(): boolean {\n if (parseCharacter(',')) {\n return stack.update(Caret.beforeValue)\n }\n\n return false\n }\n\n function parseArrayEnd(): boolean {\n if (parseCharacter(']')) {\n return stack.pop()\n }\n\n return false\n }\n\n function parseRepairMissingComma(): boolean {\n // repair missing comma\n if (!input.isEnd(i) && isStartOfValue(input.charAt(i))) {\n output.insertBeforeLastWhitespace(',')\n return stack.update(Caret.beforeValue)\n }\n\n return false\n }\n\n function parseRepairArrayEnd(): true {\n // repair missing closing bracket\n output.insertBeforeLastWhitespace(']')\n return stack.pop()\n }\n\n function parseRepairNdJsonEnd(): boolean {\n if (input.isEnd(i)) {\n output.push('\\n]')\n return stack.pop()\n }\n\n throwUnexpectedEnd()\n return false // just to make TS happy\n }\n\n function parseFunctionCallEnd(): true {\n if (skipCharacter(')')) {\n skipCharacter(';')\n }\n\n return stack.pop()\n }\n\n function parseRootStart(): boolean {\n parseMarkdownCodeBlock(['```', '[```', '{```'])\n\n return parseValue() || parseUnexpectedEnd()\n }\n\n function parseRootEnd(): boolean {\n parseMarkdownCodeBlock(['```', '```]', '```}'])\n\n const parsedComma = parseCharacter(',')\n parseWhitespaceAndSkipComments()\n\n if (\n isStartOfValue(input.charAt(i)) &&\n (output.endsWithIgnoringWhitespace(',') || output.endsWithIgnoringWhitespace('\\n'))\n ) {\n // start of a new value after end of the root level object: looks like\n // newline delimited JSON -> turn into a root level array\n if (!parsedComma) {\n // repair missing comma\n output.insertBeforeLastWhitespace(',')\n }\n\n output.unshift('[\\n')\n\n return stack.push(StackType.ndJson, Caret.beforeValue)\n }\n\n if (parsedComma) {\n // repair: remove trailing comma\n output.stripLastOccurrence(',')\n\n return stack.update(Caret.afterValue)\n }\n\n // repair redundant end braces and brackets\n while (input.charAt(i) === '}' || input.charAt(i) === ']') {\n i++\n parseWhitespaceAndSkipComments()\n }\n\n if (!input.isEnd(i)) {\n throwUnexpectedCharacter()\n }\n\n return false\n }\n\n function parseWhitespaceAndSkipComments(skipNewline = true): boolean {\n const start = i\n\n let changed = parseWhitespace(skipNewline)\n do {\n changed = parseComment()\n if (changed) {\n changed = parseWhitespace(skipNewline)\n }\n } while (changed)\n\n return i > start\n }\n\n function parseWhitespace(skipNewline: boolean): boolean {\n const _isWhiteSpace = skipNewline ? isWhitespace : isWhitespaceExceptNewline\n let whitespace = ''\n\n while (true) {\n if (_isWhiteSpace(input, i)) {\n whitespace += input.charAt(i)\n i++\n } else if (isSpecialWhitespace(input, i)) {\n // repair special whitespace\n whitespace += ' '\n i++\n } else {\n break\n }\n }\n\n if (whitespace.length > 0) {\n output.push(whitespace)\n return true\n }\n\n return false\n }\n\n function parseComment(): boolean {\n // find a block comment '/* ... */'\n if (input.charAt(i) === '/' && input.charAt(i + 1) === '*') {\n // repair block comment by skipping it\n while (!input.isEnd(i) && !atEndOfBlockComment(i)) {\n i++\n }\n i += 2\n\n return true\n }\n\n // find a line comment '// ...'\n if (input.charAt(i) === '/' && input.charAt(i + 1) === '/') {\n // repair line comment by skipping it\n while (!input.isEnd(i) && input.charAt(i) !== '\\n') {\n i++\n }\n\n return true\n }\n\n return false\n }\n\n function parseMarkdownCodeBlock(blocks: string[]): boolean {\n // find and skip over a Markdown fenced code block:\n // ``` ... ```\n // or\n // ```json ... ```\n if (skipMarkdownCodeBlock(blocks)) {\n if (isFunctionNameCharStart(input.charAt(i))) {\n // strip the optional language specifier like \"json\"\n while (!input.isEnd(i) && isFunctionNameChar(input.charAt(i))) {\n i++\n }\n }\n\n parseWhitespaceAndSkipComments()\n\n return true\n }\n\n return false\n }\n\n function skipMarkdownCodeBlock(blocks: string[]): boolean {\n for (const block of blocks) {\n const end = i + block.length\n if (input.substring(i, end) === block) {\n i = end\n return true\n }\n }\n\n return false\n }\n\n function parseCharacter(char: string): boolean {\n if (input.charAt(i) === char) {\n output.push(input.charAt(i))\n i++\n return true\n }\n\n return false\n }\n\n function skipCharacter(char: string): boolean {\n if (input.charAt(i) === char) {\n i++\n return true\n }\n\n return false\n }\n\n function skipEscapeCharacter(): boolean {\n return skipCharacter('\\\\')\n }\n\n /**\n * Skip ellipsis like \"[1,2,3,...]\" or \"[1,2,3,...,9]\" or \"[...,7,8,9]\"\n * or a similar construct in objects.\n */\n function skipEllipsis(): boolean {\n parseWhitespaceAndSkipComments()\n\n if (input.charAt(i) === '.' && input.charAt(i + 1) === '.' && input.charAt(i + 2) === '.') {\n // repair: remove the ellipsis (three dots) and optionally a comma\n i += 3\n parseWhitespaceAndSkipComments()\n skipCharacter(',')\n\n return true\n }\n\n return false\n }\n\n /**\n * Parse a string enclosed by double quotes \"...\". Can contain escaped quotes\n * Repair strings enclosed in single quotes or special quotes\n * Repair an escaped string\n *\n * The function can run in two stages:\n * - First, it assumes the string has a valid end quote\n * - If it turns out that the string does not have a valid end quote followed\n * by a delimiter (which should be the case), the function runs again in a\n * more conservative way, stopping the string at the first next delimiter\n * and fixing the string by inserting a quote there, or stopping at a\n * stop index detected in the first iteration.\n */\n function parseString(stopAtDelimiter = false, stopAtIndex = -1): boolean {\n let skipEscapeChars = input.charAt(i) === '\\\\'\n if (skipEscapeChars) {\n // repair: remove the first escape character\n i++\n skipEscapeChars = true\n }\n\n if (isQuote(input.charAt(i))) {\n // double quotes are correct JSON,\n // single quotes come from JavaScript for example, we assume it will have a correct single end quote too\n // otherwise, we will match any double-quote-like start with a double-quote-like end,\n // or any single-quote-like start with a single-quote-like end\n const isEndQuote = isDoubleQuote(input.charAt(i))\n ? isDoubleQuote\n : isSingleQuote(input.charAt(i))\n ? isSingleQuote\n : isSingleQuoteLike(input.charAt(i))\n ? isSingleQuoteLike\n : isDoubleQuoteLike\n\n const iBefore = i\n const oBefore = output.length()\n\n output.push('\"')\n i++\n\n while (true) {\n if (input.isEnd(i)) {\n // end of text, we have a missing quote somewhere\n\n const iPrev = prevNonWhitespaceIndex(i - 1)\n if (!stopAtDelimiter && isDelimiter(input.charAt(iPrev))) {\n // if the text ends with a delimiter, like [\"hello],\n // so the missing end quote should be inserted before this delimiter\n // retry parsing the string, stopping at the first next delimiter\n i = iBefore\n output.remove(oBefore)\n\n return parseString(true)\n }\n\n // repair missing quote\n output.insertBeforeLastWhitespace('\"')\n\n return stack.update(Caret.afterValue)\n }\n\n if (i === stopAtIndex) {\n // use the stop index detected in the first iteration, and repair end quote\n output.insertBeforeLastWhitespace('\"')\n\n return stack.update(Caret.afterValue)\n }\n\n if (isEndQuote(input.charAt(i))) {\n // end quote\n // let us check what is before and after the quote to verify whether this is a legit end quote\n const iQuote = i\n const oQuote = output.length()\n output.push('\"')\n i++\n\n parseWhitespaceAndSkipComments(false)\n\n if (\n stopAtDelimiter ||\n input.isEnd(i) ||\n isDelimiter(input.charAt(i)) ||\n isQuote(input.charAt(i)) ||\n isDigit(input.charAt(i))\n ) {\n // The quote is followed by the end of the text, a delimiter, or a next value\n // so the quote is indeed the end of the string\n parseConcatenatedString()\n\n return stack.update(Caret.afterValue)\n }\n\n const iPrevChar = prevNonWhitespaceIndex(iQuote - 1)\n const prevChar = input.charAt(iPrevChar)\n\n if (prevChar === ',') {\n // A comma followed by a quote, like '{\"a\":\"b,c,\"d\":\"e\"}'.\n // We assume that the quote is a start quote, and that the end quote\n // should have been located right before the comma but is missing.\n i = iBefore\n output.remove(oBefore)\n\n return parseString(false, iPrevChar)\n }\n\n if (isDelimiter(prevChar)) {\n // This is not the right end quote: it is preceded by a delimiter,\n // and NOT followed by a delimiter. So, there is an end quote missing\n // parse the string again and then stop at the first next delimiter\n i = iBefore\n output.remove(oBefore)\n\n return parseString(true)\n }\n\n // revert to right after the quote but before any whitespace, and continue parsing the string\n output.remove(oQuote + 1)\n i = iQuote + 1\n\n // repair unescaped quote\n output.insertAt(oQuote, '\\\\')\n } else if (stopAtDelimiter && isUnquotedStringDelimiter(input.charAt(i))) {\n // we're in the mode to stop the string at the first delimiter\n // because there is an end quote missing\n\n // test start of an url like \"https://...\" (this would be parsed as a comment)\n if (\n input.charAt(i - 1) === ':' &&\n regexUrlStart.test(input.substring(iBefore + 1, i + 2))\n ) {\n while (!input.isEnd(i) && regexUrlChar.test(input.charAt(i))) {\n output.push(input.charAt(i))\n i++\n }\n }\n\n // repair missing quote\n output.insertBeforeLastWhitespace('\"')\n\n parseConcatenatedString()\n\n return stack.update(Caret.afterValue)\n } else if (input.charAt(i) === '\\\\') {\n // handle escaped content like \\n or \\u2605\n const char = input.charAt(i + 1)\n const escapeChar = escapeCharacters[char]\n if (escapeChar !== undefined) {\n output.push(input.substring(i, i + 2))\n i += 2\n } else if (char === 'u') {\n let j = 2\n while (j < 6 && isHex(input.charAt(i + j))) {\n j++\n }\n\n if (j === 6) {\n output.push(input.substring(i, i + 6))\n i += 6\n } else if (input.isEnd(i + j)) {\n // repair invalid or truncated unicode char at the end of the text\n // by removing the unicode char and ending the string here\n i += j\n } else {\n throwInvalidUnicodeCharacter()\n }\n } else {\n // repair invalid escape character: remove it\n output.push(char)\n i += 2\n }\n } else {\n // handle regular characters\n const char = input.charAt(i)\n\n if (char === '\"' && input.charAt(i - 1) !== '\\\\') {\n // repair unescaped double quote\n output.push(`\\\\${char}`)\n i++\n } else if (isControlCharacter(char)) {\n // unescaped control character\n output.push(controlCharacters[char])\n i++\n } else {\n if (!isValidStringCharacter(char)) {\n throwInvalidCharacter(char)\n }\n output.push(char)\n i++\n }\n }\n\n if (skipEscapeChars) {\n // repair: skipped escape character (nothing to do)\n skipEscapeCharacter()\n }\n }\n }\n\n return false\n }\n\n /**\n * Repair concatenated strings like \"hello\" + \"world\", change this into \"helloworld\"\n */\n function parseConcatenatedString(): boolean {\n let parsed = false\n\n parseWhitespaceAndSkipComments()\n while (input.charAt(i) === '+') {\n parsed = true\n i++\n parseWhitespaceAndSkipComments()\n\n // repair: remove the end quote of the first string\n output.stripLastOccurrence('\"', true)\n const start = output.length()\n const parsedStr = parseString()\n if (parsedStr) {\n // repair: remove the start quote of the second string\n output.remove(start, start + 1)\n } else {\n // repair: remove the + because it is not followed by a string\n output.insertBeforeLastWhitespace('\"')\n }\n }\n\n return parsed\n }\n\n /**\n * Parse a number like 2.4 or 2.4e6\n */\n function parseNumber(): boolean {\n const start = i\n if (input.charAt(i) === '-') {\n i++\n if (atEndOfNumber()) {\n repairNumberEndingWithNumericSymbol(start)\n return stack.update(Caret.afterValue)\n }\n if (!isDigit(input.charAt(i))) {\n i = start\n return false\n }\n }\n\n // Note that in JSON leading zeros like \"00789\" are not allowed.\n // We will allow all leading zeros here though and at the end of parseNumber\n // check against trailing zeros and repair that if needed.\n // Leading zeros can have meaning, so we should not clear them.\n while (isDigit(input.charAt(i))) {\n i++\n }\n\n if (input.charAt(i) === '.') {\n i++\n if (atEndOfNumber()) {\n repairNumberEndingWithNumericSymbol(start)\n return stack.update(Caret.afterValue)\n }\n if (!isDigit(input.charAt(i))) {\n i = start\n return false\n }\n while (isDigit(input.charAt(i))) {\n i++\n }\n }\n\n if (input.charAt(i) === 'e' || input.charAt(i) === 'E') {\n i++\n if (input.charAt(i) === '-' || input.charAt(i) === '+') {\n i++\n }\n if (atEndOfNumber()) {\n repairNumberEndingWithNumericSymbol(start)\n return stack.update(Caret.afterValue)\n }\n if (!isDigit(input.charAt(i))) {\n i = start\n return false\n }\n while (isDigit(input.charAt(i))) {\n i++\n }\n }\n\n // if we're not at the end of the number by this point, allow this to be parsed as another type\n if (!atEndOfNumber()) {\n i = start\n return false\n }\n\n if (i > start) {\n // repair a number with leading zeros like \"00789\"\n const num = input.substring(start, i)\n const hasInvalidLeadingZero = /^0\\d/.test(num)\n\n output.push(hasInvalidLeadingZero ? `\"${num}\"` : num)\n return stack.update(Caret.afterValue)\n }\n\n return false\n }\n\n /**\n * Parse keywords true, false, null\n * Repair Python keywords True, False, None\n */\n function parseKeywords(): boolean {\n return (\n parseKeyword('true', 'true') ||\n parseKeyword('false', 'false') ||\n parseKeyword('null', 'null') ||\n // repair Python keywords True, False, None\n parseKeyword('True', 'true') ||\n parseKeyword('False', 'false') ||\n parseKeyword('None', 'null')\n )\n }\n\n function parseKeyword(name: string, value: string): boolean {\n if (input.substring(i, i + name.length) === name) {\n output.push(value)\n i += name.length\n return stack.update(Caret.afterValue)\n }\n\n return false\n }\n\n function parseUnquotedKey(): boolean {\n let end = findNextDelimiter(true, i)\n\n if (end !== null) {\n // first, go back to prevent getting trailing whitespaces in the string\n while (isWhitespace(input, end - 1) && end > i) {\n end--\n }\n\n const symbol = input.substring(i, end)\n output.push(JSON.stringify(symbol))\n i = end\n\n if (input.charAt(i) === '\"') {\n // we had a missing start quote, but now we encountered the end quote, so we can skip that one\n i++\n }\n\n return stack.update(Caret.afterValue) // we do not have a state Caret.afterKey, therefore we use afterValue here\n }\n\n return false\n }\n\n function findNextDelimiter(isKey: boolean, start: number): number | null {\n // note that the symbol can end with whitespaces: we stop at the next delimiter\n // also, note that we allow strings to contain a slash / in order to support repairing regular expressions\n let j = start\n while (\n !input.isEnd(j) &&\n !isUnquotedStringDelimiter(input.charAt(j)) &&\n !isQuote(input.charAt(j)) &&\n (!isKey || input.charAt(j) !== ':')\n ) {\n j++\n }\n\n return j > i ? j : null\n }\n\n function prevNonWhitespaceIndex(start: number): number {\n let prev = start\n\n while (prev > 0 && isWhitespace(input, prev)) {\n prev--\n }\n\n return prev\n }\n\n function atEndOfNumber() {\n return input.isEnd(i) || isDelimiter(input.charAt(i)) || isWhitespace(input, i)\n }\n\n function repairNumberEndingWithNumericSymbol(start: number) {\n // repair numbers cut off at the end\n // this will only be called when we end after a '.', '-', or 'e' and does not\n // change the number more than it needs to make it valid JSON\n output.push(`${input.substring(start, i)}0`)\n }\n\n function throwInvalidCharacter(char: string) {\n throw new JSONRepairError(`Invalid character ${JSON.stringify(char)}`, i)\n }\n\n function throwUnexpectedCharacter() {\n throw new JSONRepairError(`Unexpected character ${JSON.stringify(input.charAt(i))}`, i)\n }\n\n function throwUnexpectedEnd() {\n throw new JSONRepairError('Unexpected end of json string', i)\n }\n\n function throwObjectKeyExpected() {\n throw new JSONRepairError('Object key expected', i)\n }\n\n function throwColonExpected() {\n throw new JSONRepairError('Colon expected', i)\n }\n\n function throwInvalidUnicodeCharacter() {\n const chars = input.substring(i, i + 6)\n throw new JSONRepairError(`Invalid unicode character \"${chars}\"`, i)\n }\n\n function atEndOfBlockComment(i: number) {\n return input.charAt(i) === '*' && input.charAt(i + 1) === '/'\n }\n\n return {\n transform,\n flush\n }\n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C;EAEA,SAASkI,qBAAqBA,CAAC9B,IAAY,EAAE;IAC3C,MAAM,IAAI0C,gCAAe,CAAC,qBAAqB7E,IAAI,CAACC,SAAS,CAACkC,IAAI,CAAC,EAAE,EAAEpG,CAAC,CAAC;EAC3E;EAEA,SAASyE,wBAAwBA,CAAA,EAAG;IAClC,MAAM,IAAIqE,gCAAe,CAAC,wBAAwB7E,IAAI,CAACC,SAAS,CAACvE,KAAK,CAAC2D,MAAM,CAACtD,CAAC,CAAC,CAAC,EAAE,EAAEA,CAAC,CAAC;EACzF;EAEA,SAASwE,kBAAkBA,CAAA,EAAG;IAC5B,MAAM,IAAIsE,gCAAe,CAAC,+BAA+B,EAAE9I,CAAC,CAAC;EAC/D;EAEA,SAASsE,sBAAsBA,CAAA,EAAG;IAChC,MAAM,IAAIwE,gCAAe,CAAC,qBAAqB,EAAE9I,CAAC,CAAC;EACrD;EAEA,SAAS+E,kBAAkBA,CAAA,EAAG;IAC5B,MAAM,IAAI+D,gCAAe,CAAC,gBAAgB,EAAE9I,CAAC,CAAC;EAChD;EAEA,SAAS+H,4BAA4BA,CAAA,EAAG;IACtC,MAAMgB,KAAK,GAAGpJ,KAAK,CAACmE,SAAS,CAAC9D,CAAC,EAAEA,CAAC,GAAG,CAAC,CAAC;IACvC,MAAM,IAAI8I,gCAAe,CAAC,8BAA8BC,KAAK,GAAG,EAAE/I,CAAC,CAAC;EACtE;EAEA,SAAS+F,mBAAmBA,CAAC/F,CAAS,EAAE;IACtC,OAAOL,KAAK,CAAC2D,MAAM,CAACtD,CAAC,CAAC,KAAK,GAAG,IAAIL,KAAK,CAAC2D,MAAM,CAACtD,CAAC,GAAG,CAAC,CAAC,KAAK,GAAG;EAC/D;EAEA,OAAO;IACLM,SAAS;IACTD;EACF,CAAC;AACH","ignoreList":[]} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/streaming/stack.js b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/streaming/stack.js new file mode 100644 index 0000000000000000000000000000000000000000..7170df85d756b2f92cefa73eb1f5db05ce7c7559 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/streaming/stack.js @@ -0,0 +1,51 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.StackType = exports.Caret = void 0; +exports.createStack = createStack; +let Caret = exports.Caret = /*#__PURE__*/function (Caret) { + Caret["beforeValue"] = "beforeValue"; + Caret["afterValue"] = "afterValue"; + Caret["beforeKey"] = "beforeKey"; + return Caret; +}({}); +let StackType = exports.StackType = /*#__PURE__*/function (StackType) { + StackType["root"] = "root"; + StackType["object"] = "object"; + StackType["array"] = "array"; + StackType["ndJson"] = "ndJson"; + StackType["functionCall"] = "dataType"; + return StackType; +}({}); +function createStack() { + const stack = [StackType.root]; + let caret = Caret.beforeValue; + return { + get type() { + return last(stack); + }, + get caret() { + return caret; + }, + pop() { + stack.pop(); + caret = Caret.afterValue; + return true; + }, + push(type, newCaret) { + stack.push(type); + caret = newCaret; + return true; + }, + update(newCaret) { + caret = newCaret; + return true; + } + }; +} +function last(array) { + return array[array.length - 1]; +} +//# sourceMappingURL=stack.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/streaming/stack.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/streaming/stack.js.map new file mode 100644 index 0000000000000000000000000000000000000000..6952c4a7c4b8f25f3448290b5b25ad655387c8f5 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/streaming/stack.js.map @@ -0,0 +1 @@ +{"version":3,"file":"stack.js","names":["Caret","exports","StackType","createStack","stack","root","caret","beforeValue","type","last","pop","afterValue","push","newCaret","update","array","length"],"sources":["../../../src/streaming/stack.ts"],"sourcesContent":["export enum Caret {\n beforeValue = 'beforeValue',\n afterValue = 'afterValue',\n beforeKey = 'beforeKey'\n}\n\nexport enum StackType {\n root = 'root',\n object = 'object',\n array = 'array',\n ndJson = 'ndJson',\n functionCall = 'dataType'\n}\n\nexport function createStack() {\n const stack: StackType[] = [StackType.root]\n let caret = Caret.beforeValue\n\n return {\n get type() {\n return last(stack)\n },\n\n get caret() {\n return caret\n },\n\n pop(): true {\n stack.pop()\n caret = Caret.afterValue\n\n return true\n },\n\n push(type: StackType, newCaret: Caret): true {\n stack.push(type)\n caret = newCaret\n\n return true\n },\n\n update(newCaret: Caret): true {\n caret = newCaret\n\n return true\n }\n }\n}\n\nfunction last(array: T[]): T | undefined {\n return array[array.length - 1]\n}\n"],"mappings":";;;;;;;IAAYA,KAAK,GAAAC,OAAA,CAAAD,KAAA,0BAALA,KAAK;EAALA,KAAK;EAALA,KAAK;EAALA,KAAK;EAAA,OAALA,KAAK;AAAA;AAAA,IAMLE,SAAS,GAAAD,OAAA,CAAAC,SAAA,0BAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAAA,OAATA,SAAS;AAAA;AAQd,SAASC,WAAWA,CAAA,EAAG;EAC5B,MAAMC,KAAkB,GAAG,CAACF,SAAS,CAACG,IAAI,CAAC;EAC3C,IAAIC,KAAK,GAAGN,KAAK,CAACO,WAAW;EAE7B,OAAO;IACL,IAAIC,IAAIA,CAAA,EAAG;MACT,OAAOC,IAAI,CAACL,KAAK,CAAC;IACpB,CAAC;IAED,IAAIE,KAAKA,CAAA,EAAG;MACV,OAAOA,KAAK;IACd,CAAC;IAEDI,GAAGA,CAAA,EAAS;MACVN,KAAK,CAACM,GAAG,CAAC,CAAC;MACXJ,KAAK,GAAGN,KAAK,CAACW,UAAU;MAExB,OAAO,IAAI;IACb,CAAC;IAEDC,IAAIA,CAACJ,IAAe,EAAEK,QAAe,EAAQ;MAC3CT,KAAK,CAACQ,IAAI,CAACJ,IAAI,CAAC;MAChBF,KAAK,GAAGO,QAAQ;MAEhB,OAAO,IAAI;IACb,CAAC;IAEDC,MAAMA,CAACD,QAAe,EAAQ;MAC5BP,KAAK,GAAGO,QAAQ;MAEhB,OAAO,IAAI;IACb;EACF,CAAC;AACH;AAEA,SAASJ,IAAIA,CAAIM,KAAU,EAAiB;EAC1C,OAAOA,KAAK,CAACA,KAAK,CAACC,MAAM,GAAG,CAAC,CAAC;AAChC","ignoreList":[]} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/streaming/stream.js b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/streaming/stream.js new file mode 100644 index 0000000000000000000000000000000000000000..24949216e4d8b73d0c97ad7dfe8fba019d31b7c5 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/streaming/stream.js @@ -0,0 +1,37 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.jsonrepairTransform = jsonrepairTransform; +var _nodeStream = require("node:stream"); +var _core = require("./core.js"); +function jsonrepairTransform(options) { + const repair = (0, _core.jsonrepairCore)({ + onData: chunk => transform.push(chunk), + bufferSize: options?.bufferSize, + chunkSize: options?.chunkSize + }); + const transform = new _nodeStream.Transform({ + transform(chunk, _encoding, callback) { + try { + repair.transform(chunk.toString()); + } catch (err) { + this.emit('error', err); + } finally { + callback(); + } + }, + flush(callback) { + try { + repair.flush(); + } catch (err) { + this.emit('error', err); + } finally { + callback(); + } + } + }); + return transform; +} +//# sourceMappingURL=stream.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/streaming/stream.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/streaming/stream.js.map new file mode 100644 index 0000000000000000000000000000000000000000..2d44c7a1796948caa011635d53e07c0e729f57a5 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/streaming/stream.js.map @@ -0,0 +1 @@ +{"version":3,"file":"stream.js","names":["_nodeStream","require","_core","jsonrepairTransform","options","repair","jsonrepairCore","onData","chunk","transform","push","bufferSize","chunkSize","Transform","_encoding","callback","toString","err","emit","flush"],"sources":["../../../src/streaming/stream.ts"],"sourcesContent":["import { Transform } from 'node:stream'\nimport { jsonrepairCore } from './core.js'\n\nexport interface JsonRepairTransformOptions {\n chunkSize?: number\n bufferSize?: number\n}\n\nexport function jsonrepairTransform(options?: JsonRepairTransformOptions): Transform {\n const repair = jsonrepairCore({\n onData: (chunk) => transform.push(chunk),\n bufferSize: options?.bufferSize,\n chunkSize: options?.chunkSize\n })\n\n const transform = new Transform({\n transform(chunk, _encoding, callback) {\n try {\n repair.transform(chunk.toString())\n } catch (err) {\n this.emit('error', err)\n } finally {\n callback()\n }\n },\n\n flush(callback) {\n try {\n repair.flush()\n } catch (err) {\n this.emit('error', err)\n } finally {\n callback()\n }\n }\n })\n\n return transform\n}\n"],"mappings":";;;;;;AAAA,IAAAA,WAAA,GAAAC,OAAA;AACA,IAAAC,KAAA,GAAAD,OAAA;AAOO,SAASE,mBAAmBA,CAACC,OAAoC,EAAa;EACnF,MAAMC,MAAM,GAAG,IAAAC,oBAAc,EAAC;IAC5BC,MAAM,EAAGC,KAAK,IAAKC,SAAS,CAACC,IAAI,CAACF,KAAK,CAAC;IACxCG,UAAU,EAAEP,OAAO,EAAEO,UAAU;IAC/BC,SAAS,EAAER,OAAO,EAAEQ;EACtB,CAAC,CAAC;EAEF,MAAMH,SAAS,GAAG,IAAII,qBAAS,CAAC;IAC9BJ,SAASA,CAACD,KAAK,EAAEM,SAAS,EAAEC,QAAQ,EAAE;MACpC,IAAI;QACFV,MAAM,CAACI,SAAS,CAACD,KAAK,CAACQ,QAAQ,CAAC,CAAC,CAAC;MACpC,CAAC,CAAC,OAAOC,GAAG,EAAE;QACZ,IAAI,CAACC,IAAI,CAAC,OAAO,EAAED,GAAG,CAAC;MACzB,CAAC,SAAS;QACRF,QAAQ,CAAC,CAAC;MACZ;IACF,CAAC;IAEDI,KAAKA,CAACJ,QAAQ,EAAE;MACd,IAAI;QACFV,MAAM,CAACc,KAAK,CAAC,CAAC;MAChB,CAAC,CAAC,OAAOF,GAAG,EAAE;QACZ,IAAI,CAACC,IAAI,CAAC,OAAO,EAAED,GAAG,CAAC;MACzB,CAAC,SAAS;QACRF,QAAQ,CAAC,CAAC;MACZ;IACF;EACF,CAAC,CAAC;EAEF,OAAON,SAAS;AAClB","ignoreList":[]} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/utils/JSONRepairError.js b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/utils/JSONRepairError.js new file mode 100644 index 0000000000000000000000000000000000000000..eb0fd80504d1f76fda3263840a078a7e67efd96c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/utils/JSONRepairError.js @@ -0,0 +1,14 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.JSONRepairError = void 0; +class JSONRepairError extends Error { + constructor(message, position) { + super(`${message} at position ${position}`); + this.position = position; + } +} +exports.JSONRepairError = JSONRepairError; +//# sourceMappingURL=JSONRepairError.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/utils/JSONRepairError.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/utils/JSONRepairError.js.map new file mode 100644 index 0000000000000000000000000000000000000000..107e08c2cbe7500ed15cc57f806dede61ebd5c30 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/utils/JSONRepairError.js.map @@ -0,0 +1 @@ +{"version":3,"file":"JSONRepairError.js","names":["JSONRepairError","Error","constructor","message","position","exports"],"sources":["../../../src/utils/JSONRepairError.ts"],"sourcesContent":["export class JSONRepairError extends Error {\n position: number\n\n constructor(message: string, position: number) {\n super(`${message} at position ${position}`)\n\n this.position = position\n }\n}\n"],"mappings":";;;;;;AAAO,MAAMA,eAAe,SAASC,KAAK,CAAC;EAGzCC,WAAWA,CAACC,OAAe,EAAEC,QAAgB,EAAE;IAC7C,KAAK,CAAC,GAAGD,OAAO,gBAAgBC,QAAQ,EAAE,CAAC;IAE3C,IAAI,CAACA,QAAQ,GAAGA,QAAQ;EAC1B;AACF;AAACC,OAAA,CAAAL,eAAA,GAAAA,eAAA","ignoreList":[]} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/utils/stringUtils.js b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/utils/stringUtils.js new file mode 100644 index 0000000000000000000000000000000000000000..22c0a5244e18f93dbb415098c2a3bb406ba9fb33 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/utils/stringUtils.js @@ -0,0 +1,174 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.endsWithCommaOrNewline = endsWithCommaOrNewline; +exports.insertBeforeLastWhitespace = insertBeforeLastWhitespace; +exports.isControlCharacter = isControlCharacter; +exports.isDelimiter = isDelimiter; +exports.isDigit = isDigit; +exports.isDoubleQuote = isDoubleQuote; +exports.isDoubleQuoteLike = isDoubleQuoteLike; +exports.isFunctionNameChar = isFunctionNameChar; +exports.isFunctionNameCharStart = isFunctionNameCharStart; +exports.isHex = isHex; +exports.isQuote = isQuote; +exports.isSingleQuote = isSingleQuote; +exports.isSingleQuoteLike = isSingleQuoteLike; +exports.isSpecialWhitespace = isSpecialWhitespace; +exports.isStartOfValue = isStartOfValue; +exports.isUnquotedStringDelimiter = isUnquotedStringDelimiter; +exports.isValidStringCharacter = isValidStringCharacter; +exports.isWhitespace = isWhitespace; +exports.isWhitespaceExceptNewline = isWhitespaceExceptNewline; +exports.regexUrlStart = exports.regexUrlChar = void 0; +exports.removeAtIndex = removeAtIndex; +exports.stripLastOccurrence = stripLastOccurrence; +const codeSpace = 0x20; // " " +const codeNewline = 0xa; // "\n" +const codeTab = 0x9; // "\t" +const codeReturn = 0xd; // "\r" +const codeNonBreakingSpace = 0xa0; +const codeEnQuad = 0x2000; +const codeHairSpace = 0x200a; +const codeNarrowNoBreakSpace = 0x202f; +const codeMediumMathematicalSpace = 0x205f; +const codeIdeographicSpace = 0x3000; +function isHex(char) { + return /^[0-9A-Fa-f]$/.test(char); +} +function isDigit(char) { + return char >= '0' && char <= '9'; +} +function isValidStringCharacter(char) { + // note that the valid range is between \u{0020} and \u{10ffff}, + // but in JavaScript it is not possible to create a code point larger than + // \u{10ffff}, so there is no need to test for that here. + return char >= '\u0020'; +} +function isDelimiter(char) { + return ',:[]/{}()\n+'.includes(char); +} +function isFunctionNameCharStart(char) { + return char >= 'a' && char <= 'z' || char >= 'A' && char <= 'Z' || char === '_' || char === '$'; +} +function isFunctionNameChar(char) { + return char >= 'a' && char <= 'z' || char >= 'A' && char <= 'Z' || char === '_' || char === '$' || char >= '0' && char <= '9'; +} + +// matches "https://" and other schemas +const regexUrlStart = exports.regexUrlStart = /^(http|https|ftp|mailto|file|data|irc):\/\/$/; + +// matches all valid URL characters EXCEPT "[", "]", and ",", since that are important JSON delimiters +const regexUrlChar = exports.regexUrlChar = /^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/; +function isUnquotedStringDelimiter(char) { + return ',[]/{}\n+'.includes(char); +} +function isStartOfValue(char) { + return isQuote(char) || regexStartOfValue.test(char); +} + +// alpha, number, minus, or opening bracket or brace +const regexStartOfValue = /^[[{\w-]$/; +function isControlCharacter(char) { + return char === '\n' || char === '\r' || char === '\t' || char === '\b' || char === '\f'; +} +/** + * Check if the given character is a whitespace character like space, tab, or + * newline + */ +function isWhitespace(text, index) { + const code = text.charCodeAt(index); + return code === codeSpace || code === codeNewline || code === codeTab || code === codeReturn; +} + +/** + * Check if the given character is a whitespace character like space or tab, + * but NOT a newline + */ +function isWhitespaceExceptNewline(text, index) { + const code = text.charCodeAt(index); + return code === codeSpace || code === codeTab || code === codeReturn; +} + +/** + * Check if the given character is a special whitespace character, some + * unicode variant + */ +function isSpecialWhitespace(text, index) { + const code = text.charCodeAt(index); + return code === codeNonBreakingSpace || code >= codeEnQuad && code <= codeHairSpace || code === codeNarrowNoBreakSpace || code === codeMediumMathematicalSpace || code === codeIdeographicSpace; +} + +/** + * Test whether the given character is a quote or double quote character. + * Also tests for special variants of quotes. + */ +function isQuote(char) { + // the first check double quotes, since that occurs most often + return isDoubleQuoteLike(char) || isSingleQuoteLike(char); +} + +/** + * Test whether the given character is a double quote character. + * Also tests for special variants of double quotes. + */ +function isDoubleQuoteLike(char) { + return char === '"' || char === '\u201c' || char === '\u201d'; +} + +/** + * Test whether the given character is a double quote character. + * Does NOT test for special variants of double quotes. + */ +function isDoubleQuote(char) { + return char === '"'; +} + +/** + * Test whether the given character is a single quote character. + * Also tests for special variants of single quotes. + */ +function isSingleQuoteLike(char) { + return char === "'" || char === '\u2018' || char === '\u2019' || char === '\u0060' || char === '\u00b4'; +} + +/** + * Test whether the given character is a single quote character. + * Does NOT test for special variants of single quotes. + */ +function isSingleQuote(char) { + return char === "'"; +} + +/** + * Strip last occurrence of textToStrip from text + */ +function stripLastOccurrence(text, textToStrip) { + let stripRemainingText = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + const index = text.lastIndexOf(textToStrip); + return index !== -1 ? text.substring(0, index) + (stripRemainingText ? '' : text.substring(index + 1)) : text; +} +function insertBeforeLastWhitespace(text, textToInsert) { + let index = text.length; + if (!isWhitespace(text, index - 1)) { + // no trailing whitespaces + return text + textToInsert; + } + while (isWhitespace(text, index - 1)) { + index--; + } + return text.substring(0, index) + textToInsert + text.substring(index); +} +function removeAtIndex(text, start, count) { + return text.substring(0, start) + text.substring(start + count); +} + +/** + * Test whether a string ends with a newline or comma character and optional whitespace + */ +function endsWithCommaOrNewline(text) { + return /[,\n][ \t\r]*$/.test(text); +} +//# sourceMappingURL=stringUtils.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/utils/stringUtils.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/utils/stringUtils.js.map new file mode 100644 index 0000000000000000000000000000000000000000..5a4edde289a7810b4bae21ba978d5cf89004c485 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/cjs/utils/stringUtils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"stringUtils.js","names":["codeSpace","codeNewline","codeTab","codeReturn","codeNonBreakingSpace","codeEnQuad","codeHairSpace","codeNarrowNoBreakSpace","codeMediumMathematicalSpace","codeIdeographicSpace","isHex","char","test","isDigit","isValidStringCharacter","isDelimiter","includes","isFunctionNameCharStart","isFunctionNameChar","regexUrlStart","exports","regexUrlChar","isUnquotedStringDelimiter","isStartOfValue","isQuote","regexStartOfValue","isControlCharacter","isWhitespace","text","index","code","charCodeAt","isWhitespaceExceptNewline","isSpecialWhitespace","isDoubleQuoteLike","isSingleQuoteLike","isDoubleQuote","isSingleQuote","stripLastOccurrence","textToStrip","stripRemainingText","arguments","length","undefined","lastIndexOf","substring","insertBeforeLastWhitespace","textToInsert","removeAtIndex","start","count","endsWithCommaOrNewline"],"sources":["../../../src/utils/stringUtils.ts"],"sourcesContent":["const codeSpace = 0x20 // \" \"\nconst codeNewline = 0xa // \"\\n\"\nconst codeTab = 0x9 // \"\\t\"\nconst codeReturn = 0xd // \"\\r\"\nconst codeNonBreakingSpace = 0xa0\nconst codeEnQuad = 0x2000\nconst codeHairSpace = 0x200a\nconst codeNarrowNoBreakSpace = 0x202f\nconst codeMediumMathematicalSpace = 0x205f\nconst codeIdeographicSpace = 0x3000\n\nexport function isHex(char: string): boolean {\n return /^[0-9A-Fa-f]$/.test(char)\n}\n\nexport function isDigit(char: string): boolean {\n return char >= '0' && char <= '9'\n}\n\nexport function isValidStringCharacter(char: string): boolean {\n // note that the valid range is between \\u{0020} and \\u{10ffff},\n // but in JavaScript it is not possible to create a code point larger than\n // \\u{10ffff}, so there is no need to test for that here.\n return char >= '\\u0020'\n}\n\nexport function isDelimiter(char: string): boolean {\n return ',:[]/{}()\\n+'.includes(char)\n}\n\nexport function isFunctionNameCharStart(char: string) {\n return (\n (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z') || char === '_' || char === '$'\n )\n}\n\nexport function isFunctionNameChar(char: string) {\n return (\n (char >= 'a' && char <= 'z') ||\n (char >= 'A' && char <= 'Z') ||\n char === '_' ||\n char === '$' ||\n (char >= '0' && char <= '9')\n )\n}\n\n// matches \"https://\" and other schemas\nexport const regexUrlStart = /^(http|https|ftp|mailto|file|data|irc):\\/\\/$/\n\n// matches all valid URL characters EXCEPT \"[\", \"]\", and \",\", since that are important JSON delimiters\nexport const regexUrlChar = /^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/\n\nexport function isUnquotedStringDelimiter(char: string): boolean {\n return ',[]/{}\\n+'.includes(char)\n}\n\nexport function isStartOfValue(char: string): boolean {\n return isQuote(char) || regexStartOfValue.test(char)\n}\n\n// alpha, number, minus, or opening bracket or brace\nconst regexStartOfValue = /^[[{\\w-]$/\n\nexport function isControlCharacter(char: string) {\n return char === '\\n' || char === '\\r' || char === '\\t' || char === '\\b' || char === '\\f'\n}\n\nexport interface Text {\n charCodeAt: (index: number) => number\n}\n\n/**\n * Check if the given character is a whitespace character like space, tab, or\n * newline\n */\nexport function isWhitespace(text: Text, index: number): boolean {\n const code = text.charCodeAt(index)\n\n return code === codeSpace || code === codeNewline || code === codeTab || code === codeReturn\n}\n\n/**\n * Check if the given character is a whitespace character like space or tab,\n * but NOT a newline\n */\nexport function isWhitespaceExceptNewline(text: Text, index: number): boolean {\n const code = text.charCodeAt(index)\n\n return code === codeSpace || code === codeTab || code === codeReturn\n}\n\n/**\n * Check if the given character is a special whitespace character, some\n * unicode variant\n */\nexport function isSpecialWhitespace(text: Text, index: number): boolean {\n const code = text.charCodeAt(index)\n\n return (\n code === codeNonBreakingSpace ||\n (code >= codeEnQuad && code <= codeHairSpace) ||\n code === codeNarrowNoBreakSpace ||\n code === codeMediumMathematicalSpace ||\n code === codeIdeographicSpace\n )\n}\n\n/**\n * Test whether the given character is a quote or double quote character.\n * Also tests for special variants of quotes.\n */\nexport function isQuote(char: string): boolean {\n // the first check double quotes, since that occurs most often\n return isDoubleQuoteLike(char) || isSingleQuoteLike(char)\n}\n\n/**\n * Test whether the given character is a double quote character.\n * Also tests for special variants of double quotes.\n */\nexport function isDoubleQuoteLike(char: string): boolean {\n return char === '\"' || char === '\\u201c' || char === '\\u201d'\n}\n\n/**\n * Test whether the given character is a double quote character.\n * Does NOT test for special variants of double quotes.\n */\nexport function isDoubleQuote(char: string): boolean {\n return char === '\"'\n}\n\n/**\n * Test whether the given character is a single quote character.\n * Also tests for special variants of single quotes.\n */\nexport function isSingleQuoteLike(char: string): boolean {\n return (\n char === \"'\" || char === '\\u2018' || char === '\\u2019' || char === '\\u0060' || char === '\\u00b4'\n )\n}\n\n/**\n * Test whether the given character is a single quote character.\n * Does NOT test for special variants of single quotes.\n */\nexport function isSingleQuote(char: string): boolean {\n return char === \"'\"\n}\n\n/**\n * Strip last occurrence of textToStrip from text\n */\nexport function stripLastOccurrence(\n text: string,\n textToStrip: string,\n stripRemainingText = false\n): string {\n const index = text.lastIndexOf(textToStrip)\n return index !== -1\n ? text.substring(0, index) + (stripRemainingText ? '' : text.substring(index + 1))\n : text\n}\n\nexport function insertBeforeLastWhitespace(text: string, textToInsert: string): string {\n let index = text.length\n\n if (!isWhitespace(text, index - 1)) {\n // no trailing whitespaces\n return text + textToInsert\n }\n\n while (isWhitespace(text, index - 1)) {\n index--\n }\n\n return text.substring(0, index) + textToInsert + text.substring(index)\n}\n\nexport function removeAtIndex(text: string, start: number, count: number) {\n return text.substring(0, start) + text.substring(start + count)\n}\n\n/**\n * Test whether a string ends with a newline or comma character and optional whitespace\n */\nexport function endsWithCommaOrNewline(text: string): boolean {\n return /[,\\n][ \\t\\r]*$/.test(text)\n}\n"],"mappings":";;;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AG,EAAE,GAAGZ,IAAI,CAACiB,SAAS,CAAChB,KAAK,GAAG,CAAC,CAAC,CAAC,GAChFD,IAAI;AACV;AAEO,SAASkB,0BAA0BA,CAAClB,IAAY,EAAEmB,YAAoB,EAAU;EACrF,IAAIlB,KAAK,GAAGD,IAAI,CAACc,MAAM;EAEvB,IAAI,CAACf,YAAY,CAACC,IAAI,EAAEC,KAAK,GAAG,CAAC,CAAC,EAAE;IAClC;IACA,OAAOD,IAAI,GAAGmB,YAAY;EAC5B;EAEA,OAAOpB,YAAY,CAACC,IAAI,EAAEC,KAAK,GAAG,CAAC,CAAC,EAAE;IACpCA,KAAK,EAAE;EACT;EAEA,OAAOD,IAAI,CAACiB,SAAS,CAAC,CAAC,EAAEhB,KAAK,CAAC,GAAGkB,YAAY,GAAGnB,IAAI,CAACiB,SAAS,CAAChB,KAAK,CAAC;AACxE;AAEO,SAASmB,aAAaA,CAACpB,IAAY,EAAEqB,KAAa,EAAEC,KAAa,EAAE;EACxE,OAAOtB,IAAI,CAACiB,SAAS,CAAC,CAAC,EAAEI,KAAK,CAAC,GAAGrB,IAAI,CAACiB,SAAS,CAACI,KAAK,GAAGC,KAAK,CAAC;AACjE;;AAEA;AACA;AACA;AACO,SAASC,sBAAsBA,CAACvB,IAAY,EAAW;EAC5D,OAAO,gBAAgB,CAAChB,IAAI,CAACgB,IAAI,CAAC;AACpC","ignoreList":[]} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/index.js new file mode 100644 index 0000000000000000000000000000000000000000..18e8dc22386cfc17829e07881ebda4d91b29159b --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/index.js @@ -0,0 +1,4 @@ +// Cross-platform, non-streaming JavaScript API +export { jsonrepair } from './regular/jsonrepair.js'; +export { JSONRepairError } from './utils/JSONRepairError.js'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/index.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..3f8eb817d131435555d78b9d9389a29ccf7ebb30 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["jsonrepair","JSONRepairError"],"sources":["../../src/index.ts"],"sourcesContent":["// Cross-platform, non-streaming JavaScript API\nexport { jsonrepair } from './regular/jsonrepair.js'\nexport { JSONRepairError } from './utils/JSONRepairError.js'\n"],"mappings":"AAAA;AACA,SAASA,UAAU,QAAQ,yBAAyB;AACpD,SAASC,eAAe,QAAQ,4BAA4B","ignoreList":[]} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/regular/jsonrepair.js b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/regular/jsonrepair.js new file mode 100644 index 0000000000000000000000000000000000000000..bc1baa7539aabf67105c006ddb191ce2f5e65880 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/regular/jsonrepair.js @@ -0,0 +1,739 @@ +import { JSONRepairError } from '../utils/JSONRepairError.js'; +import { endsWithCommaOrNewline, insertBeforeLastWhitespace, isControlCharacter, isDelimiter, isDigit, isDoubleQuote, isDoubleQuoteLike, isFunctionNameChar, isFunctionNameCharStart, isHex, isQuote, isSingleQuote, isSingleQuoteLike, isSpecialWhitespace, isStartOfValue, isUnquotedStringDelimiter, isValidStringCharacter, isWhitespace, isWhitespaceExceptNewline, regexUrlChar, regexUrlStart, removeAtIndex, stripLastOccurrence } from '../utils/stringUtils.js'; +const controlCharacters = { + '\b': '\\b', + '\f': '\\f', + '\n': '\\n', + '\r': '\\r', + '\t': '\\t' +}; + +// map with all escape characters +const escapeCharacters = { + '"': '"', + '\\': '\\', + '/': '/', + b: '\b', + f: '\f', + n: '\n', + r: '\r', + t: '\t' + // note that \u is handled separately in parseString() +}; + +/** + * Repair a string containing an invalid JSON document. + * For example changes JavaScript notation into JSON notation. + * + * Example: + * + * try { + * const json = "{name: 'John'}" + * const repaired = jsonrepair(json) + * console.log(repaired) + * // '{"name": "John"}' + * } catch (err) { + * console.error(err) + * } + * + */ +export function jsonrepair(text) { + let i = 0; // current index in text + let output = ''; // generated output + + parseMarkdownCodeBlock(['```', '[```', '{```']); + const processed = parseValue(); + if (!processed) { + throwUnexpectedEnd(); + } + parseMarkdownCodeBlock(['```', '```]', '```}']); + const processedComma = parseCharacter(','); + if (processedComma) { + parseWhitespaceAndSkipComments(); + } + if (isStartOfValue(text[i]) && endsWithCommaOrNewline(output)) { + // start of a new value after end of the root level object: looks like + // newline delimited JSON -> turn into a root level array + if (!processedComma) { + // repair missing comma + output = insertBeforeLastWhitespace(output, ','); + } + parseNewlineDelimitedJSON(); + } else if (processedComma) { + // repair: remove trailing comma + output = stripLastOccurrence(output, ','); + } + + // repair redundant end quotes + while (text[i] === '}' || text[i] === ']') { + i++; + parseWhitespaceAndSkipComments(); + } + if (i >= text.length) { + // reached the end of the document properly + return output; + } + throwUnexpectedCharacter(); + function parseValue() { + parseWhitespaceAndSkipComments(); + const processed = parseObject() || parseArray() || parseString() || parseNumber() || parseKeywords() || parseUnquotedString(false) || parseRegex(); + parseWhitespaceAndSkipComments(); + return processed; + } + function parseWhitespaceAndSkipComments() { + let skipNewline = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; + const start = i; + let changed = parseWhitespace(skipNewline); + do { + changed = parseComment(); + if (changed) { + changed = parseWhitespace(skipNewline); + } + } while (changed); + return i > start; + } + function parseWhitespace(skipNewline) { + const _isWhiteSpace = skipNewline ? isWhitespace : isWhitespaceExceptNewline; + let whitespace = ''; + while (true) { + if (_isWhiteSpace(text, i)) { + whitespace += text[i]; + i++; + } else if (isSpecialWhitespace(text, i)) { + // repair special whitespace + whitespace += ' '; + i++; + } else { + break; + } + } + if (whitespace.length > 0) { + output += whitespace; + return true; + } + return false; + } + function parseComment() { + // find a block comment '/* ... */' + if (text[i] === '/' && text[i + 1] === '*') { + // repair block comment by skipping it + while (i < text.length && !atEndOfBlockComment(text, i)) { + i++; + } + i += 2; + return true; + } + + // find a line comment '// ...' + if (text[i] === '/' && text[i + 1] === '/') { + // repair line comment by skipping it + while (i < text.length && text[i] !== '\n') { + i++; + } + return true; + } + return false; + } + function parseMarkdownCodeBlock(blocks) { + // find and skip over a Markdown fenced code block: + // ``` ... ``` + // or + // ```json ... ``` + if (skipMarkdownCodeBlock(blocks)) { + if (isFunctionNameCharStart(text[i])) { + // strip the optional language specifier like "json" + while (i < text.length && isFunctionNameChar(text[i])) { + i++; + } + } + parseWhitespaceAndSkipComments(); + return true; + } + return false; + } + function skipMarkdownCodeBlock(blocks) { + for (const block of blocks) { + const end = i + block.length; + if (text.slice(i, end) === block) { + i = end; + return true; + } + } + return false; + } + function parseCharacter(char) { + if (text[i] === char) { + output += text[i]; + i++; + return true; + } + return false; + } + function skipCharacter(char) { + if (text[i] === char) { + i++; + return true; + } + return false; + } + function skipEscapeCharacter() { + return skipCharacter('\\'); + } + + /** + * Skip ellipsis like "[1,2,3,...]" or "[1,2,3,...,9]" or "[...,7,8,9]" + * or a similar construct in objects. + */ + function skipEllipsis() { + parseWhitespaceAndSkipComments(); + if (text[i] === '.' && text[i + 1] === '.' && text[i + 2] === '.') { + // repair: remove the ellipsis (three dots) and optionally a comma + i += 3; + parseWhitespaceAndSkipComments(); + skipCharacter(','); + return true; + } + return false; + } + + /** + * Parse an object like '{"key": "value"}' + */ + function parseObject() { + if (text[i] === '{') { + output += '{'; + i++; + parseWhitespaceAndSkipComments(); + + // repair: skip leading comma like in {, message: "hi"} + if (skipCharacter(',')) { + parseWhitespaceAndSkipComments(); + } + let initial = true; + while (i < text.length && text[i] !== '}') { + let processedComma; + if (!initial) { + processedComma = parseCharacter(','); + if (!processedComma) { + // repair missing comma + output = insertBeforeLastWhitespace(output, ','); + } + parseWhitespaceAndSkipComments(); + } else { + processedComma = true; + initial = false; + } + skipEllipsis(); + const processedKey = parseString() || parseUnquotedString(true); + if (!processedKey) { + if (text[i] === '}' || text[i] === '{' || text[i] === ']' || text[i] === '[' || text[i] === undefined) { + // repair trailing comma + output = stripLastOccurrence(output, ','); + } else { + throwObjectKeyExpected(); + } + break; + } + parseWhitespaceAndSkipComments(); + const processedColon = parseCharacter(':'); + const truncatedText = i >= text.length; + if (!processedColon) { + if (isStartOfValue(text[i]) || truncatedText) { + // repair missing colon + output = insertBeforeLastWhitespace(output, ':'); + } else { + throwColonExpected(); + } + } + const processedValue = parseValue(); + if (!processedValue) { + if (processedColon || truncatedText) { + // repair missing object value + output += 'null'; + } else { + throwColonExpected(); + } + } + } + if (text[i] === '}') { + output += '}'; + i++; + } else { + // repair missing end bracket + output = insertBeforeLastWhitespace(output, '}'); + } + return true; + } + return false; + } + + /** + * Parse an array like '["item1", "item2", ...]' + */ + function parseArray() { + if (text[i] === '[') { + output += '['; + i++; + parseWhitespaceAndSkipComments(); + + // repair: skip leading comma like in [,1,2,3] + if (skipCharacter(',')) { + parseWhitespaceAndSkipComments(); + } + let initial = true; + while (i < text.length && text[i] !== ']') { + if (!initial) { + const processedComma = parseCharacter(','); + if (!processedComma) { + // repair missing comma + output = insertBeforeLastWhitespace(output, ','); + } + } else { + initial = false; + } + skipEllipsis(); + const processedValue = parseValue(); + if (!processedValue) { + // repair trailing comma + output = stripLastOccurrence(output, ','); + break; + } + } + if (text[i] === ']') { + output += ']'; + i++; + } else { + // repair missing closing array bracket + output = insertBeforeLastWhitespace(output, ']'); + } + return true; + } + return false; + } + + /** + * Parse and repair Newline Delimited JSON (NDJSON): + * multiple JSON objects separated by a newline character + */ + function parseNewlineDelimitedJSON() { + // repair NDJSON + let initial = true; + let processedValue = true; + while (processedValue) { + if (!initial) { + // parse optional comma, insert when missing + const processedComma = parseCharacter(','); + if (!processedComma) { + // repair: add missing comma + output = insertBeforeLastWhitespace(output, ','); + } + } else { + initial = false; + } + processedValue = parseValue(); + } + if (!processedValue) { + // repair: remove trailing comma + output = stripLastOccurrence(output, ','); + } + + // repair: wrap the output inside array brackets + output = `[\n${output}\n]`; + } + + /** + * Parse a string enclosed by double quotes "...". Can contain escaped quotes + * Repair strings enclosed in single quotes or special quotes + * Repair an escaped string + * + * The function can run in two stages: + * - First, it assumes the string has a valid end quote + * - If it turns out that the string does not have a valid end quote followed + * by a delimiter (which should be the case), the function runs again in a + * more conservative way, stopping the string at the first next delimiter + * and fixing the string by inserting a quote there, or stopping at a + * stop index detected in the first iteration. + */ + function parseString() { + let stopAtDelimiter = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + let stopAtIndex = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : -1; + let skipEscapeChars = text[i] === '\\'; + if (skipEscapeChars) { + // repair: remove the first escape character + i++; + skipEscapeChars = true; + } + if (isQuote(text[i])) { + // double quotes are correct JSON, + // single quotes come from JavaScript for example, we assume it will have a correct single end quote too + // otherwise, we will match any double-quote-like start with a double-quote-like end, + // or any single-quote-like start with a single-quote-like end + const isEndQuote = isDoubleQuote(text[i]) ? isDoubleQuote : isSingleQuote(text[i]) ? isSingleQuote : isSingleQuoteLike(text[i]) ? isSingleQuoteLike : isDoubleQuoteLike; + const iBefore = i; + const oBefore = output.length; + let str = '"'; + i++; + while (true) { + if (i >= text.length) { + // end of text, we are missing an end quote + + const iPrev = prevNonWhitespaceIndex(i - 1); + if (!stopAtDelimiter && isDelimiter(text.charAt(iPrev))) { + // if the text ends with a delimiter, like ["hello], + // so the missing end quote should be inserted before this delimiter + // retry parsing the string, stopping at the first next delimiter + i = iBefore; + output = output.substring(0, oBefore); + return parseString(true); + } + + // repair missing quote + str = insertBeforeLastWhitespace(str, '"'); + output += str; + return true; + } + if (i === stopAtIndex) { + // use the stop index detected in the first iteration, and repair end quote + str = insertBeforeLastWhitespace(str, '"'); + output += str; + return true; + } + if (isEndQuote(text[i])) { + // end quote + // let us check what is before and after the quote to verify whether this is a legit end quote + const iQuote = i; + const oQuote = str.length; + str += '"'; + i++; + output += str; + parseWhitespaceAndSkipComments(false); + if (stopAtDelimiter || i >= text.length || isDelimiter(text[i]) || isQuote(text[i]) || isDigit(text[i])) { + // The quote is followed by the end of the text, a delimiter, + // or a next value. So the quote is indeed the end of the string. + parseConcatenatedString(); + return true; + } + const iPrevChar = prevNonWhitespaceIndex(iQuote - 1); + const prevChar = text.charAt(iPrevChar); + if (prevChar === ',') { + // A comma followed by a quote, like '{"a":"b,c,"d":"e"}'. + // We assume that the quote is a start quote, and that the end quote + // should have been located right before the comma but is missing. + i = iBefore; + output = output.substring(0, oBefore); + return parseString(false, iPrevChar); + } + if (isDelimiter(prevChar)) { + // This is not the right end quote: it is preceded by a delimiter, + // and NOT followed by a delimiter. So, there is an end quote missing + // parse the string again and then stop at the first next delimiter + i = iBefore; + output = output.substring(0, oBefore); + return parseString(true); + } + + // revert to right after the quote but before any whitespace, and continue parsing the string + output = output.substring(0, oBefore); + i = iQuote + 1; + + // repair unescaped quote + str = `${str.substring(0, oQuote)}\\${str.substring(oQuote)}`; + } else if (stopAtDelimiter && isUnquotedStringDelimiter(text[i])) { + // we're in the mode to stop the string at the first delimiter + // because there is an end quote missing + + // test start of an url like "https://..." (this would be parsed as a comment) + if (text[i - 1] === ':' && regexUrlStart.test(text.substring(iBefore + 1, i + 2))) { + while (i < text.length && regexUrlChar.test(text[i])) { + str += text[i]; + i++; + } + } + + // repair missing quote + str = insertBeforeLastWhitespace(str, '"'); + output += str; + parseConcatenatedString(); + return true; + } else if (text[i] === '\\') { + // handle escaped content like \n or \u2605 + const char = text.charAt(i + 1); + const escapeChar = escapeCharacters[char]; + if (escapeChar !== undefined) { + str += text.slice(i, i + 2); + i += 2; + } else if (char === 'u') { + let j = 2; + while (j < 6 && isHex(text[i + j])) { + j++; + } + if (j === 6) { + str += text.slice(i, i + 6); + i += 6; + } else if (i + j >= text.length) { + // repair invalid or truncated unicode char at the end of the text + // by removing the unicode char and ending the string here + i = text.length; + } else { + throwInvalidUnicodeCharacter(); + } + } else { + // repair invalid escape character: remove it + str += char; + i += 2; + } + } else { + // handle regular characters + const char = text.charAt(i); + if (char === '"' && text[i - 1] !== '\\') { + // repair unescaped double quote + str += `\\${char}`; + i++; + } else if (isControlCharacter(char)) { + // unescaped control character + str += controlCharacters[char]; + i++; + } else { + if (!isValidStringCharacter(char)) { + throwInvalidCharacter(char); + } + str += char; + i++; + } + } + if (skipEscapeChars) { + // repair: skipped escape character (nothing to do) + skipEscapeCharacter(); + } + } + } + return false; + } + + /** + * Repair concatenated strings like "hello" + "world", change this into "helloworld" + */ + function parseConcatenatedString() { + let processed = false; + parseWhitespaceAndSkipComments(); + while (text[i] === '+') { + processed = true; + i++; + parseWhitespaceAndSkipComments(); + + // repair: remove the end quote of the first string + output = stripLastOccurrence(output, '"', true); + const start = output.length; + const parsedStr = parseString(); + if (parsedStr) { + // repair: remove the start quote of the second string + output = removeAtIndex(output, start, 1); + } else { + // repair: remove the + because it is not followed by a string + output = insertBeforeLastWhitespace(output, '"'); + } + } + return processed; + } + + /** + * Parse a number like 2.4 or 2.4e6 + */ + function parseNumber() { + const start = i; + if (text[i] === '-') { + i++; + if (atEndOfNumber()) { + repairNumberEndingWithNumericSymbol(start); + return true; + } + if (!isDigit(text[i])) { + i = start; + return false; + } + } + + // Note that in JSON leading zeros like "00789" are not allowed. + // We will allow all leading zeros here though and at the end of parseNumber + // check against trailing zeros and repair that if needed. + // Leading zeros can have meaning, so we should not clear them. + while (isDigit(text[i])) { + i++; + } + if (text[i] === '.') { + i++; + if (atEndOfNumber()) { + repairNumberEndingWithNumericSymbol(start); + return true; + } + if (!isDigit(text[i])) { + i = start; + return false; + } + while (isDigit(text[i])) { + i++; + } + } + if (text[i] === 'e' || text[i] === 'E') { + i++; + if (text[i] === '-' || text[i] === '+') { + i++; + } + if (atEndOfNumber()) { + repairNumberEndingWithNumericSymbol(start); + return true; + } + if (!isDigit(text[i])) { + i = start; + return false; + } + while (isDigit(text[i])) { + i++; + } + } + + // if we're not at the end of the number by this point, allow this to be parsed as another type + if (!atEndOfNumber()) { + i = start; + return false; + } + if (i > start) { + // repair a number with leading zeros like "00789" + const num = text.slice(start, i); + const hasInvalidLeadingZero = /^0\d/.test(num); + output += hasInvalidLeadingZero ? `"${num}"` : num; + return true; + } + return false; + } + + /** + * Parse keywords true, false, null + * Repair Python keywords True, False, None + */ + function parseKeywords() { + return parseKeyword('true', 'true') || parseKeyword('false', 'false') || parseKeyword('null', 'null') || + // repair Python keywords True, False, None + parseKeyword('True', 'true') || parseKeyword('False', 'false') || parseKeyword('None', 'null'); + } + function parseKeyword(name, value) { + if (text.slice(i, i + name.length) === name) { + output += value; + i += name.length; + return true; + } + return false; + } + + /** + * Repair an unquoted string by adding quotes around it + * Repair a MongoDB function call like NumberLong("2") + * Repair a JSONP function call like callback({...}); + */ + function parseUnquotedString(isKey) { + // note that the symbol can end with whitespaces: we stop at the next delimiter + // also, note that we allow strings to contain a slash / in order to support repairing regular expressions + const start = i; + if (isFunctionNameCharStart(text[i])) { + while (i < text.length && isFunctionNameChar(text[i])) { + i++; + } + let j = i; + while (isWhitespace(text, j)) { + j++; + } + if (text[j] === '(') { + // repair a MongoDB function call like NumberLong("2") + // repair a JSONP function call like callback({...}); + i = j + 1; + parseValue(); + if (text[i] === ')') { + // repair: skip close bracket of function call + i++; + if (text[i] === ';') { + // repair: skip semicolon after JSONP call + i++; + } + } + return true; + } + } + while (i < text.length && !isUnquotedStringDelimiter(text[i]) && !isQuote(text[i]) && (!isKey || text[i] !== ':')) { + i++; + } + + // test start of an url like "https://..." (this would be parsed as a comment) + if (text[i - 1] === ':' && regexUrlStart.test(text.substring(start, i + 2))) { + while (i < text.length && regexUrlChar.test(text[i])) { + i++; + } + } + if (i > start) { + // repair unquoted string + // also, repair undefined into null + + // first, go back to prevent getting trailing whitespaces in the string + while (isWhitespace(text, i - 1) && i > 0) { + i--; + } + const symbol = text.slice(start, i); + output += symbol === 'undefined' ? 'null' : JSON.stringify(symbol); + if (text[i] === '"') { + // we had a missing start quote, but now we encountered the end quote, so we can skip that one + i++; + } + return true; + } + } + function parseRegex() { + if (text[i] === '/') { + const start = i; + i++; + while (i < text.length && (text[i] !== '/' || text[i - 1] === '\\')) { + i++; + } + i++; + output += `"${text.substring(start, i)}"`; + return true; + } + } + function prevNonWhitespaceIndex(start) { + let prev = start; + while (prev > 0 && isWhitespace(text, prev)) { + prev--; + } + return prev; + } + function atEndOfNumber() { + return i >= text.length || isDelimiter(text[i]) || isWhitespace(text, i); + } + function repairNumberEndingWithNumericSymbol(start) { + // repair numbers cut off at the end + // this will only be called when we end after a '.', '-', or 'e' and does not + // change the number more than it needs to make it valid JSON + output += `${text.slice(start, i)}0`; + } + function throwInvalidCharacter(char) { + throw new JSONRepairError(`Invalid character ${JSON.stringify(char)}`, i); + } + function throwUnexpectedCharacter() { + throw new JSONRepairError(`Unexpected character ${JSON.stringify(text[i])}`, i); + } + function throwUnexpectedEnd() { + throw new JSONRepairError('Unexpected end of json string', text.length); + } + function throwObjectKeyExpected() { + throw new JSONRepairError('Object key expected', i); + } + function throwColonExpected() { + throw new JSONRepairError('Colon expected', i); + } + function throwInvalidUnicodeCharacter() { + const chars = text.slice(i, i + 6); + throw new JSONRepairError(`Invalid unicode character "${chars}"`, i); + } +} +function atEndOfBlockComment(text, i) { + return text[i] === '*' && text[i + 1] === '/'; +} +//# sourceMappingURL=jsonrepair.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/regular/jsonrepair.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/regular/jsonrepair.js.map new file mode 100644 index 0000000000000000000000000000000000000000..2e7b3de39ae116d15817962c1a2d8430c238804b --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/regular/jsonrepair.js.map @@ -0,0 +1 @@ +{"version":3,"file":"jsonrepair.js","names":["JSONRepairError","endsWithCommaOrNewline","insertBeforeLastWhitespace","isControlCharacter","isDelimiter","isDigit","isDoubleQuote","isDoubleQuoteLike","isFunctionNameChar","isFunctionNameCharStart","isHex","isQuote","isSingleQuote","isSingleQuoteLike","isSpecialWhitespace","isStartOfValue","isUnquotedStringDelimiter","isValidStringCharacter","isWhitespace","isWhitespaceExceptNewline","regexUrlChar","regexUrlStart","removeAtIndex","stripLastOccurrence","controlCharacters","escapeCharacters","b","f","n","r","t","jsonrepair","text","i","output","parseMarkdownCodeBlock","processed","parseValue","throwUnexpectedEnd","processedComma","parseCharacter","parseWhitespaceAndSkipComments","parseNewlineDelimitedJSON","length","throwUnexpectedCharacter","parseObject","parseArray","parseString","parseNumber","parseKeywords","parseUnquotedString","parseRegex","skipNewline","arguments","undefined","start","changed","parseWhitespace","parseComment","_isWhiteSpace","whitespace","atEndOfBlockComment","blocks","skipMarkdownCodeBlock","block","end","slice","char","skipCharacter","skipEscapeCharacter","skipEllipsis","initial","processedKey","throwObjectKeyExpected","processedColon","truncatedText","throwColonExpected","processedValue","stopAtDelimiter","stopAtIndex","skipEscapeChars","isEndQuote","iBefore","oBefore","str","iPrev","prevNonWhitespaceIndex","charAt","substring","iQuote","oQuote","parseConcatenatedString","iPrevChar","prevChar","test","escapeChar","j","throwInvalidUnicodeCharacter","throwInvalidCharacter","parsedStr","atEndOfNumber","repairNumberEndingWithNumericSymbol","num","hasInvalidLeadingZero","parseKeyword","name","value","isKey","symbol","JSON","stringify","prev","chars"],"sources":["../../../src/regular/jsonrepair.ts"],"sourcesContent":["import { JSONRepairError } from '../utils/JSONRepairError.js'\nimport {\n endsWithCommaOrNewline,\n insertBeforeLastWhitespace,\n isControlCharacter,\n isDelimiter,\n isDigit,\n isDoubleQuote,\n isDoubleQuoteLike,\n isFunctionNameChar,\n isFunctionNameCharStart,\n isHex,\n isQuote,\n isSingleQuote,\n isSingleQuoteLike,\n isSpecialWhitespace,\n isStartOfValue,\n isUnquotedStringDelimiter,\n isValidStringCharacter,\n isWhitespace,\n isWhitespaceExceptNewline,\n regexUrlChar,\n regexUrlStart,\n removeAtIndex,\n stripLastOccurrence\n} from '../utils/stringUtils.js'\n\nconst controlCharacters: { [key: string]: string } = {\n '\\b': '\\\\b',\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t'\n}\n\n// map with all escape characters\nconst escapeCharacters: { [key: string]: string } = {\n '\"': '\"',\n '\\\\': '\\\\',\n '/': '/',\n b: '\\b',\n f: '\\f',\n n: '\\n',\n r: '\\r',\n t: '\\t'\n // note that \\u is handled separately in parseString()\n}\n\n/**\n * Repair a string containing an invalid JSON document.\n * For example changes JavaScript notation into JSON notation.\n *\n * Example:\n *\n * try {\n * const json = \"{name: 'John'}\"\n * const repaired = jsonrepair(json)\n * console.log(repaired)\n * // '{\"name\": \"John\"}'\n * } catch (err) {\n * console.error(err)\n * }\n *\n */\nexport function jsonrepair(text: string): string {\n let i = 0 // current index in text\n let output = '' // generated output\n\n parseMarkdownCodeBlock(['```', '[```', '{```'])\n\n const processed = parseValue()\n if (!processed) {\n throwUnexpectedEnd()\n }\n\n parseMarkdownCodeBlock(['```', '```]', '```}'])\n\n const processedComma = parseCharacter(',')\n if (processedComma) {\n parseWhitespaceAndSkipComments()\n }\n\n if (isStartOfValue(text[i]) && endsWithCommaOrNewline(output)) {\n // start of a new value after end of the root level object: looks like\n // newline delimited JSON -> turn into a root level array\n if (!processedComma) {\n // repair missing comma\n output = insertBeforeLastWhitespace(output, ',')\n }\n\n parseNewlineDelimitedJSON()\n } else if (processedComma) {\n // repair: remove trailing comma\n output = stripLastOccurrence(output, ',')\n }\n\n // repair redundant end quotes\n while (text[i] === '}' || text[i] === ']') {\n i++\n parseWhitespaceAndSkipComments()\n }\n\n if (i >= text.length) {\n // reached the end of the document properly\n return output\n }\n\n throwUnexpectedCharacter()\n\n function parseValue(): boolean {\n parseWhitespaceAndSkipComments()\n const processed =\n parseObject() ||\n parseArray() ||\n parseString() ||\n parseNumber() ||\n parseKeywords() ||\n parseUnquotedString(false) ||\n parseRegex()\n parseWhitespaceAndSkipComments()\n\n return processed\n }\n\n function parseWhitespaceAndSkipComments(skipNewline = true): boolean {\n const start = i\n\n let changed = parseWhitespace(skipNewline)\n do {\n changed = parseComment()\n if (changed) {\n changed = parseWhitespace(skipNewline)\n }\n } while (changed)\n\n return i > start\n }\n\n function parseWhitespace(skipNewline: boolean): boolean {\n const _isWhiteSpace = skipNewline ? isWhitespace : isWhitespaceExceptNewline\n let whitespace = ''\n\n while (true) {\n if (_isWhiteSpace(text, i)) {\n whitespace += text[i]\n i++\n } else if (isSpecialWhitespace(text, i)) {\n // repair special whitespace\n whitespace += ' '\n i++\n } else {\n break\n }\n }\n\n if (whitespace.length > 0) {\n output += whitespace\n return true\n }\n\n return false\n }\n\n function parseComment(): boolean {\n // find a block comment '/* ... */'\n if (text[i] === '/' && text[i + 1] === '*') {\n // repair block comment by skipping it\n while (i < text.length && !atEndOfBlockComment(text, i)) {\n i++\n }\n i += 2\n\n return true\n }\n\n // find a line comment '// ...'\n if (text[i] === '/' && text[i + 1] === '/') {\n // repair line comment by skipping it\n while (i < text.length && text[i] !== '\\n') {\n i++\n }\n\n return true\n }\n\n return false\n }\n\n function parseMarkdownCodeBlock(blocks: string[]): boolean {\n // find and skip over a Markdown fenced code block:\n // ``` ... ```\n // or\n // ```json ... ```\n if (skipMarkdownCodeBlock(blocks)) {\n if (isFunctionNameCharStart(text[i])) {\n // strip the optional language specifier like \"json\"\n while (i < text.length && isFunctionNameChar(text[i])) {\n i++\n }\n }\n\n parseWhitespaceAndSkipComments()\n\n return true\n }\n\n return false\n }\n\n function skipMarkdownCodeBlock(blocks: string[]): boolean {\n for (const block of blocks) {\n const end = i + block.length\n if (text.slice(i, end) === block) {\n i = end\n return true\n }\n }\n\n return false\n }\n\n function parseCharacter(char: string): boolean {\n if (text[i] === char) {\n output += text[i]\n i++\n return true\n }\n\n return false\n }\n\n function skipCharacter(char: string): boolean {\n if (text[i] === char) {\n i++\n return true\n }\n\n return false\n }\n\n function skipEscapeCharacter(): boolean {\n return skipCharacter('\\\\')\n }\n\n /**\n * Skip ellipsis like \"[1,2,3,...]\" or \"[1,2,3,...,9]\" or \"[...,7,8,9]\"\n * or a similar construct in objects.\n */\n function skipEllipsis(): boolean {\n parseWhitespaceAndSkipComments()\n\n if (text[i] === '.' && text[i + 1] === '.' && text[i + 2] === '.') {\n // repair: remove the ellipsis (three dots) and optionally a comma\n i += 3\n parseWhitespaceAndSkipComments()\n skipCharacter(',')\n\n return true\n }\n\n return false\n }\n\n /**\n * Parse an object like '{\"key\": \"value\"}'\n */\n function parseObject(): boolean {\n if (text[i] === '{') {\n output += '{'\n i++\n parseWhitespaceAndSkipComments()\n\n // repair: skip leading comma like in {, message: \"hi\"}\n if (skipCharacter(',')) {\n parseWhitespaceAndSkipComments()\n }\n\n let initial = true\n while (i < text.length && text[i] !== '}') {\n let processedComma: boolean\n if (!initial) {\n processedComma = parseCharacter(',')\n if (!processedComma) {\n // repair missing comma\n output = insertBeforeLastWhitespace(output, ',')\n }\n parseWhitespaceAndSkipComments()\n } else {\n processedComma = true\n initial = false\n }\n\n skipEllipsis()\n\n const processedKey = parseString() || parseUnquotedString(true)\n if (!processedKey) {\n if (\n text[i] === '}' ||\n text[i] === '{' ||\n text[i] === ']' ||\n text[i] === '[' ||\n text[i] === undefined\n ) {\n // repair trailing comma\n output = stripLastOccurrence(output, ',')\n } else {\n throwObjectKeyExpected()\n }\n break\n }\n\n parseWhitespaceAndSkipComments()\n const processedColon = parseCharacter(':')\n const truncatedText = i >= text.length\n if (!processedColon) {\n if (isStartOfValue(text[i]) || truncatedText) {\n // repair missing colon\n output = insertBeforeLastWhitespace(output, ':')\n } else {\n throwColonExpected()\n }\n }\n const processedValue = parseValue()\n if (!processedValue) {\n if (processedColon || truncatedText) {\n // repair missing object value\n output += 'null'\n } else {\n throwColonExpected()\n }\n }\n }\n\n if (text[i] === '}') {\n output += '}'\n i++\n } else {\n // repair missing end bracket\n output = insertBeforeLastWhitespace(output, '}')\n }\n\n return true\n }\n\n return false\n }\n\n /**\n * Parse an array like '[\"item1\", \"item2\", ...]'\n */\n function parseArray(): boolean {\n if (text[i] === '[') {\n output += '['\n i++\n parseWhitespaceAndSkipComments()\n\n // repair: skip leading comma like in [,1,2,3]\n if (skipCharacter(',')) {\n parseWhitespaceAndSkipComments()\n }\n\n let initial = true\n while (i < text.length && text[i] !== ']') {\n if (!initial) {\n const processedComma = parseCharacter(',')\n if (!processedComma) {\n // repair missing comma\n output = insertBeforeLastWhitespace(output, ',')\n }\n } else {\n initial = false\n }\n\n skipEllipsis()\n\n const processedValue = parseValue()\n if (!processedValue) {\n // repair trailing comma\n output = stripLastOccurrence(output, ',')\n break\n }\n }\n\n if (text[i] === ']') {\n output += ']'\n i++\n } else {\n // repair missing closing array bracket\n output = insertBeforeLastWhitespace(output, ']')\n }\n\n return true\n }\n\n return false\n }\n\n /**\n * Parse and repair Newline Delimited JSON (NDJSON):\n * multiple JSON objects separated by a newline character\n */\n function parseNewlineDelimitedJSON() {\n // repair NDJSON\n let initial = true\n let processedValue = true\n while (processedValue) {\n if (!initial) {\n // parse optional comma, insert when missing\n const processedComma = parseCharacter(',')\n if (!processedComma) {\n // repair: add missing comma\n output = insertBeforeLastWhitespace(output, ',')\n }\n } else {\n initial = false\n }\n\n processedValue = parseValue()\n }\n\n if (!processedValue) {\n // repair: remove trailing comma\n output = stripLastOccurrence(output, ',')\n }\n\n // repair: wrap the output inside array brackets\n output = `[\\n${output}\\n]`\n }\n\n /**\n * Parse a string enclosed by double quotes \"...\". Can contain escaped quotes\n * Repair strings enclosed in single quotes or special quotes\n * Repair an escaped string\n *\n * The function can run in two stages:\n * - First, it assumes the string has a valid end quote\n * - If it turns out that the string does not have a valid end quote followed\n * by a delimiter (which should be the case), the function runs again in a\n * more conservative way, stopping the string at the first next delimiter\n * and fixing the string by inserting a quote there, or stopping at a\n * stop index detected in the first iteration.\n */\n function parseString(stopAtDelimiter = false, stopAtIndex = -1): boolean {\n let skipEscapeChars = text[i] === '\\\\'\n if (skipEscapeChars) {\n // repair: remove the first escape character\n i++\n skipEscapeChars = true\n }\n\n if (isQuote(text[i])) {\n // double quotes are correct JSON,\n // single quotes come from JavaScript for example, we assume it will have a correct single end quote too\n // otherwise, we will match any double-quote-like start with a double-quote-like end,\n // or any single-quote-like start with a single-quote-like end\n const isEndQuote = isDoubleQuote(text[i])\n ? isDoubleQuote\n : isSingleQuote(text[i])\n ? isSingleQuote\n : isSingleQuoteLike(text[i])\n ? isSingleQuoteLike\n : isDoubleQuoteLike\n\n const iBefore = i\n const oBefore = output.length\n\n let str = '\"'\n i++\n\n while (true) {\n if (i >= text.length) {\n // end of text, we are missing an end quote\n\n const iPrev = prevNonWhitespaceIndex(i - 1)\n if (!stopAtDelimiter && isDelimiter(text.charAt(iPrev))) {\n // if the text ends with a delimiter, like [\"hello],\n // so the missing end quote should be inserted before this delimiter\n // retry parsing the string, stopping at the first next delimiter\n i = iBefore\n output = output.substring(0, oBefore)\n\n return parseString(true)\n }\n\n // repair missing quote\n str = insertBeforeLastWhitespace(str, '\"')\n output += str\n\n return true\n }\n\n if (i === stopAtIndex) {\n // use the stop index detected in the first iteration, and repair end quote\n str = insertBeforeLastWhitespace(str, '\"')\n output += str\n\n return true\n }\n\n if (isEndQuote(text[i])) {\n // end quote\n // let us check what is before and after the quote to verify whether this is a legit end quote\n const iQuote = i\n const oQuote = str.length\n str += '\"'\n i++\n output += str\n\n parseWhitespaceAndSkipComments(false)\n\n if (\n stopAtDelimiter ||\n i >= text.length ||\n isDelimiter(text[i]) ||\n isQuote(text[i]) ||\n isDigit(text[i])\n ) {\n // The quote is followed by the end of the text, a delimiter,\n // or a next value. So the quote is indeed the end of the string.\n parseConcatenatedString()\n\n return true\n }\n\n const iPrevChar = prevNonWhitespaceIndex(iQuote - 1)\n const prevChar = text.charAt(iPrevChar)\n\n if (prevChar === ',') {\n // A comma followed by a quote, like '{\"a\":\"b,c,\"d\":\"e\"}'.\n // We assume that the quote is a start quote, and that the end quote\n // should have been located right before the comma but is missing.\n i = iBefore\n output = output.substring(0, oBefore)\n\n return parseString(false, iPrevChar)\n }\n\n if (isDelimiter(prevChar)) {\n // This is not the right end quote: it is preceded by a delimiter,\n // and NOT followed by a delimiter. So, there is an end quote missing\n // parse the string again and then stop at the first next delimiter\n i = iBefore\n output = output.substring(0, oBefore)\n\n return parseString(true)\n }\n\n // revert to right after the quote but before any whitespace, and continue parsing the string\n output = output.substring(0, oBefore)\n i = iQuote + 1\n\n // repair unescaped quote\n str = `${str.substring(0, oQuote)}\\\\${str.substring(oQuote)}`\n } else if (stopAtDelimiter && isUnquotedStringDelimiter(text[i])) {\n // we're in the mode to stop the string at the first delimiter\n // because there is an end quote missing\n\n // test start of an url like \"https://...\" (this would be parsed as a comment)\n if (text[i - 1] === ':' && regexUrlStart.test(text.substring(iBefore + 1, i + 2))) {\n while (i < text.length && regexUrlChar.test(text[i])) {\n str += text[i]\n i++\n }\n }\n\n // repair missing quote\n str = insertBeforeLastWhitespace(str, '\"')\n output += str\n\n parseConcatenatedString()\n\n return true\n } else if (text[i] === '\\\\') {\n // handle escaped content like \\n or \\u2605\n const char = text.charAt(i + 1)\n const escapeChar = escapeCharacters[char]\n if (escapeChar !== undefined) {\n str += text.slice(i, i + 2)\n i += 2\n } else if (char === 'u') {\n let j = 2\n while (j < 6 && isHex(text[i + j])) {\n j++\n }\n\n if (j === 6) {\n str += text.slice(i, i + 6)\n i += 6\n } else if (i + j >= text.length) {\n // repair invalid or truncated unicode char at the end of the text\n // by removing the unicode char and ending the string here\n i = text.length\n } else {\n throwInvalidUnicodeCharacter()\n }\n } else {\n // repair invalid escape character: remove it\n str += char\n i += 2\n }\n } else {\n // handle regular characters\n const char = text.charAt(i)\n\n if (char === '\"' && text[i - 1] !== '\\\\') {\n // repair unescaped double quote\n str += `\\\\${char}`\n i++\n } else if (isControlCharacter(char)) {\n // unescaped control character\n str += controlCharacters[char]\n i++\n } else {\n if (!isValidStringCharacter(char)) {\n throwInvalidCharacter(char)\n }\n str += char\n i++\n }\n }\n\n if (skipEscapeChars) {\n // repair: skipped escape character (nothing to do)\n skipEscapeCharacter()\n }\n }\n }\n\n return false\n }\n\n /**\n * Repair concatenated strings like \"hello\" + \"world\", change this into \"helloworld\"\n */\n function parseConcatenatedString(): boolean {\n let processed = false\n\n parseWhitespaceAndSkipComments()\n while (text[i] === '+') {\n processed = true\n i++\n parseWhitespaceAndSkipComments()\n\n // repair: remove the end quote of the first string\n output = stripLastOccurrence(output, '\"', true)\n const start = output.length\n const parsedStr = parseString()\n if (parsedStr) {\n // repair: remove the start quote of the second string\n output = removeAtIndex(output, start, 1)\n } else {\n // repair: remove the + because it is not followed by a string\n output = insertBeforeLastWhitespace(output, '\"')\n }\n }\n\n return processed\n }\n\n /**\n * Parse a number like 2.4 or 2.4e6\n */\n function parseNumber(): boolean {\n const start = i\n if (text[i] === '-') {\n i++\n if (atEndOfNumber()) {\n repairNumberEndingWithNumericSymbol(start)\n return true\n }\n if (!isDigit(text[i])) {\n i = start\n return false\n }\n }\n\n // Note that in JSON leading zeros like \"00789\" are not allowed.\n // We will allow all leading zeros here though and at the end of parseNumber\n // check against trailing zeros and repair that if needed.\n // Leading zeros can have meaning, so we should not clear them.\n while (isDigit(text[i])) {\n i++\n }\n\n if (text[i] === '.') {\n i++\n if (atEndOfNumber()) {\n repairNumberEndingWithNumericSymbol(start)\n return true\n }\n if (!isDigit(text[i])) {\n i = start\n return false\n }\n while (isDigit(text[i])) {\n i++\n }\n }\n\n if (text[i] === 'e' || text[i] === 'E') {\n i++\n if (text[i] === '-' || text[i] === '+') {\n i++\n }\n if (atEndOfNumber()) {\n repairNumberEndingWithNumericSymbol(start)\n return true\n }\n if (!isDigit(text[i])) {\n i = start\n return false\n }\n while (isDigit(text[i])) {\n i++\n }\n }\n\n // if we're not at the end of the number by this point, allow this to be parsed as another type\n if (!atEndOfNumber()) {\n i = start\n return false\n }\n\n if (i > start) {\n // repair a number with leading zeros like \"00789\"\n const num = text.slice(start, i)\n const hasInvalidLeadingZero = /^0\\d/.test(num)\n\n output += hasInvalidLeadingZero ? `\"${num}\"` : num\n return true\n }\n\n return false\n }\n\n /**\n * Parse keywords true, false, null\n * Repair Python keywords True, False, None\n */\n function parseKeywords(): boolean {\n return (\n parseKeyword('true', 'true') ||\n parseKeyword('false', 'false') ||\n parseKeyword('null', 'null') ||\n // repair Python keywords True, False, None\n parseKeyword('True', 'true') ||\n parseKeyword('False', 'false') ||\n parseKeyword('None', 'null')\n )\n }\n\n function parseKeyword(name: string, value: string): boolean {\n if (text.slice(i, i + name.length) === name) {\n output += value\n i += name.length\n return true\n }\n\n return false\n }\n\n /**\n * Repair an unquoted string by adding quotes around it\n * Repair a MongoDB function call like NumberLong(\"2\")\n * Repair a JSONP function call like callback({...});\n */\n function parseUnquotedString(isKey: boolean) {\n // note that the symbol can end with whitespaces: we stop at the next delimiter\n // also, note that we allow strings to contain a slash / in order to support repairing regular expressions\n const start = i\n\n if (isFunctionNameCharStart(text[i])) {\n while (i < text.length && isFunctionNameChar(text[i])) {\n i++\n }\n\n let j = i\n while (isWhitespace(text, j)) {\n j++\n }\n\n if (text[j] === '(') {\n // repair a MongoDB function call like NumberLong(\"2\")\n // repair a JSONP function call like callback({...});\n i = j + 1\n\n parseValue()\n\n if (text[i] === ')') {\n // repair: skip close bracket of function call\n i++\n if (text[i] === ';') {\n // repair: skip semicolon after JSONP call\n i++\n }\n }\n\n return true\n }\n }\n\n while (\n i < text.length &&\n !isUnquotedStringDelimiter(text[i]) &&\n !isQuote(text[i]) &&\n (!isKey || text[i] !== ':')\n ) {\n i++\n }\n\n // test start of an url like \"https://...\" (this would be parsed as a comment)\n if (text[i - 1] === ':' && regexUrlStart.test(text.substring(start, i + 2))) {\n while (i < text.length && regexUrlChar.test(text[i])) {\n i++\n }\n }\n\n if (i > start) {\n // repair unquoted string\n // also, repair undefined into null\n\n // first, go back to prevent getting trailing whitespaces in the string\n while (isWhitespace(text, i - 1) && i > 0) {\n i--\n }\n\n const symbol = text.slice(start, i)\n output += symbol === 'undefined' ? 'null' : JSON.stringify(symbol)\n\n if (text[i] === '\"') {\n // we had a missing start quote, but now we encountered the end quote, so we can skip that one\n i++\n }\n\n return true\n }\n }\n\n function parseRegex() {\n if (text[i] === '/') {\n const start = i\n i++\n\n while (i < text.length && (text[i] !== '/' || text[i - 1] === '\\\\')) {\n i++\n }\n i++\n\n output += `\"${text.substring(start, i)}\"`\n\n return true\n }\n }\n\n function prevNonWhitespaceIndex(start: number): number {\n let prev = start\n\n while (prev > 0 && isWhitespace(text, prev)) {\n prev--\n }\n\n return prev\n }\n\n function atEndOfNumber() {\n return i >= text.length || isDelimiter(text[i]) || isWhitespace(text, i)\n }\n\n function repairNumberEndingWithNumericSymbol(start: number) {\n // repair numbers cut off at the end\n // this will only be called when we end after a '.', '-', or 'e' and does not\n // change the number more than it needs to make it valid JSON\n output += `${text.slice(start, i)}0`\n }\n\n function throwInvalidCharacter(char: string) {\n throw new JSONRepairError(`Invalid character ${JSON.stringify(char)}`, i)\n }\n\n function throwUnexpectedCharacter() {\n throw new JSONRepairError(`Unexpected character ${JSON.stringify(text[i])}`, i)\n }\n\n function throwUnexpectedEnd() {\n throw new JSONRepairError('Unexpected end of json string', text.length)\n }\n\n function throwObjectKeyExpected() {\n throw new JSONRepairError('Object key expected', i)\n }\n\n function throwColonExpected() {\n throw new JSONRepairError('Colon expected', i)\n }\n\n function throwInvalidUnicodeCharacter() {\n const chars = text.slice(i, i + 6)\n throw new JSONRepairError(`Invalid unicode character \"${chars}\"`, i)\n }\n}\n\nfunction atEndOfBlockComment(text: string, i: number) {\n return text[i] === '*' && text[i + 1] === '/'\n}\n"],"mappings":"AAAA,SAASA,eAAe,QAAQ,6BAA6B;AAC7D,SACEC,sBAAsB,EACtBC,0BAA0B,EAC1BC,kBAAkB,EACl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AAG,CAAC,CAAC,KAAK,GAAG;AAC/C","ignoreList":[]} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/stream.js b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/stream.js new file mode 100644 index 0000000000000000000000000000000000000000..a3d84c8d058a69d0286069d3097d81a7a1f1695f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/stream.js @@ -0,0 +1,3 @@ +// Node.js streaming API +export { jsonrepairTransform } from './streaming/stream.js'; +//# sourceMappingURL=stream.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/stream.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/stream.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d8f3eb9c1cc728ec0f3a852c64c4a12b579b0831 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/stream.js.map @@ -0,0 +1 @@ +{"version":3,"file":"stream.js","names":["jsonrepairTransform"],"sources":["../../src/stream.ts"],"sourcesContent":["// Node.js streaming API\nexport { type JsonRepairTransformOptions, jsonrepairTransform } from './streaming/stream.js'\n"],"mappings":"AAAA;AACA,SAA0CA,mBAAmB,QAAQ,uBAAuB","ignoreList":[]} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/streaming/buffer/InputBuffer.js b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/streaming/buffer/InputBuffer.js new file mode 100644 index 0000000000000000000000000000000000000000..cd9c1ff8fbb5106717c90b1ceaaac42fc457f573 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/streaming/buffer/InputBuffer.js @@ -0,0 +1,69 @@ +export function createInputBuffer() { + let buffer = ''; + let offset = 0; + let currentLength = 0; + let closed = false; + function ensure(index) { + if (index < offset) { + throw new Error(`${indexOutOfRangeMessage} (index: ${index}, offset: ${offset})`); + } + if (index >= currentLength) { + if (!closed) { + throw new Error(`${indexOutOfRangeMessage} (index: ${index})`); + } + } + } + function push(chunk) { + buffer += chunk; + currentLength += chunk.length; + } + function flush(position) { + if (position > currentLength) { + return; + } + buffer = buffer.substring(position - offset); + offset = position; + } + function charAt(index) { + ensure(index); + return buffer.charAt(index - offset); + } + function charCodeAt(index) { + ensure(index); + return buffer.charCodeAt(index - offset); + } + function substring(start, end) { + ensure(end - 1); // -1 because end is excluded + ensure(start); + return buffer.slice(start - offset, end - offset); + } + function length() { + if (!closed) { + throw new Error('Cannot get length: input is not yet closed'); + } + return currentLength; + } + function isEnd(index) { + if (!closed) { + ensure(index); + } + return index >= currentLength; + } + function close() { + closed = true; + } + return { + push, + flush, + charAt, + charCodeAt, + substring, + length, + currentLength: () => currentLength, + currentBufferSize: () => buffer.length, + isEnd, + close + }; +} +const indexOutOfRangeMessage = 'Index out of range, please configure a larger buffer size'; +//# sourceMappingURL=InputBuffer.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/streaming/buffer/InputBuffer.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/streaming/buffer/InputBuffer.js.map new file mode 100644 index 0000000000000000000000000000000000000000..bc719a80b68af335cc88e97eb0dd07f55dca9787 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/streaming/buffer/InputBuffer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"InputBuffer.js","names":["createInputBuffer","buffer","offset","currentLength","closed","ensure","index","Error","indexOutOfRangeMessage","push","chunk","length","flush","position","substring","charAt","charCodeAt","start","end","slice","isEnd","close","currentBufferSize"],"sources":["../../../../src/streaming/buffer/InputBuffer.ts"],"sourcesContent":["export interface InputBuffer {\n push: (chunk: string) => void\n flush: (position: number) => void\n charAt: (index: number) => string\n charCodeAt: (index: number) => number\n substring: (start: number, end: number) => string\n length: () => number\n currentLength: () => number\n currentBufferSize: () => number\n isEnd: (index: number) => boolean\n close: () => void\n}\n\nexport function createInputBuffer(): InputBuffer {\n let buffer = ''\n let offset = 0\n let currentLength = 0\n let closed = false\n\n function ensure(index: number) {\n if (index < offset) {\n throw new Error(`${indexOutOfRangeMessage} (index: ${index}, offset: ${offset})`)\n }\n\n if (index >= currentLength) {\n if (!closed) {\n throw new Error(`${indexOutOfRangeMessage} (index: ${index})`)\n }\n }\n }\n\n function push(chunk: string) {\n buffer += chunk\n currentLength += chunk.length\n }\n\n function flush(position: number) {\n if (position > currentLength) {\n return\n }\n\n buffer = buffer.substring(position - offset)\n offset = position\n }\n\n function charAt(index: number): string {\n ensure(index)\n\n return buffer.charAt(index - offset)\n }\n\n function charCodeAt(index: number): number {\n ensure(index)\n\n return buffer.charCodeAt(index - offset)\n }\n\n function substring(start: number, end: number): string {\n ensure(end - 1) // -1 because end is excluded\n ensure(start)\n\n return buffer.slice(start - offset, end - offset)\n }\n\n function length(): number {\n if (!closed) {\n throw new Error('Cannot get length: input is not yet closed')\n }\n\n return currentLength\n }\n\n function isEnd(index: number): boolean {\n if (!closed) {\n ensure(index)\n }\n\n return index >= currentLength\n }\n\n function close() {\n closed = true\n }\n\n return {\n push,\n flush,\n charAt,\n charCodeAt,\n substring,\n length,\n currentLength: () => currentLength,\n currentBufferSize: () => buffer.length,\n isEnd,\n close\n }\n}\n\nconst indexOutOfRangeMessage = 'Index out of range, please configure a larger buffer size'\n"],"mappings":"AAaA,OAAO,SAASA,iBAAiBA,CAAA,EAAgB;EAC/C,IAAIC,MAAM,GAAG,EAAE;EACf,IAAIC,MAAM,GAAG,CAAC;EACd,IAAIC,aAAa,GAAG,CAAC;EACrB,IAAIC,MAAM,GAAG,KAAK;EAElB,SAASC,MAAMA,CAACC,KAAa,EAAE;IAC7B,IAAIA,KAAK,GAAGJ,MAAM,EAAE;MAClB,MAAM,IAAIK,KAAK,CAAC,GAAGC,sBAAsB,Y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M,CAACC,KAAK,CAAC;IACf;IAEA,OAAOA,KAAK,IAAIH,aAAa;EAC/B;EAEA,SAASkB,KAAKA,CAAA,EAAG;IACfjB,MAAM,GAAG,IAAI;EACf;EAEA,OAAO;IACLK,IAAI;IACJG,KAAK;IACLG,MAAM;IACNC,UAAU;IACVF,SAAS;IACTH,MAAM;IACNR,aAAa,EAAEA,CAAA,KAAMA,aAAa;IAClCmB,iBAAiB,EAAEA,CAAA,KAAMrB,MAAM,CAACU,MAAM;IACtCS,KAAK;IACLC;EACF,CAAC;AACH;AAEA,MAAMb,sBAAsB,GAAG,2DAA2D","ignoreList":[]} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/streaming/buffer/OutputBuffer.js b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/streaming/buffer/OutputBuffer.js new file mode 100644 index 0000000000000000000000000000000000000000..e153592e032b8bf38f2bb64f1b66b05ff923b4c9 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/streaming/buffer/OutputBuffer.js @@ -0,0 +1,111 @@ +import { isWhitespace } from '../../utils/stringUtils.js'; +export function createOutputBuffer(_ref) { + let { + write, + chunkSize, + bufferSize + } = _ref; + let buffer = ''; + let offset = 0; + function flushChunks() { + let minSize = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : bufferSize; + while (buffer.length >= minSize + chunkSize) { + const chunk = buffer.substring(0, chunkSize); + write(chunk); + offset += chunkSize; + buffer = buffer.substring(chunkSize); + } + } + function flush() { + flushChunks(0); + if (buffer.length > 0) { + write(buffer); + offset += buffer.length; + buffer = ''; + } + } + function push(text) { + buffer += text; + flushChunks(); + } + function unshift(text) { + if (offset > 0) { + throw new Error(`Cannot unshift: ${flushedMessage}`); + } + buffer = text + buffer; + flushChunks(); + } + function remove(start, end) { + if (start < offset) { + throw new Error(`Cannot remove: ${flushedMessage}`); + } + if (end !== undefined) { + buffer = buffer.substring(0, start - offset) + buffer.substring(end - offset); + } else { + buffer = buffer.substring(0, start - offset); + } + } + function insertAt(index, text) { + if (index < offset) { + throw new Error(`Cannot insert: ${flushedMessage}`); + } + buffer = buffer.substring(0, index - offset) + text + buffer.substring(index - offset); + } + function length() { + return offset + buffer.length; + } + function stripLastOccurrence(textToStrip) { + let stripRemainingText = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + const bufferIndex = buffer.lastIndexOf(textToStrip); + if (bufferIndex !== -1) { + if (stripRemainingText) { + buffer = buffer.substring(0, bufferIndex); + } else { + buffer = buffer.substring(0, bufferIndex) + buffer.substring(bufferIndex + textToStrip.length); + } + } + } + function insertBeforeLastWhitespace(textToInsert) { + let bufferIndex = buffer.length; // index relative to the start of the buffer, not taking `offset` into account + + if (!isWhitespace(buffer, bufferIndex - 1)) { + // no trailing whitespaces + push(textToInsert); + return; + } + while (isWhitespace(buffer, bufferIndex - 1)) { + bufferIndex--; + } + if (bufferIndex <= 0) { + throw new Error(`Cannot insert: ${flushedMessage}`); + } + buffer = buffer.substring(0, bufferIndex) + textToInsert + buffer.substring(bufferIndex); + flushChunks(); + } + function endsWithIgnoringWhitespace(char) { + let i = buffer.length - 1; + while (i > 0) { + if (char === buffer.charAt(i)) { + return true; + } + if (!isWhitespace(buffer, i)) { + return false; + } + i--; + } + return false; + } + return { + push, + unshift, + remove, + insertAt, + length, + flush, + stripLastOccurrence, + insertBeforeLastWhitespace, + endsWithIgnoringWhitespace + }; +} +const flushedMessage = 'start of the output is already flushed from the buffer'; +//# sourceMappingURL=OutputBuffer.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/streaming/buffer/OutputBuffer.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/streaming/buffer/OutputBuffer.js.map new file mode 100644 index 0000000000000000000000000000000000000000..c3d1ddf90961d6e110fad47629ec545a669f5312 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/streaming/buffer/OutputBuffer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"OutputBuffer.js","names":["isWhitespace","createOutputBuffer","_ref","write","chunkSize","bufferSize","buffer","offset","flushChunks","minSize","arguments","length","undefined","chunk","substring","flush","push","text","unshift","Error","flushedMessage","remove","start","end","insertAt","index","stripLastOccurrence","textToStrip","stripRemainingText","bufferIndex","lastIndexOf","insertBeforeLastWhitespace","textToInsert","endsWithIgnoringWhitespace","char","i","charAt"],"sources":["../../../../src/streaming/buffer/OutputBuffer.ts"],"sourcesContent":["import { isWhitespace } from '../../utils/stringUtils.js'\n\nexport interface OutputBuffer {\n push: (text: string) => void\n unshift: (text: string) => void\n remove: (start: number, end?: number) => void\n insertAt: (index: number, text: string) => void\n length: () => number\n flush: () => void\n\n stripLastOccurrence: (textToStrip: string, stripRemainingText?: boolean) => void\n insertBeforeLastWhitespace: (textToInsert: string) => void\n endsWithIgnoringWhitespace: (char: string) => boolean\n}\n\nexport interface OutputBufferOptions {\n write: (chunk: string) => void\n chunkSize: number\n bufferSize: number\n}\n\nexport function createOutputBuffer({\n write,\n chunkSize,\n bufferSize\n}: OutputBufferOptions): OutputBuffer {\n let buffer = ''\n let offset = 0\n\n function flushChunks(minSize = bufferSize) {\n while (buffer.length >= minSize + chunkSize) {\n const chunk = buffer.substring(0, chunkSize)\n write(chunk)\n offset += chunkSize\n buffer = buffer.substring(chunkSize)\n }\n }\n\n function flush() {\n flushChunks(0)\n\n if (buffer.length > 0) {\n write(buffer)\n offset += buffer.length\n buffer = ''\n }\n }\n\n function push(text: string) {\n buffer += text\n flushChunks()\n }\n\n function unshift(text: string) {\n if (offset > 0) {\n throw new Error(`Cannot unshift: ${flushedMessage}`)\n }\n\n buffer = text + buffer\n flushChunks()\n }\n\n function remove(start: number, end?: number) {\n if (start < offset) {\n throw new Error(`Cannot remove: ${flushedMessage}`)\n }\n\n if (end !== undefined) {\n buffer = buffer.substring(0, start - offset) + buffer.substring(end - offset)\n } else {\n buffer = buffer.substring(0, start - offset)\n }\n }\n\n function insertAt(index: number, text: string) {\n if (index < offset) {\n throw new Error(`Cannot insert: ${flushedMessage}`)\n }\n\n buffer = buffer.substring(0, index - offset) + text + buffer.substring(index - offset)\n }\n\n function length(): number {\n return offset + buffer.length\n }\n\n function stripLastOccurrence(textToStrip: string, stripRemainingText = false) {\n const bufferIndex = buffer.lastIndexOf(textToStrip)\n\n if (bufferIndex !== -1) {\n if (stripRemainingText) {\n buffer = buffer.substring(0, bufferIndex)\n } else {\n buffer =\n buffer.substring(0, bufferIndex) + buffer.substring(bufferIndex + textToStrip.length)\n }\n }\n }\n\n function insertBeforeLastWhitespace(textToInsert: string) {\n let bufferIndex = buffer.length // index relative to the start of the buffer, not taking `offset` into account\n\n if (!isWhitespace(buffer, bufferIndex - 1)) {\n // no trailing whitespaces\n push(textToInsert)\n return\n }\n\n while (isWhitespace(buffer, bufferIndex - 1)) {\n bufferIndex--\n }\n\n if (bufferIndex <= 0) {\n throw new Error(`Cannot insert: ${flushedMessage}`)\n }\n\n buffer = buffer.substring(0, bufferIndex) + textToInsert + buffer.substring(bufferIndex)\n flushChunks()\n }\n\n function endsWithIgnoringWhitespace(char: string): boolean {\n let i = buffer.length - 1\n\n while (i > 0) {\n if (char === buffer.charAt(i)) {\n return true\n }\n\n if (!isWhitespace(buffer, i)) {\n return false\n }\n\n i--\n }\n\n return false\n }\n\n return {\n push,\n unshift,\n remove,\n insertAt,\n length,\n flush,\n\n stripLastOccurrence,\n insertBeforeLastWhitespace,\n endsWithIgnoringWhitespace\n }\n}\n\nconst flushedMessage = 'start of the output is already flushed from the buffer'\n"],"mappings":"AAAA,SAASA,YAAY,QAAQ,4BAA4B;AAqBzD,OAAO,SAASC,kBAAkBA,CAAAC,IAAA,EAII;EAAA,IAJH;IACjCC,KAAK;IACLC,SAAS;IACTC;EACmB,CAAC,GAAAH,IAAA;EACpB,IAAII,MAAM,GAAG,EAAE;EACf,IAAIC,MAAM,GAAG,CAAC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C,CAAC,EAAE;MAC1C;MACAb,IAAI,CAACgB,YAAY,CAAC;MAClB;IACF;IAEA,OAAOhC,YAAY,CAACM,MAAM,EAAEuB,WAAW,GAAG,CAAC,CAAC,EAAE;MAC5CA,WAAW,EAAE;IACf;IAEA,IAAIA,WAAW,IAAI,CAAC,EAAE;MACpB,MAAM,IAAIV,KAAK,CAAC,kBAAkBC,cAAc,EAAE,CAAC;IACrD;IAEAd,MAAM,GAAGA,MAAM,CAACQ,SAAS,CAAC,CAAC,EAAEe,WAAW,CAAC,GAAGG,YAAY,GAAG1B,MAAM,CAACQ,SAAS,CAACe,WAAW,CAAC;IACxFrB,WAAW,CAAC,CAAC;EACf;EAEA,SAASyB,0BAA0BA,CAACC,IAAY,EAAW;IACzD,IAAIC,CAAC,GAAG7B,MAAM,CAACK,MAAM,GAAG,CAAC;IAEzB,OAAOwB,CAAC,GAAG,CAAC,EAAE;MACZ,IAAID,IAAI,KAAK5B,MAAM,CAAC8B,MAAM,CAACD,CAAC,CAAC,EAAE;QAC7B,OAAO,IAAI;MACb;MAEA,IAAI,CAACnC,YAAY,CAACM,MAAM,EAAE6B,CAAC,CAAC,EAAE;QAC5B,OAAO,KAAK;MACd;MAEAA,CAAC,EAAE;IACL;IAEA,OAAO,KAAK;EACd;EAEA,OAAO;IACLnB,IAAI;IACJE,OAAO;IACPG,MAAM;IACNG,QAAQ;IACRb,MAAM;IACNI,KAAK;IAELW,mBAAmB;IACnBK,0BAA0B;IAC1BE;EACF,CAAC;AACH;AAEA,MAAMb,cAAc,GAAG,wDAAwD","ignoreList":[]} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/streaming/core.js b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/streaming/core.js new file mode 100644 index 0000000000000000000000000000000000000000..f5c002bdf464dd0b4a4a16f53b7fda3a7f352665 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/streaming/core.js @@ -0,0 +1,818 @@ +import { JSONRepairError } from '../utils/JSONRepairError.js'; +import { isControlCharacter, isDelimiter, isDigit, isDoubleQuote, isDoubleQuoteLike, isFunctionNameChar, isFunctionNameCharStart, isHex, isQuote, isSingleQuote, isSingleQuoteLike, isSpecialWhitespace, isStartOfValue, isUnquotedStringDelimiter, isValidStringCharacter, isWhitespace, isWhitespaceExceptNewline, regexUrlChar, regexUrlStart } from '../utils/stringUtils.js'; +import { createInputBuffer } from './buffer/InputBuffer.js'; +import { createOutputBuffer } from './buffer/OutputBuffer.js'; +import { Caret, createStack, StackType } from './stack.js'; +const controlCharacters = { + '\b': '\\b', + '\f': '\\f', + '\n': '\\n', + '\r': '\\r', + '\t': '\\t' +}; + +// map with all escape characters +const escapeCharacters = { + '"': '"', + '\\': '\\', + '/': '/', + b: '\b', + f: '\f', + n: '\n', + r: '\r', + t: '\t' + // note that \u is handled separately in parseString() +}; +export function jsonrepairCore(_ref) { + let { + onData, + bufferSize = 65536, + chunkSize = 65536 + } = _ref; + const input = createInputBuffer(); + const output = createOutputBuffer({ + write: onData, + bufferSize, + chunkSize + }); + let i = 0; + let iFlushed = 0; + const stack = createStack(); + function flushInputBuffer() { + while (iFlushed < i - bufferSize - chunkSize) { + iFlushed += chunkSize; + input.flush(iFlushed); + } + } + function transform(chunk) { + input.push(chunk); + while (i < input.currentLength() - bufferSize && parse()) { + // loop until there is nothing more to process + } + flushInputBuffer(); + } + function flush() { + input.close(); + while (parse()) { + // loop until there is nothing more to process + } + output.flush(); + } + function parse() { + parseWhitespaceAndSkipComments(); + switch (stack.type) { + case StackType.object: + { + switch (stack.caret) { + case Caret.beforeKey: + return skipEllipsis() || parseObjectKey() || parseUnexpectedColon() || parseRepairTrailingComma() || parseRepairObjectEndOrComma(); + case Caret.beforeValue: + return parseValue() || parseRepairMissingObjectValue(); + case Caret.afterValue: + return parseObjectComma() || parseObjectEnd() || parseRepairObjectEndOrComma(); + default: + return false; + } + } + case StackType.array: + { + switch (stack.caret) { + case Caret.beforeValue: + return skipEllipsis() || parseValue() || parseRepairTrailingComma() || parseRepairArrayEnd(); + case Caret.afterValue: + return parseArrayComma() || parseArrayEnd() || parseRepairMissingComma() || parseRepairArrayEnd(); + default: + return false; + } + } + case StackType.ndJson: + { + switch (stack.caret) { + case Caret.beforeValue: + return parseValue() || parseRepairTrailingComma(); + case Caret.afterValue: + return parseArrayComma() || parseRepairMissingComma() || parseRepairNdJsonEnd(); + default: + return false; + } + } + case StackType.functionCall: + { + switch (stack.caret) { + case Caret.beforeValue: + return parseValue(); + case Caret.afterValue: + return parseFunctionCallEnd(); + default: + return false; + } + } + case StackType.root: + { + switch (stack.caret) { + case Caret.beforeValue: + return parseRootStart(); + case Caret.afterValue: + return parseRootEnd(); + default: + return false; + } + } + default: + return false; + } + } + function parseValue() { + return parseObjectStart() || parseArrayStart() || parseString() || parseNumber() || parseKeywords() || parseRepairUnquotedString() || parseRepairRegex(); + } + function parseObjectStart() { + if (parseCharacter('{')) { + parseWhitespaceAndSkipComments(); + skipEllipsis(); + if (skipCharacter(',')) { + parseWhitespaceAndSkipComments(); + } + if (parseCharacter('}')) { + return stack.update(Caret.afterValue); + } + return stack.push(StackType.object, Caret.beforeKey); + } + return false; + } + function parseArrayStart() { + if (parseCharacter('[')) { + parseWhitespaceAndSkipComments(); + skipEllipsis(); + if (skipCharacter(',')) { + parseWhitespaceAndSkipComments(); + } + if (parseCharacter(']')) { + return stack.update(Caret.afterValue); + } + return stack.push(StackType.array, Caret.beforeValue); + } + return false; + } + function parseRepairUnquotedString() { + let j = i; + if (isFunctionNameCharStart(input.charAt(j))) { + while (!input.isEnd(j) && isFunctionNameChar(input.charAt(j))) { + j++; + } + let k = j; + while (isWhitespace(input, k)) { + k++; + } + if (input.charAt(k) === '(') { + // repair a MongoDB function call like NumberLong("2") + // repair a JSONP function call like callback({...}); + k++; + i = k; + return stack.push(StackType.functionCall, Caret.beforeValue); + } + } + j = findNextDelimiter(false, j); + if (j !== null) { + // test start of an url like "https://..." (this would be parsed as a comment) + if (input.charAt(j - 1) === ':' && regexUrlStart.test(input.substring(i, j + 2))) { + while (!input.isEnd(j) && regexUrlChar.test(input.charAt(j))) { + j++; + } + } + const symbol = input.substring(i, j); + i = j; + output.push(symbol === 'undefined' ? 'null' : JSON.stringify(symbol)); + if (input.charAt(i) === '"') { + // we had a missing start quote, but now we encountered the end quote, so we can skip that one + i++; + } + return stack.update(Caret.afterValue); + } + return false; + } + function parseRepairRegex() { + if (input.charAt(i) === '/') { + const start = i; + i++; + while (!input.isEnd(i) && (input.charAt(i) !== '/' || input.charAt(i - 1) === '\\')) { + i++; + } + i++; + output.push(`"${input.substring(start, i)}"`); + return stack.update(Caret.afterValue); + } + } + function parseRepairMissingObjectValue() { + // repair missing object value + output.push('null'); + return stack.update(Caret.afterValue); + } + function parseRepairTrailingComma() { + // repair trailing comma + if (output.endsWithIgnoringWhitespace(',')) { + output.stripLastOccurrence(','); + return stack.update(Caret.afterValue); + } + return false; + } + function parseUnexpectedColon() { + if (input.charAt(i) === ':') { + throwObjectKeyExpected(); + } + return false; + } + function parseUnexpectedEnd() { + if (input.isEnd(i)) { + throwUnexpectedEnd(); + } else { + throwUnexpectedCharacter(); + } + return false; + } + function parseObjectKey() { + const parsedKey = parseString() || parseUnquotedKey(); + if (parsedKey) { + parseWhitespaceAndSkipComments(); + if (parseCharacter(':')) { + // expect a value after the : + return stack.update(Caret.beforeValue); + } + const truncatedText = input.isEnd(i); + if (isStartOfValue(input.charAt(i)) || truncatedText) { + // repair missing colon + output.insertBeforeLastWhitespace(':'); + return stack.update(Caret.beforeValue); + } + throwColonExpected(); + } + return false; + } + function parseObjectComma() { + if (parseCharacter(',')) { + return stack.update(Caret.beforeKey); + } + return false; + } + function parseObjectEnd() { + if (parseCharacter('}')) { + return stack.pop(); + } + return false; + } + function parseRepairObjectEndOrComma() { + // repair missing object end and trailing comma + if (input.charAt(i) === '{') { + output.stripLastOccurrence(','); + output.insertBeforeLastWhitespace('}'); + return stack.pop(); + } + + // repair missing comma + if (!input.isEnd(i) && isStartOfValue(input.charAt(i))) { + output.insertBeforeLastWhitespace(','); + return stack.update(Caret.beforeKey); + } + + // repair missing closing brace + output.insertBeforeLastWhitespace('}'); + return stack.pop(); + } + function parseArrayComma() { + if (parseCharacter(',')) { + return stack.update(Caret.beforeValue); + } + return false; + } + function parseArrayEnd() { + if (parseCharacter(']')) { + return stack.pop(); + } + return false; + } + function parseRepairMissingComma() { + // repair missing comma + if (!input.isEnd(i) && isStartOfValue(input.charAt(i))) { + output.insertBeforeLastWhitespace(','); + return stack.update(Caret.beforeValue); + } + return false; + } + function parseRepairArrayEnd() { + // repair missing closing bracket + output.insertBeforeLastWhitespace(']'); + return stack.pop(); + } + function parseRepairNdJsonEnd() { + if (input.isEnd(i)) { + output.push('\n]'); + return stack.pop(); + } + throwUnexpectedEnd(); + return false; // just to make TS happy + } + function parseFunctionCallEnd() { + if (skipCharacter(')')) { + skipCharacter(';'); + } + return stack.pop(); + } + function parseRootStart() { + parseMarkdownCodeBlock(['```', '[```', '{```']); + return parseValue() || parseUnexpectedEnd(); + } + function parseRootEnd() { + parseMarkdownCodeBlock(['```', '```]', '```}']); + const parsedComma = parseCharacter(','); + parseWhitespaceAndSkipComments(); + if (isStartOfValue(input.charAt(i)) && (output.endsWithIgnoringWhitespace(',') || output.endsWithIgnoringWhitespace('\n'))) { + // start of a new value after end of the root level object: looks like + // newline delimited JSON -> turn into a root level array + if (!parsedComma) { + // repair missing comma + output.insertBeforeLastWhitespace(','); + } + output.unshift('[\n'); + return stack.push(StackType.ndJson, Caret.beforeValue); + } + if (parsedComma) { + // repair: remove trailing comma + output.stripLastOccurrence(','); + return stack.update(Caret.afterValue); + } + + // repair redundant end braces and brackets + while (input.charAt(i) === '}' || input.charAt(i) === ']') { + i++; + parseWhitespaceAndSkipComments(); + } + if (!input.isEnd(i)) { + throwUnexpectedCharacter(); + } + return false; + } + function parseWhitespaceAndSkipComments() { + let skipNewline = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; + const start = i; + let changed = parseWhitespace(skipNewline); + do { + changed = parseComment(); + if (changed) { + changed = parseWhitespace(skipNewline); + } + } while (changed); + return i > start; + } + function parseWhitespace(skipNewline) { + const _isWhiteSpace = skipNewline ? isWhitespace : isWhitespaceExceptNewline; + let whitespace = ''; + while (true) { + if (_isWhiteSpace(input, i)) { + whitespace += input.charAt(i); + i++; + } else if (isSpecialWhitespace(input, i)) { + // repair special whitespace + whitespace += ' '; + i++; + } else { + break; + } + } + if (whitespace.length > 0) { + output.push(whitespace); + return true; + } + return false; + } + function parseComment() { + // find a block comment '/* ... */' + if (input.charAt(i) === '/' && input.charAt(i + 1) === '*') { + // repair block comment by skipping it + while (!input.isEnd(i) && !atEndOfBlockComment(i)) { + i++; + } + i += 2; + return true; + } + + // find a line comment '// ...' + if (input.charAt(i) === '/' && input.charAt(i + 1) === '/') { + // repair line comment by skipping it + while (!input.isEnd(i) && input.charAt(i) !== '\n') { + i++; + } + return true; + } + return false; + } + function parseMarkdownCodeBlock(blocks) { + // find and skip over a Markdown fenced code block: + // ``` ... ``` + // or + // ```json ... ``` + if (skipMarkdownCodeBlock(blocks)) { + if (isFunctionNameCharStart(input.charAt(i))) { + // strip the optional language specifier like "json" + while (!input.isEnd(i) && isFunctionNameChar(input.charAt(i))) { + i++; + } + } + parseWhitespaceAndSkipComments(); + return true; + } + return false; + } + function skipMarkdownCodeBlock(blocks) { + for (const block of blocks) { + const end = i + block.length; + if (input.substring(i, end) === block) { + i = end; + return true; + } + } + return false; + } + function parseCharacter(char) { + if (input.charAt(i) === char) { + output.push(input.charAt(i)); + i++; + return true; + } + return false; + } + function skipCharacter(char) { + if (input.charAt(i) === char) { + i++; + return true; + } + return false; + } + function skipEscapeCharacter() { + return skipCharacter('\\'); + } + + /** + * Skip ellipsis like "[1,2,3,...]" or "[1,2,3,...,9]" or "[...,7,8,9]" + * or a similar construct in objects. + */ + function skipEllipsis() { + parseWhitespaceAndSkipComments(); + if (input.charAt(i) === '.' && input.charAt(i + 1) === '.' && input.charAt(i + 2) === '.') { + // repair: remove the ellipsis (three dots) and optionally a comma + i += 3; + parseWhitespaceAndSkipComments(); + skipCharacter(','); + return true; + } + return false; + } + + /** + * Parse a string enclosed by double quotes "...". Can contain escaped quotes + * Repair strings enclosed in single quotes or special quotes + * Repair an escaped string + * + * The function can run in two stages: + * - First, it assumes the string has a valid end quote + * - If it turns out that the string does not have a valid end quote followed + * by a delimiter (which should be the case), the function runs again in a + * more conservative way, stopping the string at the first next delimiter + * and fixing the string by inserting a quote there, or stopping at a + * stop index detected in the first iteration. + */ + function parseString() { + let stopAtDelimiter = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + let stopAtIndex = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : -1; + let skipEscapeChars = input.charAt(i) === '\\'; + if (skipEscapeChars) { + // repair: remove the first escape character + i++; + skipEscapeChars = true; + } + if (isQuote(input.charAt(i))) { + // double quotes are correct JSON, + // single quotes come from JavaScript for example, we assume it will have a correct single end quote too + // otherwise, we will match any double-quote-like start with a double-quote-like end, + // or any single-quote-like start with a single-quote-like end + const isEndQuote = isDoubleQuote(input.charAt(i)) ? isDoubleQuote : isSingleQuote(input.charAt(i)) ? isSingleQuote : isSingleQuoteLike(input.charAt(i)) ? isSingleQuoteLike : isDoubleQuoteLike; + const iBefore = i; + const oBefore = output.length(); + output.push('"'); + i++; + while (true) { + if (input.isEnd(i)) { + // end of text, we have a missing quote somewhere + + const iPrev = prevNonWhitespaceIndex(i - 1); + if (!stopAtDelimiter && isDelimiter(input.charAt(iPrev))) { + // if the text ends with a delimiter, like ["hello], + // so the missing end quote should be inserted before this delimiter + // retry parsing the string, stopping at the first next delimiter + i = iBefore; + output.remove(oBefore); + return parseString(true); + } + + // repair missing quote + output.insertBeforeLastWhitespace('"'); + return stack.update(Caret.afterValue); + } + if (i === stopAtIndex) { + // use the stop index detected in the first iteration, and repair end quote + output.insertBeforeLastWhitespace('"'); + return stack.update(Caret.afterValue); + } + if (isEndQuote(input.charAt(i))) { + // end quote + // let us check what is before and after the quote to verify whether this is a legit end quote + const iQuote = i; + const oQuote = output.length(); + output.push('"'); + i++; + parseWhitespaceAndSkipComments(false); + if (stopAtDelimiter || input.isEnd(i) || isDelimiter(input.charAt(i)) || isQuote(input.charAt(i)) || isDigit(input.charAt(i))) { + // The quote is followed by the end of the text, a delimiter, or a next value + // so the quote is indeed the end of the string + parseConcatenatedString(); + return stack.update(Caret.afterValue); + } + const iPrevChar = prevNonWhitespaceIndex(iQuote - 1); + const prevChar = input.charAt(iPrevChar); + if (prevChar === ',') { + // A comma followed by a quote, like '{"a":"b,c,"d":"e"}'. + // We assume that the quote is a start quote, and that the end quote + // should have been located right before the comma but is missing. + i = iBefore; + output.remove(oBefore); + return parseString(false, iPrevChar); + } + if (isDelimiter(prevChar)) { + // This is not the right end quote: it is preceded by a delimiter, + // and NOT followed by a delimiter. So, there is an end quote missing + // parse the string again and then stop at the first next delimiter + i = iBefore; + output.remove(oBefore); + return parseString(true); + } + + // revert to right after the quote but before any whitespace, and continue parsing the string + output.remove(oQuote + 1); + i = iQuote + 1; + + // repair unescaped quote + output.insertAt(oQuote, '\\'); + } else if (stopAtDelimiter && isUnquotedStringDelimiter(input.charAt(i))) { + // we're in the mode to stop the string at the first delimiter + // because there is an end quote missing + + // test start of an url like "https://..." (this would be parsed as a comment) + if (input.charAt(i - 1) === ':' && regexUrlStart.test(input.substring(iBefore + 1, i + 2))) { + while (!input.isEnd(i) && regexUrlChar.test(input.charAt(i))) { + output.push(input.charAt(i)); + i++; + } + } + + // repair missing quote + output.insertBeforeLastWhitespace('"'); + parseConcatenatedString(); + return stack.update(Caret.afterValue); + } else if (input.charAt(i) === '\\') { + // handle escaped content like \n or \u2605 + const char = input.charAt(i + 1); + const escapeChar = escapeCharacters[char]; + if (escapeChar !== undefined) { + output.push(input.substring(i, i + 2)); + i += 2; + } else if (char === 'u') { + let j = 2; + while (j < 6 && isHex(input.charAt(i + j))) { + j++; + } + if (j === 6) { + output.push(input.substring(i, i + 6)); + i += 6; + } else if (input.isEnd(i + j)) { + // repair invalid or truncated unicode char at the end of the text + // by removing the unicode char and ending the string here + i += j; + } else { + throwInvalidUnicodeCharacter(); + } + } else { + // repair invalid escape character: remove it + output.push(char); + i += 2; + } + } else { + // handle regular characters + const char = input.charAt(i); + if (char === '"' && input.charAt(i - 1) !== '\\') { + // repair unescaped double quote + output.push(`\\${char}`); + i++; + } else if (isControlCharacter(char)) { + // unescaped control character + output.push(controlCharacters[char]); + i++; + } else { + if (!isValidStringCharacter(char)) { + throwInvalidCharacter(char); + } + output.push(char); + i++; + } + } + if (skipEscapeChars) { + // repair: skipped escape character (nothing to do) + skipEscapeCharacter(); + } + } + } + return false; + } + + /** + * Repair concatenated strings like "hello" + "world", change this into "helloworld" + */ + function parseConcatenatedString() { + let parsed = false; + parseWhitespaceAndSkipComments(); + while (input.charAt(i) === '+') { + parsed = true; + i++; + parseWhitespaceAndSkipComments(); + + // repair: remove the end quote of the first string + output.stripLastOccurrence('"', true); + const start = output.length(); + const parsedStr = parseString(); + if (parsedStr) { + // repair: remove the start quote of the second string + output.remove(start, start + 1); + } else { + // repair: remove the + because it is not followed by a string + output.insertBeforeLastWhitespace('"'); + } + } + return parsed; + } + + /** + * Parse a number like 2.4 or 2.4e6 + */ + function parseNumber() { + const start = i; + if (input.charAt(i) === '-') { + i++; + if (atEndOfNumber()) { + repairNumberEndingWithNumericSymbol(start); + return stack.update(Caret.afterValue); + } + if (!isDigit(input.charAt(i))) { + i = start; + return false; + } + } + + // Note that in JSON leading zeros like "00789" are not allowed. + // We will allow all leading zeros here though and at the end of parseNumber + // check against trailing zeros and repair that if needed. + // Leading zeros can have meaning, so we should not clear them. + while (isDigit(input.charAt(i))) { + i++; + } + if (input.charAt(i) === '.') { + i++; + if (atEndOfNumber()) { + repairNumberEndingWithNumericSymbol(start); + return stack.update(Caret.afterValue); + } + if (!isDigit(input.charAt(i))) { + i = start; + return false; + } + while (isDigit(input.charAt(i))) { + i++; + } + } + if (input.charAt(i) === 'e' || input.charAt(i) === 'E') { + i++; + if (input.charAt(i) === '-' || input.charAt(i) === '+') { + i++; + } + if (atEndOfNumber()) { + repairNumberEndingWithNumericSymbol(start); + return stack.update(Caret.afterValue); + } + if (!isDigit(input.charAt(i))) { + i = start; + return false; + } + while (isDigit(input.charAt(i))) { + i++; + } + } + + // if we're not at the end of the number by this point, allow this to be parsed as another type + if (!atEndOfNumber()) { + i = start; + return false; + } + if (i > start) { + // repair a number with leading zeros like "00789" + const num = input.substring(start, i); + const hasInvalidLeadingZero = /^0\d/.test(num); + output.push(hasInvalidLeadingZero ? `"${num}"` : num); + return stack.update(Caret.afterValue); + } + return false; + } + + /** + * Parse keywords true, false, null + * Repair Python keywords True, False, None + */ + function parseKeywords() { + return parseKeyword('true', 'true') || parseKeyword('false', 'false') || parseKeyword('null', 'null') || + // repair Python keywords True, False, None + parseKeyword('True', 'true') || parseKeyword('False', 'false') || parseKeyword('None', 'null'); + } + function parseKeyword(name, value) { + if (input.substring(i, i + name.length) === name) { + output.push(value); + i += name.length; + return stack.update(Caret.afterValue); + } + return false; + } + function parseUnquotedKey() { + let end = findNextDelimiter(true, i); + if (end !== null) { + // first, go back to prevent getting trailing whitespaces in the string + while (isWhitespace(input, end - 1) && end > i) { + end--; + } + const symbol = input.substring(i, end); + output.push(JSON.stringify(symbol)); + i = end; + if (input.charAt(i) === '"') { + // we had a missing start quote, but now we encountered the end quote, so we can skip that one + i++; + } + return stack.update(Caret.afterValue); // we do not have a state Caret.afterKey, therefore we use afterValue here + } + return false; + } + function findNextDelimiter(isKey, start) { + // note that the symbol can end with whitespaces: we stop at the next delimiter + // also, note that we allow strings to contain a slash / in order to support repairing regular expressions + let j = start; + while (!input.isEnd(j) && !isUnquotedStringDelimiter(input.charAt(j)) && !isQuote(input.charAt(j)) && (!isKey || input.charAt(j) !== ':')) { + j++; + } + return j > i ? j : null; + } + function prevNonWhitespaceIndex(start) { + let prev = start; + while (prev > 0 && isWhitespace(input, prev)) { + prev--; + } + return prev; + } + function atEndOfNumber() { + return input.isEnd(i) || isDelimiter(input.charAt(i)) || isWhitespace(input, i); + } + function repairNumberEndingWithNumericSymbol(start) { + // repair numbers cut off at the end + // this will only be called when we end after a '.', '-', or 'e' and does not + // change the number more than it needs to make it valid JSON + output.push(`${input.substring(start, i)}0`); + } + function throwInvalidCharacter(char) { + throw new JSONRepairError(`Invalid character ${JSON.stringify(char)}`, i); + } + function throwUnexpectedCharacter() { + throw new JSONRepairError(`Unexpected character ${JSON.stringify(input.charAt(i))}`, i); + } + function throwUnexpectedEnd() { + throw new JSONRepairError('Unexpected end of json string', i); + } + function throwObjectKeyExpected() { + throw new JSONRepairError('Object key expected', i); + } + function throwColonExpected() { + throw new JSONRepairError('Colon expected', i); + } + function throwInvalidUnicodeCharacter() { + const chars = input.substring(i, i + 6); + throw new JSONRepairError(`Invalid unicode character "${chars}"`, i); + } + function atEndOfBlockComment(i) { + return input.charAt(i) === '*' && input.charAt(i + 1) === '/'; + } + return { + transform, + flush + }; +} +//# sourceMappingURL=core.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/streaming/core.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/streaming/core.js.map new file mode 100644 index 0000000000000000000000000000000000000000..60ff7194a5a938d435dabdf9116bf1e2346d1fc5 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/streaming/core.js.map @@ -0,0 +1 @@ +{"version":3,"file":"core.js","names":["JSONRepairError","isControlCharacter","isDelimiter","isDigit","isDoubleQuote","isDoubleQuoteLike","isFunctionNameChar","isFunctionNameCharStart","isHex","isQuote","isSingleQuote","isSingleQuoteLike","isSpecialWhitespace","isStartOfValue","isUnquotedStringDelimiter","isValidStringCharacter","isWhitespace","isWhitespaceExceptNewline","regexUrlChar","regexUrlStart","createInputBuffer","createOutputBuffer","Caret","createStack","StackType","controlCharacters","escapeCharacters","b","f","n","r","t","jsonrepairCore","_ref","onData","bufferSize","chunkSize","input","output","write","i","iFlushed","stack","flushInputBuffer","flush","transform","chunk","push","currentLength","parse","close","parseWhitespaceAndSkipComments","type","object","caret","beforeKey","skipEllipsis","parseObjectKey","parseUnexpectedColon","parseRepairTrailingComma","parseRepairObjectEndOrComma","beforeValue","parseValue","parseRepairMissingObjectValue","afterValue","parseObjectComma","parseObjectEnd","array","parseRepairArrayEnd","parseArrayComma","parseArrayEnd","parseRepairMissingComma","ndJson","parseRepairNdJsonEnd","functionCall","parseFunctionCallEnd","root","parseRootStart","parseRootEnd","parseObjectStart","parseArrayStart","parseString","parseNumber","parseKeywords","parseRepairUnquotedString","parseRepairRegex","parseCharacter","skipCharacter","update","j","charAt","isEnd","k","findNextDelimiter","test","substring","symbol","JSON","stringify","start","endsWithIgnoringWhitespace","stripLastOccurrence","throwObjectKeyExpected","parseUnexpectedEnd","throwUnexpectedEnd","throwUnexpectedCharacter","parsedKey","parseUnquotedKey","truncatedText","insertBeforeLastWhitespace","throwColonExpected","pop","parseMarkdownCodeBlock","parsedComma","unshift","skipNewline","arguments","length","undefined","changed","parseWhitespace","parseComment","_isWhiteSpace","whitespace","atEndOfBlockComment","blocks","skipMarkdownCodeBlock","block","end","char","skipEscapeCharacter","stopAtDelimiter","stopAtIndex","skipEscapeChars","isEndQuote","iBefore","oBefore","iPrev","prevNonWhitespaceIndex","remove","iQuote","oQuote","parseConcatenatedString","iPrevChar","prevChar","insertAt","escapeChar","throwInvalidUnicodeCharacter","throwInvalidCharacter","parsed","parsedStr","atEndOfNumber","repairNumberEndingWithNumericSymbol","num","hasInvalidLeadingZero","parseKeyword","name","value","isKey","prev","chars"],"sources":["../../../src/streaming/core.ts"],"sourcesContent":["import { JSONRepairError } from '../utils/JSONRepairError.js'\nimport {\n isControlCharacter,\n isDelimiter,\n isDigit,\n isDoubleQuote,\n isDoubleQuoteLike,\n isFunctionNameChar,\n isFunctionNameCharStart,\n isHex,\n isQuote,\n isSingleQuote,\n isSingleQuoteLike,\n isSpecialWhitespace,\n isStartOfValue,\n isUnquotedStringDelimiter,\n isValidStringCharacter,\n isWhitespace,\n isWhitespaceExceptNewline,\n regexUrlChar,\n regexUrlStart\n} from '../utils/stringUtils.js'\nimport { createInputBuffer } from './buffer/InputBuffer.js'\nimport { createOutputBuffer } from './buffer/OutputBuffer.js'\nimport { Caret, createStack, StackType } from './stack.js'\n\nconst controlCharacters: { [key: string]: string } = {\n '\\b': '\\\\b',\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t'\n}\n\n// map with all escape characters\nconst escapeCharacters: { [key: string]: string } = {\n '\"': '\"',\n '\\\\': '\\\\',\n '/': '/',\n b: '\\b',\n f: '\\f',\n n: '\\n',\n r: '\\r',\n t: '\\t'\n // note that \\u is handled separately in parseString()\n}\n\nexport interface JsonRepairCoreOptions {\n onData: (chunk: string) => void\n chunkSize?: number\n bufferSize?: number\n}\n\nexport interface JsonRepairCore {\n transform: (chunk: string) => void\n flush: () => void\n}\n\nexport function jsonrepairCore({\n onData,\n bufferSize = 65536,\n chunkSize = 65536\n}: JsonRepairCoreOptions): JsonRepairCore {\n const input = createInputBuffer()\n\n const output = createOutputBuffer({\n write: onData,\n bufferSize,\n chunkSize\n })\n\n let i = 0\n let iFlushed = 0\n const stack = createStack()\n\n function flushInputBuffer() {\n while (iFlushed < i - bufferSize - chunkSize) {\n iFlushed += chunkSize\n input.flush(iFlushed)\n }\n }\n\n function transform(chunk: string) {\n input.push(chunk)\n\n while (i < input.currentLength() - bufferSize && parse()) {\n // loop until there is nothing more to process\n }\n\n flushInputBuffer()\n }\n\n function flush() {\n input.close()\n\n while (parse()) {\n // loop until there is nothing more to process\n }\n\n output.flush()\n }\n\n function parse(): boolean {\n parseWhitespaceAndSkipComments()\n\n switch (stack.type) {\n case StackType.object: {\n switch (stack.caret) {\n case Caret.beforeKey:\n return (\n skipEllipsis() ||\n parseObjectKey() ||\n parseUnexpectedColon() ||\n parseRepairTrailingComma() ||\n parseRepairObjectEndOrComma()\n )\n case Caret.beforeValue:\n return parseValue() || parseRepairMissingObjectValue()\n case Caret.afterValue:\n return parseObjectComma() || parseObjectEnd() || parseRepairObjectEndOrComma()\n default:\n return false\n }\n }\n\n case StackType.array: {\n switch (stack.caret) {\n case Caret.beforeValue:\n return (\n skipEllipsis() || parseValue() || parseRepairTrailingComma() || parseRepairArrayEnd()\n )\n case Caret.afterValue:\n return (\n parseArrayComma() ||\n parseArrayEnd() ||\n parseRepairMissingComma() ||\n parseRepairArrayEnd()\n )\n default:\n return false\n }\n }\n\n case StackType.ndJson: {\n switch (stack.caret) {\n case Caret.beforeValue:\n return parseValue() || parseRepairTrailingComma()\n case Caret.afterValue:\n return parseArrayComma() || parseRepairMissingComma() || parseRepairNdJsonEnd()\n default:\n return false\n }\n }\n\n case StackType.functionCall: {\n switch (stack.caret) {\n case Caret.beforeValue:\n return parseValue()\n case Caret.afterValue:\n return parseFunctionCallEnd()\n default:\n return false\n }\n }\n\n case StackType.root: {\n switch (stack.caret) {\n case Caret.beforeValue:\n return parseRootStart()\n case Caret.afterValue:\n return parseRootEnd()\n default:\n return false\n }\n }\n\n default:\n return false\n }\n }\n\n function parseValue(): boolean {\n return (\n parseObjectStart() ||\n parseArrayStart() ||\n parseString() ||\n parseNumber() ||\n parseKeywords() ||\n parseRepairUnquotedString() ||\n parseRepairRegex()\n )\n }\n\n function parseObjectStart(): boolean {\n if (parseCharacter('{')) {\n parseWhitespaceAndSkipComments()\n\n skipEllipsis()\n\n if (skipCharacter(',')) {\n parseWhitespaceAndSkipComments()\n }\n\n if (parseCharacter('}')) {\n return stack.update(Caret.afterValue)\n }\n\n return stack.push(StackType.object, Caret.beforeKey)\n }\n\n return false\n }\n\n function parseArrayStart(): boolean {\n if (parseCharacter('[')) {\n parseWhitespaceAndSkipComments()\n\n skipEllipsis()\n\n if (skipCharacter(',')) {\n parseWhitespaceAndSkipComments()\n }\n\n if (parseCharacter(']')) {\n return stack.update(Caret.afterValue)\n }\n\n return stack.push(StackType.array, Caret.beforeValue)\n }\n\n return false\n }\n\n function parseRepairUnquotedString(): boolean {\n let j = i\n\n if (isFunctionNameCharStart(input.charAt(j))) {\n while (!input.isEnd(j) && isFunctionNameChar(input.charAt(j))) {\n j++\n }\n\n let k = j\n while (isWhitespace(input, k)) {\n k++\n }\n\n if (input.charAt(k) === '(') {\n // repair a MongoDB function call like NumberLong(\"2\")\n // repair a JSONP function call like callback({...});\n k++\n i = k\n return stack.push(StackType.functionCall, Caret.beforeValue)\n }\n }\n\n j = findNextDelimiter(false, j)\n if (j !== null) {\n // test start of an url like \"https://...\" (this would be parsed as a comment)\n if (input.charAt(j - 1) === ':' && regexUrlStart.test(input.substring(i, j + 2))) {\n while (!input.isEnd(j) && regexUrlChar.test(input.charAt(j))) {\n j++\n }\n }\n\n const symbol = input.substring(i, j)\n i = j\n\n output.push(symbol === 'undefined' ? 'null' : JSON.stringify(symbol))\n\n if (input.charAt(i) === '\"') {\n // we had a missing start quote, but now we encountered the end quote, so we can skip that one\n i++\n }\n\n return stack.update(Caret.afterValue)\n }\n\n return false\n }\n\n function parseRepairRegex() {\n if (input.charAt(i) === '/') {\n const start = i\n i++\n\n while (!input.isEnd(i) && (input.charAt(i) !== '/' || input.charAt(i - 1) === '\\\\')) {\n i++\n }\n i++\n\n output.push(`\"${input.substring(start, i)}\"`)\n\n return stack.update(Caret.afterValue)\n }\n }\n\n function parseRepairMissingObjectValue(): boolean {\n // repair missing object value\n output.push('null')\n return stack.update(Caret.afterValue)\n }\n\n function parseRepairTrailingComma(): boolean {\n // repair trailing comma\n if (output.endsWithIgnoringWhitespace(',')) {\n output.stripLastOccurrence(',')\n return stack.update(Caret.afterValue)\n }\n\n return false\n }\n\n function parseUnexpectedColon(): boolean {\n if (input.charAt(i) === ':') {\n throwObjectKeyExpected()\n }\n\n return false\n }\n\n function parseUnexpectedEnd(): boolean {\n if (input.isEnd(i)) {\n throwUnexpectedEnd()\n } else {\n throwUnexpectedCharacter()\n }\n\n return false\n }\n\n function parseObjectKey(): boolean {\n const parsedKey = parseString() || parseUnquotedKey()\n if (parsedKey) {\n parseWhitespaceAndSkipComments()\n\n if (parseCharacter(':')) {\n // expect a value after the :\n return stack.update(Caret.beforeValue)\n }\n\n const truncatedText = input.isEnd(i)\n if (isStartOfValue(input.charAt(i)) || truncatedText) {\n // repair missing colon\n output.insertBeforeLastWhitespace(':')\n return stack.update(Caret.beforeValue)\n }\n\n throwColonExpected()\n }\n\n return false\n }\n\n function parseObjectComma(): boolean {\n if (parseCharacter(',')) {\n return stack.update(Caret.beforeKey)\n }\n\n return false\n }\n\n function parseObjectEnd(): boolean {\n if (parseCharacter('}')) {\n return stack.pop()\n }\n\n return false\n }\n\n function parseRepairObjectEndOrComma(): true {\n // repair missing object end and trailing comma\n if (input.charAt(i) === '{') {\n output.stripLastOccurrence(',')\n output.insertBeforeLastWhitespace('}')\n return stack.pop()\n }\n\n // repair missing comma\n if (!input.isEnd(i) && isStartOfValue(input.charAt(i))) {\n output.insertBeforeLastWhitespace(',')\n return stack.update(Caret.beforeKey)\n }\n\n // repair missing closing brace\n output.insertBeforeLastWhitespace('}')\n return stack.pop()\n }\n\n function parseArrayComma(): boolean {\n if (parseCharacter(',')) {\n return stack.update(Caret.beforeValue)\n }\n\n return false\n }\n\n function parseArrayEnd(): boolean {\n if (parseCharacter(']')) {\n return stack.pop()\n }\n\n return false\n }\n\n function parseRepairMissingComma(): boolean {\n // repair missing comma\n if (!input.isEnd(i) && isStartOfValue(input.charAt(i))) {\n output.insertBeforeLastWhitespace(',')\n return stack.update(Caret.beforeValue)\n }\n\n return false\n }\n\n function parseRepairArrayEnd(): true {\n // repair missing closing bracket\n output.insertBeforeLastWhitespace(']')\n return stack.pop()\n }\n\n function parseRepairNdJsonEnd(): boolean {\n if (input.isEnd(i)) {\n output.push('\\n]')\n return stack.pop()\n }\n\n throwUnexpectedEnd()\n return false // just to make TS happy\n }\n\n function parseFunctionCallEnd(): true {\n if (skipCharacter(')')) {\n skipCharacter(';')\n }\n\n return stack.pop()\n }\n\n function parseRootStart(): boolean {\n parseMarkdownCodeBlock(['```', '[```', '{```'])\n\n return parseValue() || parseUnexpectedEnd()\n }\n\n function parseRootEnd(): boolean {\n parseMarkdownCodeBlock(['```', '```]', '```}'])\n\n const parsedComma = parseCharacter(',')\n parseWhitespaceAndSkipComments()\n\n if (\n isStartOfValue(input.charAt(i)) &&\n (output.endsWithIgnoringWhitespace(',') || output.endsWithIgnoringWhitespace('\\n'))\n ) {\n // start of a new value after end of the root level object: looks like\n // newline delimited JSON -> turn into a root level array\n if (!parsedComma) {\n // repair missing comma\n output.insertBeforeLastWhitespace(',')\n }\n\n output.unshift('[\\n')\n\n return stack.push(StackType.ndJson, Caret.beforeValue)\n }\n\n if (parsedComma) {\n // repair: remove trailing comma\n output.stripLastOccurrence(',')\n\n return stack.update(Caret.afterValue)\n }\n\n // repair redundant end braces and brackets\n while (input.charAt(i) === '}' || input.charAt(i) === ']') {\n i++\n parseWhitespaceAndSkipComments()\n }\n\n if (!input.isEnd(i)) {\n throwUnexpectedCharacter()\n }\n\n return false\n }\n\n function parseWhitespaceAndSkipComments(skipNewline = true): boolean {\n const start = i\n\n let changed = parseWhitespace(skipNewline)\n do {\n changed = parseComment()\n if (changed) {\n changed = parseWhitespace(skipNewline)\n }\n } while (changed)\n\n return i > start\n }\n\n function parseWhitespace(skipNewline: boolean): boolean {\n const _isWhiteSpace = skipNewline ? isWhitespace : isWhitespaceExceptNewline\n let whitespace = ''\n\n while (true) {\n if (_isWhiteSpace(input, i)) {\n whitespace += input.charAt(i)\n i++\n } else if (isSpecialWhitespace(input, i)) {\n // repair special whitespace\n whitespace += ' '\n i++\n } else {\n break\n }\n }\n\n if (whitespace.length > 0) {\n output.push(whitespace)\n return true\n }\n\n return false\n }\n\n function parseComment(): boolean {\n // find a block comment '/* ... */'\n if (input.charAt(i) === '/' && input.charAt(i + 1) === '*') {\n // repair block comment by skipping it\n while (!input.isEnd(i) && !atEndOfBlockComment(i)) {\n i++\n }\n i += 2\n\n return true\n }\n\n // find a line comment '// ...'\n if (input.charAt(i) === '/' && input.charAt(i + 1) === '/') {\n // repair line comment by skipping it\n while (!input.isEnd(i) && input.charAt(i) !== '\\n') {\n i++\n }\n\n return true\n }\n\n return false\n }\n\n function parseMarkdownCodeBlock(blocks: string[]): boolean {\n // find and skip over a Markdown fenced code block:\n // ``` ... ```\n // or\n // ```json ... ```\n if (skipMarkdownCodeBlock(blocks)) {\n if (isFunctionNameCharStart(input.charAt(i))) {\n // strip the optional language specifier like \"json\"\n while (!input.isEnd(i) && isFunctionNameChar(input.charAt(i))) {\n i++\n }\n }\n\n parseWhitespaceAndSkipComments()\n\n return true\n }\n\n return false\n }\n\n function skipMarkdownCodeBlock(blocks: string[]): boolean {\n for (const block of blocks) {\n const end = i + block.length\n if (input.substring(i, end) === block) {\n i = end\n return true\n }\n }\n\n return false\n }\n\n function parseCharacter(char: string): boolean {\n if (input.charAt(i) === char) {\n output.push(input.charAt(i))\n i++\n return true\n }\n\n return false\n }\n\n function skipCharacter(char: string): boolean {\n if (input.charAt(i) === char) {\n i++\n return true\n }\n\n return false\n }\n\n function skipEscapeCharacter(): boolean {\n return skipCharacter('\\\\')\n }\n\n /**\n * Skip ellipsis like \"[1,2,3,...]\" or \"[1,2,3,...,9]\" or \"[...,7,8,9]\"\n * or a similar construct in objects.\n */\n function skipEllipsis(): boolean {\n parseWhitespaceAndSkipComments()\n\n if (input.charAt(i) === '.' && input.charAt(i + 1) === '.' && input.charAt(i + 2) === '.') {\n // repair: remove the ellipsis (three dots) and optionally a comma\n i += 3\n parseWhitespaceAndSkipComments()\n skipCharacter(',')\n\n return true\n }\n\n return false\n }\n\n /**\n * Parse a string enclosed by double quotes \"...\". Can contain escaped quotes\n * Repair strings enclosed in single quotes or special quotes\n * Repair an escaped string\n *\n * The function can run in two stages:\n * - First, it assumes the string has a valid end quote\n * - If it turns out that the string does not have a valid end quote followed\n * by a delimiter (which should be the case), the function runs again in a\n * more conservative way, stopping the string at the first next delimiter\n * and fixing the string by inserting a quote there, or stopping at a\n * stop index detected in the first iteration.\n */\n function parseString(stopAtDelimiter = false, stopAtIndex = -1): boolean {\n let skipEscapeChars = input.charAt(i) === '\\\\'\n if (skipEscapeChars) {\n // repair: remove the first escape character\n i++\n skipEscapeChars = true\n }\n\n if (isQuote(input.charAt(i))) {\n // double quotes are correct JSON,\n // single quotes come from JavaScript for example, we assume it will have a correct single end quote too\n // otherwise, we will match any double-quote-like start with a double-quote-like end,\n // or any single-quote-like start with a single-quote-like end\n const isEndQuote = isDoubleQuote(input.charAt(i))\n ? isDoubleQuote\n : isSingleQuote(input.charAt(i))\n ? isSingleQuote\n : isSingleQuoteLike(input.charAt(i))\n ? isSingleQuoteLike\n : isDoubleQuoteLike\n\n const iBefore = i\n const oBefore = output.length()\n\n output.push('\"')\n i++\n\n while (true) {\n if (input.isEnd(i)) {\n // end of text, we have a missing quote somewhere\n\n const iPrev = prevNonWhitespaceIndex(i - 1)\n if (!stopAtDelimiter && isDelimiter(input.charAt(iPrev))) {\n // if the text ends with a delimiter, like [\"hello],\n // so the missing end quote should be inserted before this delimiter\n // retry parsing the string, stopping at the first next delimiter\n i = iBefore\n output.remove(oBefore)\n\n return parseString(true)\n }\n\n // repair missing quote\n output.insertBeforeLastWhitespace('\"')\n\n return stack.update(Caret.afterValue)\n }\n\n if (i === stopAtIndex) {\n // use the stop index detected in the first iteration, and repair end quote\n output.insertBeforeLastWhitespace('\"')\n\n return stack.update(Caret.afterValue)\n }\n\n if (isEndQuote(input.charAt(i))) {\n // end quote\n // let us check what is before and after the quote to verify whether this is a legit end quote\n const iQuote = i\n const oQuote = output.length()\n output.push('\"')\n i++\n\n parseWhitespaceAndSkipComments(false)\n\n if (\n stopAtDelimiter ||\n input.isEnd(i) ||\n isDelimiter(input.charAt(i)) ||\n isQuote(input.charAt(i)) ||\n isDigit(input.charAt(i))\n ) {\n // The quote is followed by the end of the text, a delimiter, or a next value\n // so the quote is indeed the end of the string\n parseConcatenatedString()\n\n return stack.update(Caret.afterValue)\n }\n\n const iPrevChar = prevNonWhitespaceIndex(iQuote - 1)\n const prevChar = input.charAt(iPrevChar)\n\n if (prevChar === ',') {\n // A comma followed by a quote, like '{\"a\":\"b,c,\"d\":\"e\"}'.\n // We assume that the quote is a start quote, and that the end quote\n // should have been located right before the comma but is missing.\n i = iBefore\n output.remove(oBefore)\n\n return parseString(false, iPrevChar)\n }\n\n if (isDelimiter(prevChar)) {\n // This is not the right end quote: it is preceded by a delimiter,\n // and NOT followed by a delimiter. So, there is an end quote missing\n // parse the string again and then stop at the first next delimiter\n i = iBefore\n output.remove(oBefore)\n\n return parseString(true)\n }\n\n // revert to right after the quote but before any whitespace, and continue parsing the string\n output.remove(oQuote + 1)\n i = iQuote + 1\n\n // repair unescaped quote\n output.insertAt(oQuote, '\\\\')\n } else if (stopAtDelimiter && isUnquotedStringDelimiter(input.charAt(i))) {\n // we're in the mode to stop the string at the first delimiter\n // because there is an end quote missing\n\n // test start of an url like \"https://...\" (this would be parsed as a comment)\n if (\n input.charAt(i - 1) === ':' &&\n regexUrlStart.test(input.substring(iBefore + 1, i + 2))\n ) {\n while (!input.isEnd(i) && regexUrlChar.test(input.charAt(i))) {\n output.push(input.charAt(i))\n i++\n }\n }\n\n // repair missing quote\n output.insertBeforeLastWhitespace('\"')\n\n parseConcatenatedString()\n\n return stack.update(Caret.afterValue)\n } else if (input.charAt(i) === '\\\\') {\n // handle escaped content like \\n or \\u2605\n const char = input.charAt(i + 1)\n const escapeChar = escapeCharacters[char]\n if (escapeChar !== undefined) {\n output.push(input.substring(i, i + 2))\n i += 2\n } else if (char === 'u') {\n let j = 2\n while (j < 6 && isHex(input.charAt(i + j))) {\n j++\n }\n\n if (j === 6) {\n output.push(input.substring(i, i + 6))\n i += 6\n } else if (input.isEnd(i + j)) {\n // repair invalid or truncated unicode char at the end of the text\n // by removing the unicode char and ending the string here\n i += j\n } else {\n throwInvalidUnicodeCharacter()\n }\n } else {\n // repair invalid escape character: remove it\n output.push(char)\n i += 2\n }\n } else {\n // handle regular characters\n const char = input.charAt(i)\n\n if (char === '\"' && input.charAt(i - 1) !== '\\\\') {\n // repair unescaped double quote\n output.push(`\\\\${char}`)\n i++\n } else if (isControlCharacter(char)) {\n // unescaped control character\n output.push(controlCharacters[char])\n i++\n } else {\n if (!isValidStringCharacter(char)) {\n throwInvalidCharacter(char)\n }\n output.push(char)\n i++\n }\n }\n\n if (skipEscapeChars) {\n // repair: skipped escape character (nothing to do)\n skipEscapeCharacter()\n }\n }\n }\n\n return false\n }\n\n /**\n * Repair concatenated strings like \"hello\" + \"world\", change this into \"helloworld\"\n */\n function parseConcatenatedString(): boolean {\n let parsed = false\n\n parseWhitespaceAndSkipComments()\n while (input.charAt(i) === '+') {\n parsed = true\n i++\n parseWhitespaceAndSkipComments()\n\n // repair: remove the end quote of the first string\n output.stripLastOccurrence('\"', true)\n const start = output.length()\n const parsedStr = parseString()\n if (parsedStr) {\n // repair: remove the start quote of the second string\n output.remove(start, start + 1)\n } else {\n // repair: remove the + because it is not followed by a string\n output.insertBeforeLastWhitespace('\"')\n }\n }\n\n return parsed\n }\n\n /**\n * Parse a number like 2.4 or 2.4e6\n */\n function parseNumber(): boolean {\n const start = i\n if (input.charAt(i) === '-') {\n i++\n if (atEndOfNumber()) {\n repairNumberEndingWithNumericSymbol(start)\n return stack.update(Caret.afterValue)\n }\n if (!isDigit(input.charAt(i))) {\n i = start\n return false\n }\n }\n\n // Note that in JSON leading zeros like \"00789\" are not allowed.\n // We will allow all leading zeros here though and at the end of parseNumber\n // check against trailing zeros and repair that if needed.\n // Leading zeros can have meaning, so we should not clear them.\n while (isDigit(input.charAt(i))) {\n i++\n }\n\n if (input.charAt(i) === '.') {\n i++\n if (atEndOfNumber()) {\n repairNumberEndingWithNumericSymbol(start)\n return stack.update(Caret.afterValue)\n }\n if (!isDigit(input.charAt(i))) {\n i = start\n return false\n }\n while (isDigit(input.charAt(i))) {\n i++\n }\n }\n\n if (input.charAt(i) === 'e' || input.charAt(i) === 'E') {\n i++\n if (input.charAt(i) === '-' || input.charAt(i) === '+') {\n i++\n }\n if (atEndOfNumber()) {\n repairNumberEndingWithNumericSymbol(start)\n return stack.update(Caret.afterValue)\n }\n if (!isDigit(input.charAt(i))) {\n i = start\n return false\n }\n while (isDigit(input.charAt(i))) {\n i++\n }\n }\n\n // if we're not at the end of the number by this point, allow this to be parsed as another type\n if (!atEndOfNumber()) {\n i = start\n return false\n }\n\n if (i > start) {\n // repair a number with leading zeros like \"00789\"\n const num = input.substring(start, i)\n const hasInvalidLeadingZero = /^0\\d/.test(num)\n\n output.push(hasInvalidLeadingZero ? `\"${num}\"` : num)\n return stack.update(Caret.afterValue)\n }\n\n return false\n }\n\n /**\n * Parse keywords true, false, null\n * Repair Python keywords True, False, None\n */\n function parseKeywords(): boolean {\n return (\n parseKeyword('true', 'true') ||\n parseKeyword('false', 'false') ||\n parseKeyword('null', 'null') ||\n // repair Python keywords True, False, None\n parseKeyword('True', 'true') ||\n parseKeyword('False', 'false') ||\n parseKeyword('None', 'null')\n )\n }\n\n function parseKeyword(name: string, value: string): boolean {\n if (input.substring(i, i + name.length) === name) {\n output.push(value)\n i += name.length\n return stack.update(Caret.afterValue)\n }\n\n return false\n }\n\n function parseUnquotedKey(): boolean {\n let end = findNextDelimiter(true, i)\n\n if (end !== null) {\n // first, go back to prevent getting trailing whitespaces in the string\n while (isWhitespace(input, end - 1) && end > i) {\n end--\n }\n\n const symbol = input.substring(i, end)\n output.push(JSON.stringify(symbol))\n i = end\n\n if (input.charAt(i) === '\"') {\n // we had a missing start quote, but now we encountered the end quote, so we can skip that one\n i++\n }\n\n return stack.update(Caret.afterValue) // we do not have a state Caret.afterKey, therefore we use afterValue here\n }\n\n return false\n }\n\n function findNextDelimiter(isKey: boolean, start: number): number | null {\n // note that the symbol can end with whitespaces: we stop at the next delimiter\n // also, note that we allow strings to contain a slash / in order to support repairing regular expressions\n let j = start\n while (\n !input.isEnd(j) &&\n !isUnquotedStringDelimiter(input.charAt(j)) &&\n !isQuote(input.charAt(j)) &&\n (!isKey || input.charAt(j) !== ':')\n ) {\n j++\n }\n\n return j > i ? j : null\n }\n\n function prevNonWhitespaceIndex(start: number): number {\n let prev = start\n\n while (prev > 0 && isWhitespace(input, prev)) {\n prev--\n }\n\n return prev\n }\n\n function atEndOfNumber() {\n return input.isEnd(i) || isDelimiter(input.charAt(i)) || isWhitespace(input, i)\n }\n\n function repairNumberEndingWithNumericSymbol(start: number) {\n // repair numbers cut off at the end\n // this will only be called when we end after a '.', '-', or 'e' and does not\n // change the number more than it needs to make it valid JSON\n output.push(`${input.substring(start, i)}0`)\n }\n\n function throwInvalidCharacter(char: string) {\n throw new JSONRepairError(`Invalid character ${JSON.stringify(char)}`, i)\n }\n\n function throwUnexpectedCharacter() {\n throw new JSONRepairError(`Unexpected character ${JSON.stringify(input.charAt(i))}`, i)\n }\n\n function throwUnexpectedEnd() {\n throw new JSONRepairError('Unexpected end of json string', i)\n }\n\n function throwObjectKeyExpected() {\n throw new JSONRepairError('Object key expected', i)\n }\n\n function throwColonExpected() {\n throw new JSONRepairError('Colon expected', i)\n }\n\n function throwInvalidUnicodeCharacter() {\n const chars = input.substring(i, i + 6)\n throw new JSONRepairError(`Invalid unicode character \"${chars}\"`, i)\n }\n\n function atEndOfBlockComment(i: number) {\n return input.charAt(i) === '*' && input.charAt(i + 1) === '/'\n }\n\n return {\n transform,\n flush\n }\n}\n"],"mappings":"AAAA,SAASA,eAAe,QAAQ,6BAA6B;AAC7D,SACEC,kBAAkB,EAClBC,WAAW,EACXC,OAAO,EACPC,aAAa,EACbC,iBAAiB,EACjBC,kBAAkB,EAClBC,uBAAuB,EACvBC,KAAK,EACLC,OAAO,EACPC,aAAa,EACbC,iBAAiB,EACjBC,mBAAmB,EACnBC,cAAc,EACdC,yBAAyB,EACzBC,sBAAsB,EACtB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,wBAAwBiG,IAAI,CAACC,SAAS,CAAC7D,KAAK,CAACqD,MAAM,CAAClD,CAAC,CAAC,CAAC,EAAE,EAAEA,CAAC,CAAC;EACzF;EAEA,SAASgE,kBAAkBA,CAAA,EAAG;IAC5B,MAAM,IAAIxG,eAAe,CAAC,+BAA+B,EAAEwC,CAAC,CAAC;EAC/D;EAEA,SAAS8D,sBAAsBA,CAAA,EAAG;IAChC,MAAM,IAAItG,eAAe,CAAC,qBAAqB,EAAEwC,CAAC,CAAC;EACrD;EAEA,SAASsE,kBAAkBA,CAAA,EAAG;IAC5B,MAAM,IAAI9G,eAAe,CAAC,gBAAgB,EAAEwC,CAAC,CAAC;EAChD;EAEA,SAAS2G,4BAA4BA,CAAA,EAAG;IACtC,MAAMa,KAAK,GAAG3H,KAAK,CAAC0D,SAAS,CAACvD,CAAC,EAAEA,CAAC,GAAG,CAAC,CAAC;IACvC,MAAM,IAAIxC,eAAe,CAAC,8BAA8BgK,KAAK,GAAG,EAAExH,CAAC,CAAC;EACtE;EAEA,SAASoF,mBAAmBA,CAACpF,CAAS,EAAE;IACtC,OAAOH,KAAK,CAACqD,MAAM,CAAClD,CAAC,CAAC,KAAK,GAAG,IAAIH,KAAK,CAACqD,MAAM,CAAClD,CAAC,GAAG,CAAC,CAAC,KAAK,GAAG;EAC/D;EAEA,OAAO;IACLK,SAAS;IACTD;EACF,CAAC;AACH","ignoreList":[]} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/streaming/stack.js b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/streaming/stack.js new file mode 100644 index 0000000000000000000000000000000000000000..9cd665e56547aae115ca07589bb7c3b7e956da1d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/streaming/stack.js @@ -0,0 +1,44 @@ +export let Caret = /*#__PURE__*/function (Caret) { + Caret["beforeValue"] = "beforeValue"; + Caret["afterValue"] = "afterValue"; + Caret["beforeKey"] = "beforeKey"; + return Caret; +}({}); +export let StackType = /*#__PURE__*/function (StackType) { + StackType["root"] = "root"; + StackType["object"] = "object"; + StackType["array"] = "array"; + StackType["ndJson"] = "ndJson"; + StackType["functionCall"] = "dataType"; + return StackType; +}({}); +export function createStack() { + const stack = [StackType.root]; + let caret = Caret.beforeValue; + return { + get type() { + return last(stack); + }, + get caret() { + return caret; + }, + pop() { + stack.pop(); + caret = Caret.afterValue; + return true; + }, + push(type, newCaret) { + stack.push(type); + caret = newCaret; + return true; + }, + update(newCaret) { + caret = newCaret; + return true; + } + }; +} +function last(array) { + return array[array.length - 1]; +} +//# sourceMappingURL=stack.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/streaming/stack.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/streaming/stack.js.map new file mode 100644 index 0000000000000000000000000000000000000000..945c44a0a227f1dfd862752fa4b492c36193bbc7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/streaming/stack.js.map @@ -0,0 +1 @@ +{"version":3,"file":"stack.js","names":["Caret","StackType","createStack","stack","root","caret","beforeValue","type","last","pop","afterValue","push","newCaret","update","array","length"],"sources":["../../../src/streaming/stack.ts"],"sourcesContent":["export enum Caret {\n beforeValue = 'beforeValue',\n afterValue = 'afterValue',\n beforeKey = 'beforeKey'\n}\n\nexport enum StackType {\n root = 'root',\n object = 'object',\n array = 'array',\n ndJson = 'ndJson',\n functionCall = 'dataType'\n}\n\nexport function createStack() {\n const stack: StackType[] = [StackType.root]\n let caret = Caret.beforeValue\n\n return {\n get type() {\n return last(stack)\n },\n\n get caret() {\n return caret\n },\n\n pop(): true {\n stack.pop()\n caret = Caret.afterValue\n\n return true\n },\n\n push(type: StackType, newCaret: Caret): true {\n stack.push(type)\n caret = newCaret\n\n return true\n },\n\n update(newCaret: Caret): true {\n caret = newCaret\n\n return true\n }\n }\n}\n\nfunction last(array: T[]): T | undefined {\n return array[array.length - 1]\n}\n"],"mappings":"AAAA,WAAYA,KAAK,0BAALA,KAAK;EAALA,KAAK;EAALA,KAAK;EAALA,KAAK;EAAA,OAALA,KAAK;AAAA;AAMjB,WAAYC,SAAS,0BAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAAA,OAATA,SAAS;AAAA;AAQrB,OAAO,SAASC,WAAWA,CAAA,EAAG;EAC5B,MAAMC,KAAkB,GAAG,CAACF,SAAS,CAACG,IAAI,CAAC;EAC3C,IAAIC,KAAK,GAAGL,KAAK,CAACM,WAAW;EAE7B,OAAO;IACL,IAAIC,IAAIA,CAAA,EAAG;MACT,OAAOC,IAAI,CAACL,KAAK,CAAC;IACpB,CAAC;IAED,IAAIE,KAAKA,CAAA,EAAG;MACV,OAAOA,KAAK;IACd,CAAC;IAEDI,GAAGA,CAAA,EAAS;MACVN,KAAK,CAACM,GAAG,CAAC,CAAC;MACXJ,KAAK,GAAGL,KAAK,CAACU,UAAU;MAExB,OAAO,IAAI;IACb,CAAC;IAEDC,IAAIA,CAACJ,IAAe,EAAEK,QAAe,EAAQ;MAC3CT,KAAK,CAACQ,IAAI,CAACJ,IAAI,CAAC;MAChBF,KAAK,GAAGO,QAAQ;MAEhB,OAAO,IAAI;IACb,CAAC;IAEDC,MAAMA,CAACD,QAAe,EAAQ;MAC5BP,KAAK,GAAGO,QAAQ;MAEhB,OAAO,IAAI;IACb;EACF,CAAC;AACH;AAEA,SAASJ,IAAIA,CAAIM,KAAU,EAAiB;EAC1C,OAAOA,KAAK,CAACA,KAAK,CAACC,MAAM,GAAG,CAAC,CAAC;AAChC","ignoreList":[]} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/streaming/stream.js b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/streaming/stream.js new file mode 100644 index 0000000000000000000000000000000000000000..d52333711746fbb6f3d530857a09cc8bf8f10c29 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/streaming/stream.js @@ -0,0 +1,31 @@ +import { Transform } from 'node:stream'; +import { jsonrepairCore } from './core.js'; +export function jsonrepairTransform(options) { + const repair = jsonrepairCore({ + onData: chunk => transform.push(chunk), + bufferSize: options?.bufferSize, + chunkSize: options?.chunkSize + }); + const transform = new Transform({ + transform(chunk, _encoding, callback) { + try { + repair.transform(chunk.toString()); + } catch (err) { + this.emit('error', err); + } finally { + callback(); + } + }, + flush(callback) { + try { + repair.flush(); + } catch (err) { + this.emit('error', err); + } finally { + callback(); + } + } + }); + return transform; +} +//# sourceMappingURL=stream.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/streaming/stream.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/streaming/stream.js.map new file mode 100644 index 0000000000000000000000000000000000000000..14f1e9d2462f05c5d7f4924637db3afa09120a56 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/streaming/stream.js.map @@ -0,0 +1 @@ +{"version":3,"file":"stream.js","names":["Transform","jsonrepairCore","jsonrepairTransform","options","repair","onData","chunk","transform","push","bufferSize","chunkSize","_encoding","callback","toString","err","emit","flush"],"sources":["../../../src/streaming/stream.ts"],"sourcesContent":["import { Transform } from 'node:stream'\nimport { jsonrepairCore } from './core.js'\n\nexport interface JsonRepairTransformOptions {\n chunkSize?: number\n bufferSize?: number\n}\n\nexport function jsonrepairTransform(options?: JsonRepairTransformOptions): Transform {\n const repair = jsonrepairCore({\n onData: (chunk) => transform.push(chunk),\n bufferSize: options?.bufferSize,\n chunkSize: options?.chunkSize\n })\n\n const transform = new Transform({\n transform(chunk, _encoding, callback) {\n try {\n repair.transform(chunk.toString())\n } catch (err) {\n this.emit('error', err)\n } finally {\n callback()\n }\n },\n\n flush(callback) {\n try {\n repair.flush()\n } catch (err) {\n this.emit('error', err)\n } finally {\n callback()\n }\n }\n })\n\n return transform\n}\n"],"mappings":"AAAA,SAASA,SAAS,QAAQ,aAAa;AACvC,SAASC,cAAc,QAAQ,WAAW;AAO1C,OAAO,SAASC,mBAAmBA,CAACC,OAAoC,EAAa;EACnF,MAAMC,MAAM,GAAGH,cAAc,CAAC;IAC5BI,MAAM,EAAGC,KAAK,IAAKC,SAAS,CAACC,IAAI,CAACF,KAAK,CAAC;IACxCG,UAAU,EAAEN,OAAO,EAAEM,UAAU;IAC/BC,SAAS,EAAEP,OAAO,EAAEO;EACtB,CAAC,CAAC;EAEF,MAAMH,SAAS,GAAG,IAAIP,SAAS,CAAC;IAC9BO,SAASA,CAACD,KAAK,EAAEK,SAAS,EAAEC,QAAQ,EAAE;MACpC,IAAI;QACFR,MAAM,CAACG,SAAS,CAACD,KAAK,CAACO,QAAQ,CAAC,CAAC,CAAC;MACpC,CAAC,CAAC,OAAOC,GAAG,EAAE;QACZ,IAAI,CAACC,IAAI,CAAC,OAAO,EAAED,GAAG,CAAC;MACzB,CAAC,SAAS;QACRF,QAAQ,CAAC,CAAC;MACZ;IACF,CAAC;IAEDI,KAAKA,CAACJ,QAAQ,EAAE;MACd,IAAI;QACFR,MAAM,CAACY,KAAK,CAAC,CAAC;MAChB,CAAC,CAAC,OAAOF,GAAG,EAAE;QACZ,IAAI,CAACC,IAAI,CAAC,OAAO,EAAED,GAAG,CAAC;MACzB,CAAC,SAAS;QACRF,QAAQ,CAAC,CAAC;MACZ;IACF;EACF,CAAC,CAAC;EAEF,OAAOL,SAAS;AAClB","ignoreList":[]} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/utils/JSONRepairError.js b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/utils/JSONRepairError.js new file mode 100644 index 0000000000000000000000000000000000000000..0631aa571a2985ef8e436531a24d3ab378d91130 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/utils/JSONRepairError.js @@ -0,0 +1,7 @@ +export class JSONRepairError extends Error { + constructor(message, position) { + super(`${message} at position ${position}`); + this.position = position; + } +} +//# sourceMappingURL=JSONRepairError.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/utils/JSONRepairError.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/utils/JSONRepairError.js.map new file mode 100644 index 0000000000000000000000000000000000000000..3dcf1a79e34dbbe94e6e3ef1c72521dfe4fb2738 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/utils/JSONRepairError.js.map @@ -0,0 +1 @@ +{"version":3,"file":"JSONRepairError.js","names":["JSONRepairError","Error","constructor","message","position"],"sources":["../../../src/utils/JSONRepairError.ts"],"sourcesContent":["export class JSONRepairError extends Error {\n position: number\n\n constructor(message: string, position: number) {\n super(`${message} at position ${position}`)\n\n this.position = position\n }\n}\n"],"mappings":"AAAA,OAAO,MAAMA,eAAe,SAASC,KAAK,CAAC;EAGzCC,WAAWA,CAACC,OAAe,EAAEC,QAAgB,EAAE;IAC7C,KAAK,CAAC,GAAGD,OAAO,gBAAgBC,QAAQ,EAAE,CAAC;IAE3C,IAAI,CAACA,QAAQ,GAAGA,QAAQ;EAC1B;AACF","ignoreList":[]} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/utils/stringUtils.js b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/utils/stringUtils.js new file mode 100644 index 0000000000000000000000000000000000000000..9482762a12dd7eefc21b97bcb54a0e44e5fc6dcf --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/utils/stringUtils.js @@ -0,0 +1,147 @@ +const codeSpace = 0x20; // " " +const codeNewline = 0xa; // "\n" +const codeTab = 0x9; // "\t" +const codeReturn = 0xd; // "\r" +const codeNonBreakingSpace = 0xa0; +const codeEnQuad = 0x2000; +const codeHairSpace = 0x200a; +const codeNarrowNoBreakSpace = 0x202f; +const codeMediumMathematicalSpace = 0x205f; +const codeIdeographicSpace = 0x3000; +export function isHex(char) { + return /^[0-9A-Fa-f]$/.test(char); +} +export function isDigit(char) { + return char >= '0' && char <= '9'; +} +export function isValidStringCharacter(char) { + // note that the valid range is between \u{0020} and \u{10ffff}, + // but in JavaScript it is not possible to create a code point larger than + // \u{10ffff}, so there is no need to test for that here. + return char >= '\u0020'; +} +export function isDelimiter(char) { + return ',:[]/{}()\n+'.includes(char); +} +export function isFunctionNameCharStart(char) { + return char >= 'a' && char <= 'z' || char >= 'A' && char <= 'Z' || char === '_' || char === '$'; +} +export function isFunctionNameChar(char) { + return char >= 'a' && char <= 'z' || char >= 'A' && char <= 'Z' || char === '_' || char === '$' || char >= '0' && char <= '9'; +} + +// matches "https://" and other schemas +export const regexUrlStart = /^(http|https|ftp|mailto|file|data|irc):\/\/$/; + +// matches all valid URL characters EXCEPT "[", "]", and ",", since that are important JSON delimiters +export const regexUrlChar = /^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/; +export function isUnquotedStringDelimiter(char) { + return ',[]/{}\n+'.includes(char); +} +export function isStartOfValue(char) { + return isQuote(char) || regexStartOfValue.test(char); +} + +// alpha, number, minus, or opening bracket or brace +const regexStartOfValue = /^[[{\w-]$/; +export function isControlCharacter(char) { + return char === '\n' || char === '\r' || char === '\t' || char === '\b' || char === '\f'; +} +/** + * Check if the given character is a whitespace character like space, tab, or + * newline + */ +export function isWhitespace(text, index) { + const code = text.charCodeAt(index); + return code === codeSpace || code === codeNewline || code === codeTab || code === codeReturn; +} + +/** + * Check if the given character is a whitespace character like space or tab, + * but NOT a newline + */ +export function isWhitespaceExceptNewline(text, index) { + const code = text.charCodeAt(index); + return code === codeSpace || code === codeTab || code === codeReturn; +} + +/** + * Check if the given character is a special whitespace character, some + * unicode variant + */ +export function isSpecialWhitespace(text, index) { + const code = text.charCodeAt(index); + return code === codeNonBreakingSpace || code >= codeEnQuad && code <= codeHairSpace || code === codeNarrowNoBreakSpace || code === codeMediumMathematicalSpace || code === codeIdeographicSpace; +} + +/** + * Test whether the given character is a quote or double quote character. + * Also tests for special variants of quotes. + */ +export function isQuote(char) { + // the first check double quotes, since that occurs most often + return isDoubleQuoteLike(char) || isSingleQuoteLike(char); +} + +/** + * Test whether the given character is a double quote character. + * Also tests for special variants of double quotes. + */ +export function isDoubleQuoteLike(char) { + return char === '"' || char === '\u201c' || char === '\u201d'; +} + +/** + * Test whether the given character is a double quote character. + * Does NOT test for special variants of double quotes. + */ +export function isDoubleQuote(char) { + return char === '"'; +} + +/** + * Test whether the given character is a single quote character. + * Also tests for special variants of single quotes. + */ +export function isSingleQuoteLike(char) { + return char === "'" || char === '\u2018' || char === '\u2019' || char === '\u0060' || char === '\u00b4'; +} + +/** + * Test whether the given character is a single quote character. + * Does NOT test for special variants of single quotes. + */ +export function isSingleQuote(char) { + return char === "'"; +} + +/** + * Strip last occurrence of textToStrip from text + */ +export function stripLastOccurrence(text, textToStrip) { + let stripRemainingText = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + const index = text.lastIndexOf(textToStrip); + return index !== -1 ? text.substring(0, index) + (stripRemainingText ? '' : text.substring(index + 1)) : text; +} +export function insertBeforeLastWhitespace(text, textToInsert) { + let index = text.length; + if (!isWhitespace(text, index - 1)) { + // no trailing whitespaces + return text + textToInsert; + } + while (isWhitespace(text, index - 1)) { + index--; + } + return text.substring(0, index) + textToInsert + text.substring(index); +} +export function removeAtIndex(text, start, count) { + return text.substring(0, start) + text.substring(start + count); +} + +/** + * Test whether a string ends with a newline or comma character and optional whitespace + */ +export function endsWithCommaOrNewline(text) { + return /[,\n][ \t\r]*$/.test(text); +} +//# sourceMappingURL=stringUtils.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/utils/stringUtils.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/utils/stringUtils.js.map new file mode 100644 index 0000000000000000000000000000000000000000..f5c677cc02b4497c0e977d3fd31d22690ade2438 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/esm/utils/stringUtils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"stringUtils.js","names":["codeSpace","codeNewline","codeTab","codeReturn","codeNonBreakingSpace","codeEnQuad","codeHairSpace","codeNarrowNoBreakSpace","codeMediumMathematicalSpace","codeIdeographicSpace","isHex","char","test","isDigit","isValidStringCharacter","isDelimiter","includes","isFunctionNameCharStart","isFunctionNameChar","regexUrlStart","regexUrlChar","isUnquotedStringDelimiter","isStartOfValue","isQuote","regexStartOfValue","isControlCharacter","isWhitespace","text","index","code","charCodeAt","isWhitespaceExceptNewline","isSpecialWhitespace","isDoubleQuoteLike","isSingleQuoteLike","isDoubleQuote","isSingleQuote","stripLastOccurrence","textToStrip","stripRemainingText","arguments","length","undefined","lastIndexOf","substring","insertBeforeLastWhitespace","textToInsert","removeAtIndex","start","count","endsWithCommaOrNewline"],"sources":["../../../src/utils/stringUtils.ts"],"sourcesContent":["const codeSpace = 0x20 // \" \"\nconst codeNewline = 0xa // \"\\n\"\nconst codeTab = 0x9 // \"\\t\"\nconst codeReturn = 0xd // \"\\r\"\nconst codeNonBreakingSpace = 0xa0\nconst codeEnQuad = 0x2000\nconst codeHairSpace = 0x200a\nconst codeNarrowNoBreakSpace = 0x202f\nconst codeMediumMathematicalSpace = 0x205f\nconst codeIdeographicSpace = 0x3000\n\nexport function isHex(char: string): boolean {\n return /^[0-9A-Fa-f]$/.test(char)\n}\n\nexport function isDigit(char: string): boolean {\n return char >= '0' && char <= '9'\n}\n\nexport function isValidStringCharacter(char: string): boolean {\n // note that the valid range is between \\u{0020} and \\u{10ffff},\n // but in JavaScript it is not possible to create a code point larger than\n // \\u{10ffff}, so there is no need to test for that here.\n return char >= '\\u0020'\n}\n\nexport function isDelimiter(char: string): boolean {\n return ',:[]/{}()\\n+'.includes(char)\n}\n\nexport function isFunctionNameCharStart(char: string) {\n return (\n (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z') || char === '_' || char === '$'\n )\n}\n\nexport function isFunctionNameChar(char: string) {\n return (\n (char >= 'a' && char <= 'z') ||\n (char >= 'A' && char <= 'Z') ||\n char === '_' ||\n char === '$' ||\n (char >= '0' && char <= '9')\n )\n}\n\n// matches \"https://\" and other schemas\nexport const regexUrlStart = /^(http|https|ftp|mailto|file|data|irc):\\/\\/$/\n\n// matches all valid URL characters EXCEPT \"[\", \"]\", and \",\", since that are important JSON delimiters\nexport const regexUrlChar = /^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/\n\nexport function isUnquotedStringDelimiter(char: string): boolean {\n return ',[]/{}\\n+'.includes(char)\n}\n\nexport function isStartOfValue(char: string): boolean {\n return isQuote(char) || regexStartOfValue.test(char)\n}\n\n// alpha, number, minus, or opening bracket or brace\nconst regexStartOfValue = /^[[{\\w-]$/\n\nexport function isControlCharacter(char: string) {\n return char === '\\n' || char === '\\r' || char === '\\t' || char === '\\b' || char === '\\f'\n}\n\nexport interface Text {\n charCodeAt: (index: number) => number\n}\n\n/**\n * Check if the given character is a whitespace character like space, tab, or\n * newline\n */\nexport function isWhitespace(text: Text, index: number): boolean {\n const code = text.charCodeAt(index)\n\n return code === codeSpace || code === codeNewline || code === codeTab || code === codeReturn\n}\n\n/**\n * Check if the given character is a whitespace character like space or tab,\n * but NOT a newline\n */\nexport function isWhitespaceExceptNewline(text: Text, index: number): boolean {\n const code = text.charCodeAt(index)\n\n return code === codeSpace || code === codeTab || code === codeReturn\n}\n\n/**\n * Check if the given character is a special whitespace character, some\n * unicode variant\n */\nexport function isSpecialWhitespace(text: Text, index: number): boolean {\n const code = text.charCodeAt(index)\n\n return (\n code === codeNonBreakingSpace ||\n (code >= codeEnQuad && code <= codeHairSpace) ||\n code === codeNarrowNoBreakSpace ||\n code === codeMediumMathematicalSpace ||\n code === codeIdeographicSpace\n )\n}\n\n/**\n * Test whether the given character is a quote or double quote character.\n * Also tests for special variants of quotes.\n */\nexport function isQuote(char: string): boolean {\n // the first check double quotes, since that occurs most often\n return isDoubleQuoteLike(char) || isSingleQuoteLike(char)\n}\n\n/**\n * Test whether the given character is a double quote character.\n * Also tests for special variants of double quotes.\n */\nexport function isDoubleQuoteLike(char: string): boolean {\n return char === '\"' || char === '\\u201c' || char === '\\u201d'\n}\n\n/**\n * Test whether the given character is a double quote character.\n * Does NOT test for special variants of double quotes.\n */\nexport function isDoubleQuote(char: string): boolean {\n return char === '\"'\n}\n\n/**\n * Test whether the given character is a single quote character.\n * Also tests for special variants of single quotes.\n */\nexport function isSingleQuoteLike(char: string): boolean {\n return (\n char === \"'\" || char === '\\u2018' || char === '\\u2019' || char === '\\u0060' || char === '\\u00b4'\n )\n}\n\n/**\n * Test whether the given character is a single quote character.\n * Does NOT test for special variants of single quotes.\n */\nexport function isSingleQuote(char: string): boolean {\n return char === \"'\"\n}\n\n/**\n * Strip last occurrence of textToStrip from text\n */\nexport function stripLastOccurrence(\n text: string,\n textToStrip: string,\n stripRemainingText = false\n): string {\n const index = text.lastIndexOf(textToStrip)\n return index !== -1\n ? text.substring(0, index) + (stripRemainingText ? '' : text.substring(index + 1))\n : text\n}\n\nexport function insertBeforeLastWhitespace(text: string, textToInsert: string): string {\n let index = text.length\n\n if (!isWhitespace(text, index - 1)) {\n // no trailing whitespaces\n return text + textToInsert\n }\n\n while (isWhitespace(text, index - 1)) {\n index--\n }\n\n return text.substring(0, index) + textToInsert + text.substring(index)\n}\n\nexport function removeAtIndex(text: string, start: number, count: number) {\n return text.substring(0, start) + text.substring(start + count)\n}\n\n/**\n * Test whether a string ends with a newline or comma character and optional whitespace\n */\nexport function endsWithCommaOrNewline(text: string): boolean {\n return /[,\\n][ \\t\\r]*$/.test(text)\n}\n"],"mappings":"AAAA,MAAMA,SAAS,GAAG,IAAI,EAAC;AACvB,MAAMC,WAAW,GAAG,GAAG,EAAC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,CAAChB,KAAK,GAAG,CAAC,CAAC,CAAC,GAChFD,IAAI;AACV;AAEA,OAAO,SAASkB,0BAA0BA,CAAClB,IAAY,EAAEmB,YAAoB,EAAU;EACrF,IAAIlB,KAAK,GAAGD,IAAI,CAACc,MAAM;EAEvB,IAAI,CAACf,YAAY,CAACC,IAAI,EAAEC,KAAK,GAAG,CAAC,CAAC,EAAE;IAClC;IACA,OAAOD,IAAI,GAAGmB,YAAY;EAC5B;EAEA,OAAOpB,YAAY,CAACC,IAAI,EAAEC,KAAK,GAAG,CAAC,CAAC,EAAE;IACpCA,KAAK,EAAE;EACT;EAEA,OAAOD,IAAI,CAACiB,SAAS,CAAC,CAAC,EAAEhB,KAAK,CAAC,GAAGkB,YAAY,GAAGnB,IAAI,CAACiB,SAAS,CAAChB,KAAK,CAAC;AACxE;AAEA,OAAO,SAASmB,aAAaA,CAACpB,IAAY,EAAEqB,KAAa,EAAEC,KAAa,EAAE;EACxE,OAAOtB,IAAI,CAACiB,SAAS,CAAC,CAAC,EAAEI,KAAK,CAAC,GAAGrB,IAAI,CAACiB,SAAS,CAACI,KAAK,GAAGC,KAAK,CAAC;AACjE;;AAEA;AACA;AACA;AACA,OAAO,SAASC,sBAAsBA,CAACvB,IAAY,EAAW;EAC5D,OAAO,gBAAgB,CAACf,IAAI,CAACe,IAAI,CAAC;AACpC","ignoreList":[]} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/index.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..88f8fea1b65f636c916fabd5b9ae5b088171b88e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/index.d.ts @@ -0,0 +1,3 @@ +export { jsonrepair } from './regular/jsonrepair.js'; +export { JSONRepairError } from './utils/JSONRepairError.js'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/index.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..b02ff6c537f9485dfcdeb1b1c08646b4282c7313 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAA;AACpD,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/regular/jsonrepair.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/regular/jsonrepair.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6c746fa45e84b2fcc95396bc7678256f6e014166 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/regular/jsonrepair.d.ts @@ -0,0 +1,18 @@ +/** + * Repair a string containing an invalid JSON document. + * For example changes JavaScript notation into JSON notation. + * + * Example: + * + * try { + * const json = "{name: 'John'}" + * const repaired = jsonrepair(json) + * console.log(repaired) + * // '{"name": "John"}' + * } catch (err) { + * console.error(err) + * } + * + */ +export declare function jsonrepair(text: string): string; +//# sourceMappingURL=jsonrepair.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/regular/jsonrepair.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/regular/jsonrepair.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..4e79ddcdaa01be63be53d48cbac2b3d3f9848c31 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/regular/jsonrepair.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"jsonrepair.d.ts","sourceRoot":"","sources":["../../../src/regular/jsonrepair.ts"],"names":[],"mappings":"AAgDA;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAm0B/C"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/stream.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/stream.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..714a13bfa7b54421acf263b91d69bf9464139c9d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/stream.d.ts @@ -0,0 +1,2 @@ +export { type JsonRepairTransformOptions, jsonrepairTransform } from './streaming/stream.js'; +//# sourceMappingURL=stream.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/stream.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/stream.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..1eba06f7c9fa13196365b7b7b4c47b8941562998 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/stream.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"stream.d.ts","sourceRoot":"","sources":["../../src/stream.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,0BAA0B,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/streaming/buffer/InputBuffer.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/streaming/buffer/InputBuffer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c53b92476af1390ae4163beb88a19086b02bfe1d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/streaming/buffer/InputBuffer.d.ts @@ -0,0 +1,14 @@ +export interface InputBuffer { + push: (chunk: string) => void; + flush: (position: number) => void; + charAt: (index: number) => string; + charCodeAt: (index: number) => number; + substring: (start: number, end: number) => string; + length: () => number; + currentLength: () => number; + currentBufferSize: () => number; + isEnd: (index: number) => boolean; + close: () => void; +} +export declare function createInputBuffer(): InputBuffer; +//# sourceMappingURL=InputBuffer.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/streaming/buffer/InputBuffer.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/streaming/buffer/InputBuffer.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..4b20a4b08f51c682c04c3dd1ed273620a847c059 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/streaming/buffer/InputBuffer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"InputBuffer.d.ts","sourceRoot":"","sources":["../../../../src/streaming/buffer/InputBuffer.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAA;IAC7B,KAAK,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,IAAI,CAAA;IACjC,MAAM,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,MAAM,CAAA;IACjC,UAAU,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,MAAM,CAAA;IACrC,SAAS,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,KAAK,MAAM,CAAA;IACjD,MAAM,EAAE,MAAM,MAAM,CAAA;IACpB,aAAa,EAAE,MAAM,MAAM,CAAA;IAC3B,iBAAiB,EAAE,MAAM,MAAM,CAAA;IAC/B,KAAK,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,CAAA;IACjC,KAAK,EAAE,MAAM,IAAI,CAAA;CAClB;AAED,wBAAgB,iBAAiB,IAAI,WAAW,CAmF/C"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/streaming/buffer/OutputBuffer.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/streaming/buffer/OutputBuffer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ff2abe16274942bdabf8f4e2e89d7bddca3d658a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/streaming/buffer/OutputBuffer.d.ts @@ -0,0 +1,18 @@ +export interface OutputBuffer { + push: (text: string) => void; + unshift: (text: string) => void; + remove: (start: number, end?: number) => void; + insertAt: (index: number, text: string) => void; + length: () => number; + flush: () => void; + stripLastOccurrence: (textToStrip: string, stripRemainingText?: boolean) => void; + insertBeforeLastWhitespace: (textToInsert: string) => void; + endsWithIgnoringWhitespace: (char: string) => boolean; +} +export interface OutputBufferOptions { + write: (chunk: string) => void; + chunkSize: number; + bufferSize: number; +} +export declare function createOutputBuffer({ write, chunkSize, bufferSize }: OutputBufferOptions): OutputBuffer; +//# sourceMappingURL=OutputBuffer.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/streaming/buffer/OutputBuffer.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/streaming/buffer/OutputBuffer.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..16bc55d190f1f9f45d96190e9f93116f05a1aa8f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/streaming/buffer/OutputBuffer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"OutputBuffer.d.ts","sourceRoot":"","sources":["../../../../src/streaming/buffer/OutputBuffer.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAA;IAC5B,OAAO,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAA;IAC/B,MAAM,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,MAAM,KAAK,IAAI,CAAA;IAC7C,QAAQ,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,KAAK,IAAI,CAAA;IAC/C,MAAM,EAAE,MAAM,MAAM,CAAA;IACpB,KAAK,EAAE,MAAM,IAAI,CAAA;IAEjB,mBAAmB,EAAE,CAAC,WAAW,EAAE,MAAM,EAAE,kBAAkB,CAAC,EAAE,OAAO,KAAK,IAAI,CAAA;IAChF,0BAA0B,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,IAAI,CAAA;IAC1D,0BAA0B,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAA;CACtD;AAED,MAAM,WAAW,mBAAmB;IAClC,KAAK,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAA;IAC9B,SAAS,EAAE,MAAM,CAAA;IACjB,UAAU,EAAE,MAAM,CAAA;CACnB;AAED,wBAAgB,kBAAkB,CAAC,EACjC,KAAK,EACL,SAAS,EACT,UAAU,EACX,EAAE,mBAAmB,GAAG,YAAY,CA6HpC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/streaming/core.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/streaming/core.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0040a4857daf07db67ce7cb3148c7006b0b6e381 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/streaming/core.d.ts @@ -0,0 +1,11 @@ +export interface JsonRepairCoreOptions { + onData: (chunk: string) => void; + chunkSize?: number; + bufferSize?: number; +} +export interface JsonRepairCore { + transform: (chunk: string) => void; + flush: () => void; +} +export declare function jsonrepairCore({ onData, bufferSize, chunkSize }: JsonRepairCoreOptions): JsonRepairCore; +//# sourceMappingURL=core.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/streaming/core.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/streaming/core.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..be169f81acc886508f45b8673ba1a210c9ce040f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/streaming/core.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"core.d.ts","sourceRoot":"","sources":["../../../src/streaming/core.ts"],"names":[],"mappings":"AA+CA,MAAM,WAAW,qBAAqB;IACpC,MAAM,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAA;IAC/B,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,UAAU,CAAC,EAAE,MAAM,CAAA;CACpB;AAED,MAAM,WAAW,cAAc;IAC7B,SAAS,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAA;IAClC,KAAK,EAAE,MAAM,IAAI,CAAA;CAClB;AAED,wBAAgB,cAAc,CAAC,EAC7B,MAAM,EACN,UAAkB,EAClB,SAAiB,EAClB,EAAE,qBAAqB,GAAG,cAAc,CA49BxC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/streaming/stack.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/streaming/stack.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0fd139cda08a42ab7f8cbbfbf2bb00c179c5dbf6 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/streaming/stack.d.ts @@ -0,0 +1,20 @@ +export declare enum Caret { + beforeValue = "beforeValue", + afterValue = "afterValue", + beforeKey = "beforeKey" +} +export declare enum StackType { + root = "root", + object = "object", + array = "array", + ndJson = "ndJson", + functionCall = "dataType" +} +export declare function createStack(): { + readonly type: StackType; + readonly caret: Caret; + pop(): true; + push(type: StackType, newCaret: Caret): true; + update(newCaret: Caret): true; +}; +//# sourceMappingURL=stack.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/streaming/stack.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/streaming/stack.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..8f243feb12abcbb028633987629e1d78ffe031d9 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/streaming/stack.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"stack.d.ts","sourceRoot":"","sources":["../../../src/streaming/stack.ts"],"names":[],"mappings":"AAAA,oBAAY,KAAK;IACf,WAAW,gBAAgB;IAC3B,UAAU,eAAe;IACzB,SAAS,cAAc;CACxB;AAED,oBAAY,SAAS;IACnB,IAAI,SAAS;IACb,MAAM,WAAW;IACjB,KAAK,UAAU;IACf,MAAM,WAAW;IACjB,YAAY,aAAa;CAC1B;AAED,wBAAgB,WAAW;;;WAahB,IAAI;eAOA,SAAS,YAAY,KAAK,GAAG,IAAI;qBAO3B,KAAK,GAAG,IAAI;EAMhC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/streaming/stream.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/streaming/stream.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8be2afc615cb8d79203c97d1d9ce0cd183af424d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/streaming/stream.d.ts @@ -0,0 +1,7 @@ +import { Transform } from 'node:stream'; +export interface JsonRepairTransformOptions { + chunkSize?: number; + bufferSize?: number; +} +export declare function jsonrepairTransform(options?: JsonRepairTransformOptions): Transform; +//# sourceMappingURL=stream.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/streaming/stream.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/streaming/stream.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..42531807728414dbeb761c8e253b579da2e6e71b --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/streaming/stream.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"stream.d.ts","sourceRoot":"","sources":["../../../src/streaming/stream.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAA;AAGvC,MAAM,WAAW,0BAA0B;IACzC,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,UAAU,CAAC,EAAE,MAAM,CAAA;CACpB;AAED,wBAAgB,mBAAmB,CAAC,OAAO,CAAC,EAAE,0BAA0B,GAAG,SAAS,CA8BnF"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/utils/JSONRepairError.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/utils/JSONRepairError.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..275b38bb61f451376a3626c3b02d9dee25f638f1 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/utils/JSONRepairError.d.ts @@ -0,0 +1,5 @@ +export declare class JSONRepairError extends Error { + position: number; + constructor(message: string, position: number); +} +//# sourceMappingURL=JSONRepairError.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/utils/JSONRepairError.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/utils/JSONRepairError.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..abbe1b43da0c3a0a02a7a7e17a7f495a601ca5aa --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/utils/JSONRepairError.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"JSONRepairError.d.ts","sourceRoot":"","sources":["../../../src/utils/JSONRepairError.ts"],"names":[],"mappings":"AAAA,qBAAa,eAAgB,SAAQ,KAAK;IACxC,QAAQ,EAAE,MAAM,CAAA;gBAEJ,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM;CAK9C"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/utils/stringUtils.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/utils/stringUtils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..080a2e69318e24ec735db492727baf85bd8159dd --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/utils/stringUtils.d.ts @@ -0,0 +1,65 @@ +export declare function isHex(char: string): boolean; +export declare function isDigit(char: string): boolean; +export declare function isValidStringCharacter(char: string): boolean; +export declare function isDelimiter(char: string): boolean; +export declare function isFunctionNameCharStart(char: string): boolean; +export declare function isFunctionNameChar(char: string): boolean; +export declare const regexUrlStart: RegExp; +export declare const regexUrlChar: RegExp; +export declare function isUnquotedStringDelimiter(char: string): boolean; +export declare function isStartOfValue(char: string): boolean; +export declare function isControlCharacter(char: string): char is "\n" | "\r" | "\t" | "\b" | "\f"; +export interface Text { + charCodeAt: (index: number) => number; +} +/** + * Check if the given character is a whitespace character like space, tab, or + * newline + */ +export declare function isWhitespace(text: Text, index: number): boolean; +/** + * Check if the given character is a whitespace character like space or tab, + * but NOT a newline + */ +export declare function isWhitespaceExceptNewline(text: Text, index: number): boolean; +/** + * Check if the given character is a special whitespace character, some + * unicode variant + */ +export declare function isSpecialWhitespace(text: Text, index: number): boolean; +/** + * Test whether the given character is a quote or double quote character. + * Also tests for special variants of quotes. + */ +export declare function isQuote(char: string): boolean; +/** + * Test whether the given character is a double quote character. + * Also tests for special variants of double quotes. + */ +export declare function isDoubleQuoteLike(char: string): boolean; +/** + * Test whether the given character is a double quote character. + * Does NOT test for special variants of double quotes. + */ +export declare function isDoubleQuote(char: string): boolean; +/** + * Test whether the given character is a single quote character. + * Also tests for special variants of single quotes. + */ +export declare function isSingleQuoteLike(char: string): boolean; +/** + * Test whether the given character is a single quote character. + * Does NOT test for special variants of single quotes. + */ +export declare function isSingleQuote(char: string): boolean; +/** + * Strip last occurrence of textToStrip from text + */ +export declare function stripLastOccurrence(text: string, textToStrip: string, stripRemainingText?: boolean): string; +export declare function insertBeforeLastWhitespace(text: string, textToInsert: string): string; +export declare function removeAtIndex(text: string, start: number, count: number): string; +/** + * Test whether a string ends with a newline or comma character and optional whitespace + */ +export declare function endsWithCommaOrNewline(text: string): boolean; +//# sourceMappingURL=stringUtils.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/utils/stringUtils.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/utils/stringUtils.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..7f62ddc57e021147daf89a34ddd7fb4d8a9359cd --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/types/utils/stringUtils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"stringUtils.d.ts","sourceRoot":"","sources":["../../../src/utils/stringUtils.ts"],"names":[],"mappings":"AAWA,wBAAgB,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAE3C;AAED,wBAAgB,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAE7C;AAED,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAK5D;AAED,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAEjD;AAED,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,MAAM,WAInD;AAED,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,WAQ9C;AAGD,eAAO,MAAM,aAAa,QAAiD,CAAA;AAG3E,eAAO,MAAM,YAAY,QAAqC,CAAA;AAE9D,wBAAgB,yBAAyB,CAAC,IAAI,E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;AAED;;GAEG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAE5D"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/umd/jsonrepair.js b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/umd/jsonrepair.js new file mode 100644 index 0000000000000000000000000000000000000000..31aefbf44e7ea74d854a9c8798d2e7d8427a795b --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/umd/jsonrepair.js @@ -0,0 +1,902 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.JSONRepair = {})); +})(this, (function (exports) { 'use strict'; + + class JSONRepairError extends Error { + constructor(message, position) { + super(`${message} at position ${position}`); + this.position = position; + } + } + + const codeSpace = 0x20; // " " + const codeNewline = 0xa; // "\n" + const codeTab = 0x9; // "\t" + const codeReturn = 0xd; // "\r" + const codeNonBreakingSpace = 0xa0; + const codeEnQuad = 0x2000; + const codeHairSpace = 0x200a; + const codeNarrowNoBreakSpace = 0x202f; + const codeMediumMathematicalSpace = 0x205f; + const codeIdeographicSpace = 0x3000; + function isHex(char) { + return /^[0-9A-Fa-f]$/.test(char); + } + function isDigit(char) { + return char >= '0' && char <= '9'; + } + function isValidStringCharacter(char) { + // note that the valid range is between \u{0020} and \u{10ffff}, + // but in JavaScript it is not possible to create a code point larger than + // \u{10ffff}, so there is no need to test for that here. + return char >= '\u0020'; + } + function isDelimiter(char) { + return ',:[]/{}()\n+'.includes(char); + } + function isFunctionNameCharStart(char) { + return char >= 'a' && char <= 'z' || char >= 'A' && char <= 'Z' || char === '_' || char === '$'; + } + function isFunctionNameChar(char) { + return char >= 'a' && char <= 'z' || char >= 'A' && char <= 'Z' || char === '_' || char === '$' || char >= '0' && char <= '9'; + } + + // matches "https://" and other schemas + const regexUrlStart = /^(http|https|ftp|mailto|file|data|irc):\/\/$/; + + // matches all valid URL characters EXCEPT "[", "]", and ",", since that are important JSON delimiters + const regexUrlChar = /^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/; + function isUnquotedStringDelimiter(char) { + return ',[]/{}\n+'.includes(char); + } + function isStartOfValue(char) { + return isQuote(char) || regexStartOfValue.test(char); + } + + // alpha, number, minus, or opening bracket or brace + const regexStartOfValue = /^[[{\w-]$/; + function isControlCharacter(char) { + return char === '\n' || char === '\r' || char === '\t' || char === '\b' || char === '\f'; + } + /** + * Check if the given character is a whitespace character like space, tab, or + * newline + */ + function isWhitespace(text, index) { + const code = text.charCodeAt(index); + return code === codeSpace || code === codeNewline || code === codeTab || code === codeReturn; + } + + /** + * Check if the given character is a whitespace character like space or tab, + * but NOT a newline + */ + function isWhitespaceExceptNewline(text, index) { + const code = text.charCodeAt(index); + return code === codeSpace || code === codeTab || code === codeReturn; + } + + /** + * Check if the given character is a special whitespace character, some + * unicode variant + */ + function isSpecialWhitespace(text, index) { + const code = text.charCodeAt(index); + return code === codeNonBreakingSpace || code >= codeEnQuad && code <= codeHairSpace || code === codeNarrowNoBreakSpace || code === codeMediumMathematicalSpace || code === codeIdeographicSpace; + } + + /** + * Test whether the given character is a quote or double quote character. + * Also tests for special variants of quotes. + */ + function isQuote(char) { + // the first check double quotes, since that occurs most often + return isDoubleQuoteLike(char) || isSingleQuoteLike(char); + } + + /** + * Test whether the given character is a double quote character. + * Also tests for special variants of double quotes. + */ + function isDoubleQuoteLike(char) { + return char === '"' || char === '\u201c' || char === '\u201d'; + } + + /** + * Test whether the given character is a double quote character. + * Does NOT test for special variants of double quotes. + */ + function isDoubleQuote(char) { + return char === '"'; + } + + /** + * Test whether the given character is a single quote character. + * Also tests for special variants of single quotes. + */ + function isSingleQuoteLike(char) { + return char === "'" || char === '\u2018' || char === '\u2019' || char === '\u0060' || char === '\u00b4'; + } + + /** + * Test whether the given character is a single quote character. + * Does NOT test for special variants of single quotes. + */ + function isSingleQuote(char) { + return char === "'"; + } + + /** + * Strip last occurrence of textToStrip from text + */ + function stripLastOccurrence(text, textToStrip) { + let stripRemainingText = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + const index = text.lastIndexOf(textToStrip); + return index !== -1 ? text.substring(0, index) + (stripRemainingText ? '' : text.substring(index + 1)) : text; + } + function insertBeforeLastWhitespace(text, textToInsert) { + let index = text.length; + if (!isWhitespace(text, index - 1)) { + // no trailing whitespaces + return text + textToInsert; + } + while (isWhitespace(text, index - 1)) { + index--; + } + return text.substring(0, index) + textToInsert + text.substring(index); + } + function removeAtIndex(text, start, count) { + return text.substring(0, start) + text.substring(start + count); + } + + /** + * Test whether a string ends with a newline or comma character and optional whitespace + */ + function endsWithCommaOrNewline(text) { + return /[,\n][ \t\r]*$/.test(text); + } + + const controlCharacters = { + '\b': '\\b', + '\f': '\\f', + '\n': '\\n', + '\r': '\\r', + '\t': '\\t' + }; + + // map with all escape characters + const escapeCharacters = { + '"': '"', + '\\': '\\', + '/': '/', + b: '\b', + f: '\f', + n: '\n', + r: '\r', + t: '\t' + // note that \u is handled separately in parseString() + }; + + /** + * Repair a string containing an invalid JSON document. + * For example changes JavaScript notation into JSON notation. + * + * Example: + * + * try { + * const json = "{name: 'John'}" + * const repaired = jsonrepair(json) + * console.log(repaired) + * // '{"name": "John"}' + * } catch (err) { + * console.error(err) + * } + * + */ + function jsonrepair(text) { + let i = 0; // current index in text + let output = ''; // generated output + + parseMarkdownCodeBlock(['```', '[```', '{```']); + const processed = parseValue(); + if (!processed) { + throwUnexpectedEnd(); + } + parseMarkdownCodeBlock(['```', '```]', '```}']); + const processedComma = parseCharacter(','); + if (processedComma) { + parseWhitespaceAndSkipComments(); + } + if (isStartOfValue(text[i]) && endsWithCommaOrNewline(output)) { + // start of a new value after end of the root level object: looks like + // newline delimited JSON -> turn into a root level array + if (!processedComma) { + // repair missing comma + output = insertBeforeLastWhitespace(output, ','); + } + parseNewlineDelimitedJSON(); + } else if (processedComma) { + // repair: remove trailing comma + output = stripLastOccurrence(output, ','); + } + + // repair redundant end quotes + while (text[i] === '}' || text[i] === ']') { + i++; + parseWhitespaceAndSkipComments(); + } + if (i >= text.length) { + // reached the end of the document properly + return output; + } + throwUnexpectedCharacter(); + function parseValue() { + parseWhitespaceAndSkipComments(); + const processed = parseObject() || parseArray() || parseString() || parseNumber() || parseKeywords() || parseUnquotedString(false) || parseRegex(); + parseWhitespaceAndSkipComments(); + return processed; + } + function parseWhitespaceAndSkipComments() { + let skipNewline = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; + const start = i; + let changed = parseWhitespace(skipNewline); + do { + changed = parseComment(); + if (changed) { + changed = parseWhitespace(skipNewline); + } + } while (changed); + return i > start; + } + function parseWhitespace(skipNewline) { + const _isWhiteSpace = skipNewline ? isWhitespace : isWhitespaceExceptNewline; + let whitespace = ''; + while (true) { + if (_isWhiteSpace(text, i)) { + whitespace += text[i]; + i++; + } else if (isSpecialWhitespace(text, i)) { + // repair special whitespace + whitespace += ' '; + i++; + } else { + break; + } + } + if (whitespace.length > 0) { + output += whitespace; + return true; + } + return false; + } + function parseComment() { + // find a block comment '/* ... */' + if (text[i] === '/' && text[i + 1] === '*') { + // repair block comment by skipping it + while (i < text.length && !atEndOfBlockComment(text, i)) { + i++; + } + i += 2; + return true; + } + + // find a line comment '// ...' + if (text[i] === '/' && text[i + 1] === '/') { + // repair line comment by skipping it + while (i < text.length && text[i] !== '\n') { + i++; + } + return true; + } + return false; + } + function parseMarkdownCodeBlock(blocks) { + // find and skip over a Markdown fenced code block: + // ``` ... ``` + // or + // ```json ... ``` + if (skipMarkdownCodeBlock(blocks)) { + if (isFunctionNameCharStart(text[i])) { + // strip the optional language specifier like "json" + while (i < text.length && isFunctionNameChar(text[i])) { + i++; + } + } + parseWhitespaceAndSkipComments(); + return true; + } + return false; + } + function skipMarkdownCodeBlock(blocks) { + for (const block of blocks) { + const end = i + block.length; + if (text.slice(i, end) === block) { + i = end; + return true; + } + } + return false; + } + function parseCharacter(char) { + if (text[i] === char) { + output += text[i]; + i++; + return true; + } + return false; + } + function skipCharacter(char) { + if (text[i] === char) { + i++; + return true; + } + return false; + } + function skipEscapeCharacter() { + return skipCharacter('\\'); + } + + /** + * Skip ellipsis like "[1,2,3,...]" or "[1,2,3,...,9]" or "[...,7,8,9]" + * or a similar construct in objects. + */ + function skipEllipsis() { + parseWhitespaceAndSkipComments(); + if (text[i] === '.' && text[i + 1] === '.' && text[i + 2] === '.') { + // repair: remove the ellipsis (three dots) and optionally a comma + i += 3; + parseWhitespaceAndSkipComments(); + skipCharacter(','); + return true; + } + return false; + } + + /** + * Parse an object like '{"key": "value"}' + */ + function parseObject() { + if (text[i] === '{') { + output += '{'; + i++; + parseWhitespaceAndSkipComments(); + + // repair: skip leading comma like in {, message: "hi"} + if (skipCharacter(',')) { + parseWhitespaceAndSkipComments(); + } + let initial = true; + while (i < text.length && text[i] !== '}') { + let processedComma; + if (!initial) { + processedComma = parseCharacter(','); + if (!processedComma) { + // repair missing comma + output = insertBeforeLastWhitespace(output, ','); + } + parseWhitespaceAndSkipComments(); + } else { + processedComma = true; + initial = false; + } + skipEllipsis(); + const processedKey = parseString() || parseUnquotedString(true); + if (!processedKey) { + if (text[i] === '}' || text[i] === '{' || text[i] === ']' || text[i] === '[' || text[i] === undefined) { + // repair trailing comma + output = stripLastOccurrence(output, ','); + } else { + throwObjectKeyExpected(); + } + break; + } + parseWhitespaceAndSkipComments(); + const processedColon = parseCharacter(':'); + const truncatedText = i >= text.length; + if (!processedColon) { + if (isStartOfValue(text[i]) || truncatedText) { + // repair missing colon + output = insertBeforeLastWhitespace(output, ':'); + } else { + throwColonExpected(); + } + } + const processedValue = parseValue(); + if (!processedValue) { + if (processedColon || truncatedText) { + // repair missing object value + output += 'null'; + } else { + throwColonExpected(); + } + } + } + if (text[i] === '}') { + output += '}'; + i++; + } else { + // repair missing end bracket + output = insertBeforeLastWhitespace(output, '}'); + } + return true; + } + return false; + } + + /** + * Parse an array like '["item1", "item2", ...]' + */ + function parseArray() { + if (text[i] === '[') { + output += '['; + i++; + parseWhitespaceAndSkipComments(); + + // repair: skip leading comma like in [,1,2,3] + if (skipCharacter(',')) { + parseWhitespaceAndSkipComments(); + } + let initial = true; + while (i < text.length && text[i] !== ']') { + if (!initial) { + const processedComma = parseCharacter(','); + if (!processedComma) { + // repair missing comma + output = insertBeforeLastWhitespace(output, ','); + } + } else { + initial = false; + } + skipEllipsis(); + const processedValue = parseValue(); + if (!processedValue) { + // repair trailing comma + output = stripLastOccurrence(output, ','); + break; + } + } + if (text[i] === ']') { + output += ']'; + i++; + } else { + // repair missing closing array bracket + output = insertBeforeLastWhitespace(output, ']'); + } + return true; + } + return false; + } + + /** + * Parse and repair Newline Delimited JSON (NDJSON): + * multiple JSON objects separated by a newline character + */ + function parseNewlineDelimitedJSON() { + // repair NDJSON + let initial = true; + let processedValue = true; + while (processedValue) { + if (!initial) { + // parse optional comma, insert when missing + const processedComma = parseCharacter(','); + if (!processedComma) { + // repair: add missing comma + output = insertBeforeLastWhitespace(output, ','); + } + } else { + initial = false; + } + processedValue = parseValue(); + } + if (!processedValue) { + // repair: remove trailing comma + output = stripLastOccurrence(output, ','); + } + + // repair: wrap the output inside array brackets + output = `[\n${output}\n]`; + } + + /** + * Parse a string enclosed by double quotes "...". Can contain escaped quotes + * Repair strings enclosed in single quotes or special quotes + * Repair an escaped string + * + * The function can run in two stages: + * - First, it assumes the string has a valid end quote + * - If it turns out that the string does not have a valid end quote followed + * by a delimiter (which should be the case), the function runs again in a + * more conservative way, stopping the string at the first next delimiter + * and fixing the string by inserting a quote there, or stopping at a + * stop index detected in the first iteration. + */ + function parseString() { + let stopAtDelimiter = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + let stopAtIndex = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : -1; + let skipEscapeChars = text[i] === '\\'; + if (skipEscapeChars) { + // repair: remove the first escape character + i++; + skipEscapeChars = true; + } + if (isQuote(text[i])) { + // double quotes are correct JSON, + // single quotes come from JavaScript for example, we assume it will have a correct single end quote too + // otherwise, we will match any double-quote-like start with a double-quote-like end, + // or any single-quote-like start with a single-quote-like end + const isEndQuote = isDoubleQuote(text[i]) ? isDoubleQuote : isSingleQuote(text[i]) ? isSingleQuote : isSingleQuoteLike(text[i]) ? isSingleQuoteLike : isDoubleQuoteLike; + const iBefore = i; + const oBefore = output.length; + let str = '"'; + i++; + while (true) { + if (i >= text.length) { + // end of text, we are missing an end quote + + const iPrev = prevNonWhitespaceIndex(i - 1); + if (!stopAtDelimiter && isDelimiter(text.charAt(iPrev))) { + // if the text ends with a delimiter, like ["hello], + // so the missing end quote should be inserted before this delimiter + // retry parsing the string, stopping at the first next delimiter + i = iBefore; + output = output.substring(0, oBefore); + return parseString(true); + } + + // repair missing quote + str = insertBeforeLastWhitespace(str, '"'); + output += str; + return true; + } + if (i === stopAtIndex) { + // use the stop index detected in the first iteration, and repair end quote + str = insertBeforeLastWhitespace(str, '"'); + output += str; + return true; + } + if (isEndQuote(text[i])) { + // end quote + // let us check what is before and after the quote to verify whether this is a legit end quote + const iQuote = i; + const oQuote = str.length; + str += '"'; + i++; + output += str; + parseWhitespaceAndSkipComments(false); + if (stopAtDelimiter || i >= text.length || isDelimiter(text[i]) || isQuote(text[i]) || isDigit(text[i])) { + // The quote is followed by the end of the text, a delimiter, + // or a next value. So the quote is indeed the end of the string. + parseConcatenatedString(); + return true; + } + const iPrevChar = prevNonWhitespaceIndex(iQuote - 1); + const prevChar = text.charAt(iPrevChar); + if (prevChar === ',') { + // A comma followed by a quote, like '{"a":"b,c,"d":"e"}'. + // We assume that the quote is a start quote, and that the end quote + // should have been located right before the comma but is missing. + i = iBefore; + output = output.substring(0, oBefore); + return parseString(false, iPrevChar); + } + if (isDelimiter(prevChar)) { + // This is not the right end quote: it is preceded by a delimiter, + // and NOT followed by a delimiter. So, there is an end quote missing + // parse the string again and then stop at the first next delimiter + i = iBefore; + output = output.substring(0, oBefore); + return parseString(true); + } + + // revert to right after the quote but before any whitespace, and continue parsing the string + output = output.substring(0, oBefore); + i = iQuote + 1; + + // repair unescaped quote + str = `${str.substring(0, oQuote)}\\${str.substring(oQuote)}`; + } else if (stopAtDelimiter && isUnquotedStringDelimiter(text[i])) { + // we're in the mode to stop the string at the first delimiter + // because there is an end quote missing + + // test start of an url like "https://..." (this would be parsed as a comment) + if (text[i - 1] === ':' && regexUrlStart.test(text.substring(iBefore + 1, i + 2))) { + while (i < text.length && regexUrlChar.test(text[i])) { + str += text[i]; + i++; + } + } + + // repair missing quote + str = insertBeforeLastWhitespace(str, '"'); + output += str; + parseConcatenatedString(); + return true; + } else if (text[i] === '\\') { + // handle escaped content like \n or \u2605 + const char = text.charAt(i + 1); + const escapeChar = escapeCharacters[char]; + if (escapeChar !== undefined) { + str += text.slice(i, i + 2); + i += 2; + } else if (char === 'u') { + let j = 2; + while (j < 6 && isHex(text[i + j])) { + j++; + } + if (j === 6) { + str += text.slice(i, i + 6); + i += 6; + } else if (i + j >= text.length) { + // repair invalid or truncated unicode char at the end of the text + // by removing the unicode char and ending the string here + i = text.length; + } else { + throwInvalidUnicodeCharacter(); + } + } else { + // repair invalid escape character: remove it + str += char; + i += 2; + } + } else { + // handle regular characters + const char = text.charAt(i); + if (char === '"' && text[i - 1] !== '\\') { + // repair unescaped double quote + str += `\\${char}`; + i++; + } else if (isControlCharacter(char)) { + // unescaped control character + str += controlCharacters[char]; + i++; + } else { + if (!isValidStringCharacter(char)) { + throwInvalidCharacter(char); + } + str += char; + i++; + } + } + if (skipEscapeChars) { + // repair: skipped escape character (nothing to do) + skipEscapeCharacter(); + } + } + } + return false; + } + + /** + * Repair concatenated strings like "hello" + "world", change this into "helloworld" + */ + function parseConcatenatedString() { + let processed = false; + parseWhitespaceAndSkipComments(); + while (text[i] === '+') { + processed = true; + i++; + parseWhitespaceAndSkipComments(); + + // repair: remove the end quote of the first string + output = stripLastOccurrence(output, '"', true); + const start = output.length; + const parsedStr = parseString(); + if (parsedStr) { + // repair: remove the start quote of the second string + output = removeAtIndex(output, start, 1); + } else { + // repair: remove the + because it is not followed by a string + output = insertBeforeLastWhitespace(output, '"'); + } + } + return processed; + } + + /** + * Parse a number like 2.4 or 2.4e6 + */ + function parseNumber() { + const start = i; + if (text[i] === '-') { + i++; + if (atEndOfNumber()) { + repairNumberEndingWithNumericSymbol(start); + return true; + } + if (!isDigit(text[i])) { + i = start; + return false; + } + } + + // Note that in JSON leading zeros like "00789" are not allowed. + // We will allow all leading zeros here though and at the end of parseNumber + // check against trailing zeros and repair that if needed. + // Leading zeros can have meaning, so we should not clear them. + while (isDigit(text[i])) { + i++; + } + if (text[i] === '.') { + i++; + if (atEndOfNumber()) { + repairNumberEndingWithNumericSymbol(start); + return true; + } + if (!isDigit(text[i])) { + i = start; + return false; + } + while (isDigit(text[i])) { + i++; + } + } + if (text[i] === 'e' || text[i] === 'E') { + i++; + if (text[i] === '-' || text[i] === '+') { + i++; + } + if (atEndOfNumber()) { + repairNumberEndingWithNumericSymbol(start); + return true; + } + if (!isDigit(text[i])) { + i = start; + return false; + } + while (isDigit(text[i])) { + i++; + } + } + + // if we're not at the end of the number by this point, allow this to be parsed as another type + if (!atEndOfNumber()) { + i = start; + return false; + } + if (i > start) { + // repair a number with leading zeros like "00789" + const num = text.slice(start, i); + const hasInvalidLeadingZero = /^0\d/.test(num); + output += hasInvalidLeadingZero ? `"${num}"` : num; + return true; + } + return false; + } + + /** + * Parse keywords true, false, null + * Repair Python keywords True, False, None + */ + function parseKeywords() { + return parseKeyword('true', 'true') || parseKeyword('false', 'false') || parseKeyword('null', 'null') || + // repair Python keywords True, False, None + parseKeyword('True', 'true') || parseKeyword('False', 'false') || parseKeyword('None', 'null'); + } + function parseKeyword(name, value) { + if (text.slice(i, i + name.length) === name) { + output += value; + i += name.length; + return true; + } + return false; + } + + /** + * Repair an unquoted string by adding quotes around it + * Repair a MongoDB function call like NumberLong("2") + * Repair a JSONP function call like callback({...}); + */ + function parseUnquotedString(isKey) { + // note that the symbol can end with whitespaces: we stop at the next delimiter + // also, note that we allow strings to contain a slash / in order to support repairing regular expressions + const start = i; + if (isFunctionNameCharStart(text[i])) { + while (i < text.length && isFunctionNameChar(text[i])) { + i++; + } + let j = i; + while (isWhitespace(text, j)) { + j++; + } + if (text[j] === '(') { + // repair a MongoDB function call like NumberLong("2") + // repair a JSONP function call like callback({...}); + i = j + 1; + parseValue(); + if (text[i] === ')') { + // repair: skip close bracket of function call + i++; + if (text[i] === ';') { + // repair: skip semicolon after JSONP call + i++; + } + } + return true; + } + } + while (i < text.length && !isUnquotedStringDelimiter(text[i]) && !isQuote(text[i]) && (!isKey || text[i] !== ':')) { + i++; + } + + // test start of an url like "https://..." (this would be parsed as a comment) + if (text[i - 1] === ':' && regexUrlStart.test(text.substring(start, i + 2))) { + while (i < text.length && regexUrlChar.test(text[i])) { + i++; + } + } + if (i > start) { + // repair unquoted string + // also, repair undefined into null + + // first, go back to prevent getting trailing whitespaces in the string + while (isWhitespace(text, i - 1) && i > 0) { + i--; + } + const symbol = text.slice(start, i); + output += symbol === 'undefined' ? 'null' : JSON.stringify(symbol); + if (text[i] === '"') { + // we had a missing start quote, but now we encountered the end quote, so we can skip that one + i++; + } + return true; + } + } + function parseRegex() { + if (text[i] === '/') { + const start = i; + i++; + while (i < text.length && (text[i] !== '/' || text[i - 1] === '\\')) { + i++; + } + i++; + output += `"${text.substring(start, i)}"`; + return true; + } + } + function prevNonWhitespaceIndex(start) { + let prev = start; + while (prev > 0 && isWhitespace(text, prev)) { + prev--; + } + return prev; + } + function atEndOfNumber() { + return i >= text.length || isDelimiter(text[i]) || isWhitespace(text, i); + } + function repairNumberEndingWithNumericSymbol(start) { + // repair numbers cut off at the end + // this will only be called when we end after a '.', '-', or 'e' and does not + // change the number more than it needs to make it valid JSON + output += `${text.slice(start, i)}0`; + } + function throwInvalidCharacter(char) { + throw new JSONRepairError(`Invalid character ${JSON.stringify(char)}`, i); + } + function throwUnexpectedCharacter() { + throw new JSONRepairError(`Unexpected character ${JSON.stringify(text[i])}`, i); + } + function throwUnexpectedEnd() { + throw new JSONRepairError('Unexpected end of json string', text.length); + } + function throwObjectKeyExpected() { + throw new JSONRepairError('Object key expected', i); + } + function throwColonExpected() { + throw new JSONRepairError('Colon expected', i); + } + function throwInvalidUnicodeCharacter() { + const chars = text.slice(i, i + 6); + throw new JSONRepairError(`Invalid unicode character "${chars}"`, i); + } + } + function atEndOfBlockComment(text, i) { + return text[i] === '*' && text[i + 1] === '/'; + } + + exports.JSONRepairError = JSONRepairError; + exports.jsonrepair = jsonrepair; + +})); +//# sourceMappingURL=jsonrepair.js.map diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/umd/jsonrepair.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/umd/jsonrepair.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ddd6a44839cea88751a93d09b5d5170d87563a1a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/umd/jsonrepair.js.map @@ -0,0 +1 @@ +{"version":3,"file":"jsonrepair.js","sources":["../esm/utils/JSONRepairError.js","../esm/utils/stringUtils.js","../esm/regular/jsonrepair.js"],"sourcesContent":["export class JSONRepairError extends Error {\n constructor(message, position) {\n super(`${message} at position ${position}`);\n this.position = position;\n }\n}\n//# sourceMappingURL=JSONRepairError.js.map","const codeSpace = 0x20; // \" \"\nconst codeNewline = 0xa; // \"\\n\"\nconst codeTab = 0x9; // \"\\t\"\nconst codeReturn = 0xd; // \"\\r\"\nconst codeNonBreakingSpace = 0xa0;\nconst codeEnQuad = 0x2000;\nconst codeHairSpace = 0x200a;\nconst codeNarrowNoBreakSpace = 0x202f;\nconst codeMediumMathematicalSpace = 0x205f;\nconst codeIdeographicSpace = 0x3000;\nexport function isHex(char) {\n return /^[0-9A-Fa-f]$/.test(char);\n}\nexport function isDigit(char) {\n return char >= '0' && char <= '9';\n}\nexport function isValidStringCharacter(char) {\n // note that the valid range is between \\u{0020} and \\u{10ffff},\n // but in JavaScript it is not possible to create a code point larger than\n // \\u{10ffff}, so there is no need to test for that here.\n return char >= '\\u0020';\n}\nexport function isDelimiter(char) {\n return ',:[]/{}()\\n+'.includes(char);\n}\nexport function isFunctionNameCharStart(char) {\n return char >= 'a' && char <= 'z' || char >= 'A' && char <= 'Z' || char === '_' || char === '$';\n}\nexport function isFunctionNameChar(char) {\n return char >= 'a' && char <= 'z' || char >= 'A' && char <= 'Z' || char === '_' || char === '$' || char >= '0' && char <= '9';\n}\n\n// matches \"https://\" and other schemas\nexport const regexUrlStart = /^(http|https|ftp|mailto|file|data|irc):\\/\\/$/;\n\n// matches all valid URL characters EXCEPT \"[\", \"]\", and \",\", since that are important JSON delimiters\nexport const regexUrlChar = /^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;\nexport function isUnquotedStringDelimiter(char) {\n return ',[]/{}\\n+'.includes(char);\n}\nexport function isStartOfValue(char) {\n return isQuote(char) || regexStartOfValue.test(char);\n}\n\n// alpha, number, minus, or opening bracket or brace\nconst regexStartOfValue = /^[[{\\w-]$/;\nexport function isControlCharacter(char) {\n return char === '\\n' || char === '\\r' || char === '\\t' || char === '\\b' || char === '\\f';\n}\n/**\n * Check if the given character is a whitespace character like space, tab, or\n * newline\n */\nexport function isWhitespace(text, index) {\n const code = text.charCodeAt(index);\n return code === codeSpace || code === codeNewline || code === codeTab || code === codeReturn;\n}\n\n/**\n * Check if the given character is a whitespace character like space or tab,\n * but NOT a newline\n */\nexport function isWhitespaceExceptNewline(text, index) {\n const code = text.charCodeAt(index);\n return code === codeSpace || code === codeTab || code === codeReturn;\n}\n\n/**\n * Check if the given character is a special whitespace character, some\n * unicode variant\n */\nexport function isSpecialWhitespace(text, index) {\n const code = text.charCodeAt(index);\n return code === codeNonBreakingSpace || code >= codeEnQuad && code <= codeHairSpace || code === codeNarrowNoBreakSpace || code === codeMediumMathematicalSpace || code === codeIdeographicSpace;\n}\n\n/**\n * Test whether the given character is a quote or double quote character.\n * Also tests for special variants of quotes.\n */\nexport function isQuote(char) {\n // the first check double quotes, since that occurs most often\n return isDoubleQuoteLike(char) || isSingleQuoteLike(char);\n}\n\n/**\n * Test whether the given character is a double quote character.\n * Also tests for special variants of double quotes.\n */\nexport function isDoubleQuoteLike(char) {\n return char === '\"' || char === '\\u201c' || char === '\\u201d';\n}\n\n/**\n * Test whether the given character is a double quote character.\n * Does NOT test for special variants of double quotes.\n */\nexport function isDoubleQuote(char) {\n return char === '\"';\n}\n\n/**\n * Test whether the given character is a single quote character.\n * Also tests for special variants of single quotes.\n */\nexport function isSingleQuoteLike(char) {\n return char === \"'\" || char === '\\u2018' || char === '\\u2019' || char === '\\u0060' || char === '\\u00b4';\n}\n\n/**\n * Test whether the given character is a single quote character.\n * Does NOT test for special variants of single quotes.\n */\nexport function isSingleQuote(char) {\n return char === \"'\";\n}\n\n/**\n * Strip last occurrence of textToStrip from text\n */\nexport function stripLastOccurrence(text, textToStrip) {\n let stripRemainingText = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n const index = text.lastIndexOf(textToStrip);\n return index !== -1 ? text.substring(0, index) + (stripRemainingText ? '' : text.substring(index + 1)) : text;\n}\nexport function insertBeforeLastWhitespace(text, textToInsert) {\n let index = text.length;\n if (!isWhitespace(text, index - 1)) {\n // no trailing whitespaces\n return text + textToInsert;\n }\n while (isWhitespace(text, index - 1)) {\n index--;\n }\n return text.substring(0, index) + textToInsert + text.substring(index);\n}\nexport function removeAtIndex(text, start, count) {\n return text.substring(0, start) + text.substring(start + count);\n}\n\n/**\n * Test whether a string ends with a newline or comma character and optional whitespace\n */\nexport function endsWithCommaOrNewline(text) {\n return /[,\\n][ \\t\\r]*$/.test(text);\n}\n//# sourceMappingURL=stringUtils.js.map","import { JSONRepairError } from '../utils/JSONRepairError.js';\nimport { endsWithCommaOrNewline, insertBeforeLastWhitespace, isControlCharacter, isDelimiter, isDigit, isDoubleQuote, isDoubleQuoteLike, isFunctionNameChar, isFunctionNameCharStart, isHex, isQuote, isSingleQuote, isSingleQuoteLike, isSpecialWhitespace, isStartOfValue, isUnquotedStringDelimiter, isValidStringCharacter, isWhitespace, isWhitespaceExceptNewline, regexUrlChar, regexUrlStart, removeAtIndex, stripLastOccurrence } from '../utils/stringUtils.js';\nconst controlCharacters = {\n '\\b': '\\\\b',\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t'\n};\n\n// map with all escape characters\nconst escapeCharacters = {\n '\"': '\"',\n '\\\\': '\\\\',\n '/': '/',\n b: '\\b',\n f: '\\f',\n n: '\\n',\n r: '\\r',\n t: '\\t'\n // note that \\u is handled separately in parseString()\n};\n\n/**\n * Repair a string containing an invalid JSON document.\n * For example changes JavaScript notation into JSON notation.\n *\n * Example:\n *\n * try {\n * const json = \"{name: 'John'}\"\n * const repaired = jsonrepair(json)\n * console.log(repaired)\n * // '{\"name\": \"John\"}'\n * } catch (err) {\n * console.error(err)\n * }\n *\n */\nexport function jsonrepair(text) {\n let i = 0; // current index in text\n let output = ''; // generated output\n\n parseMarkdownCodeBlock(['```', '[```', '{```']);\n const processed = parseValue();\n if (!processed) {\n throwUnexpectedEnd();\n }\n parseMarkdownCodeBlock(['```', '```]', '```}']);\n const processedComma = parseCharacter(',');\n if (processedComma) {\n parseWhitespaceAndSkipComments();\n }\n if (isStartOfValue(text[i]) && endsWithCommaOrNewline(output)) {\n // start of a new value after end of the root level object: looks like\n // newline delimited JSON -> turn into a root level array\n if (!processedComma) {\n // repair missing comma\n output = insertBeforeLastWhitespace(output, ',');\n }\n parseNewlineDelimitedJSON();\n } else if (processedComma) {\n // repair: remove trailing comma\n output = stripLastOccurrence(output, ',');\n }\n\n // repair redundant end quotes\n while (text[i] === '}' || text[i] === ']') {\n i++;\n parseWhitespaceAndSkipComments();\n }\n if (i >= text.length) {\n // reached the end of the document properly\n return output;\n }\n throwUnexpectedCharacter();\n function parseValue() {\n parseWhitespaceAndSkipComments();\n const processed = parseObject() || parseArray() || parseString() || parseNumber() || parseKeywords() || parseUnquotedString(false) || parseRegex();\n parseWhitespaceAndSkipComments();\n return processed;\n }\n function parseWhitespaceAndSkipComments() {\n let skipNewline = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;\n const start = i;\n let changed = parseWhitespace(skipNewline);\n do {\n changed = parseComment();\n if (changed) {\n changed = parseWhitespace(skipNewline);\n }\n } while (changed);\n return i > start;\n }\n function parseWhitespace(skipNewline) {\n const _isWhiteSpace = skipNewline ? isWhitespace : isWhitespaceExceptNewline;\n let whitespace = '';\n while (true) {\n if (_isWhiteSpace(text, i)) {\n whitespace += text[i];\n i++;\n } else if (isSpecialWhitespace(text, i)) {\n // repair special whitespace\n whitespace += ' ';\n i++;\n } else {\n break;\n }\n }\n if (whitespace.length > 0) {\n output += whitespace;\n return true;\n }\n return false;\n }\n function parseComment() {\n // find a block comment '/* ... */'\n if (text[i] === '/' && text[i + 1] === '*') {\n // repair block comment by skipping it\n while (i < text.length && !atEndOfBlockComment(text, i)) {\n i++;\n }\n i += 2;\n return true;\n }\n\n // find a line comment '// ...'\n if (text[i] === '/' && text[i + 1] === '/') {\n // repair line comment by skipping it\n while (i < text.length && text[i] !== '\\n') {\n i++;\n }\n return true;\n }\n return false;\n }\n function parseMarkdownCodeBlock(blocks) {\n // find and skip over a Markdown fenced code block:\n // ``` ... ```\n // or\n // ```json ... ```\n if (skipMarkdownCodeBlock(blocks)) {\n if (isFunctionNameCharStart(text[i])) {\n // strip the optional language specifier like \"json\"\n while (i < text.length && isFunctionNameChar(text[i])) {\n i++;\n }\n }\n parseWhitespaceAndSkipComments();\n return true;\n }\n return false;\n }\n function skipMarkdownCodeBlock(blocks) {\n for (const block of blocks) {\n const end = i + block.length;\n if (text.slice(i, end) === block) {\n i = end;\n return true;\n }\n }\n return false;\n }\n function parseCharacter(char) {\n if (text[i] === char) {\n output += text[i];\n i++;\n return true;\n }\n return false;\n }\n function skipCharacter(char) {\n if (text[i] === char) {\n i++;\n return true;\n }\n return false;\n }\n function skipEscapeCharacter() {\n return skipCharacter('\\\\');\n }\n\n /**\n * Skip ellipsis like \"[1,2,3,...]\" or \"[1,2,3,...,9]\" or \"[...,7,8,9]\"\n * or a similar construct in objects.\n */\n function skipEllipsis() {\n parseWhitespaceAndSkipComments();\n if (text[i] === '.' && text[i + 1] === '.' && text[i + 2] === '.') {\n // repair: remove the ellipsis (three dots) and optionally a comma\n i += 3;\n parseWhitespaceAndSkipComments();\n skipCharacter(',');\n return true;\n }\n return false;\n }\n\n /**\n * Parse an object like '{\"key\": \"value\"}'\n */\n function parseObject() {\n if (text[i] === '{') {\n output += '{';\n i++;\n parseWhitespaceAndSkipComments();\n\n // repair: skip leading comma like in {, message: \"hi\"}\n if (skipCharacter(',')) {\n parseWhitespaceAndSkipComments();\n }\n let initial = true;\n while (i < text.length && text[i] !== '}') {\n let processedComma;\n if (!initial) {\n processedComma = parseCharacter(',');\n if (!processedComma) {\n // repair missing comma\n output = insertBeforeLastWhitespace(output, ',');\n }\n parseWhitespaceAndSkipComments();\n } else {\n processedComma = true;\n initial = false;\n }\n skipEllipsis();\n const processedKey = parseString() || parseUnquotedString(true);\n if (!processedKey) {\n if (text[i] === '}' || text[i] === '{' || text[i] === ']' || text[i] === '[' || text[i] === undefined) {\n // repair trailing comma\n output = stripLastOccurrence(output, ',');\n } else {\n throwObjectKeyExpected();\n }\n break;\n }\n parseWhitespaceAndSkipComments();\n const processedColon = parseCharacter(':');\n const truncatedText = i >= text.length;\n if (!processedColon) {\n if (isStartOfValue(text[i]) || truncatedText) {\n // repair missing colon\n output = insertBeforeLastWhitespace(output, ':');\n } else {\n throwColonExpected();\n }\n }\n const processedValue = parseValue();\n if (!processedValue) {\n if (processedColon || truncatedText) {\n // repair missing object value\n output += 'null';\n } else {\n throwColonExpected();\n }\n }\n }\n if (text[i] === '}') {\n output += '}';\n i++;\n } else {\n // repair missing end bracket\n output = insertBeforeLastWhitespace(output, '}');\n }\n return true;\n }\n return false;\n }\n\n /**\n * Parse an array like '[\"item1\", \"item2\", ...]'\n */\n function parseArray() {\n if (text[i] === '[') {\n output += '[';\n i++;\n parseWhitespaceAndSkipComments();\n\n // repair: skip leading comma like in [,1,2,3]\n if (skipCharacter(',')) {\n parseWhitespaceAndSkipComments();\n }\n let initial = true;\n while (i < text.length && text[i] !== ']') {\n if (!initial) {\n const processedComma = parseCharacter(',');\n if (!processedComma) {\n // repair missing comma\n output = insertBeforeLastWhitespace(output, ',');\n }\n } else {\n initial = false;\n }\n skipEllipsis();\n const processedValue = parseValue();\n if (!processedValue) {\n // repair trailing comma\n output = stripLastOccurrence(output, ',');\n break;\n }\n }\n if (text[i] === ']') {\n output += ']';\n i++;\n } else {\n // repair missing closing array bracket\n output = insertBeforeLastWhitespace(output, ']');\n }\n return true;\n }\n return false;\n }\n\n /**\n * Parse and repair Newline Delimited JSON (NDJSON):\n * multiple JSON objects separated by a newline character\n */\n function parseNewlineDelimitedJSON() {\n // repair NDJSON\n let initial = true;\n let processedValue = true;\n while (processedValue) {\n if (!initial) {\n // parse optional comma, insert when missing\n const processedComma = parseCharacter(',');\n if (!processedComma) {\n // repair: add missing comma\n output = insertBeforeLastWhitespace(output, ',');\n }\n } else {\n initial = false;\n }\n processedValue = parseValue();\n }\n if (!processedValue) {\n // repair: remove trailing comma\n output = stripLastOccurrence(output, ',');\n }\n\n // repair: wrap the output inside array brackets\n output = `[\\n${output}\\n]`;\n }\n\n /**\n * Parse a string enclosed by double quotes \"...\". Can contain escaped quotes\n * Repair strings enclosed in single quotes or special quotes\n * Repair an escaped string\n *\n * The function can run in two stages:\n * - First, it assumes the string has a valid end quote\n * - If it turns out that the string does not have a valid end quote followed\n * by a delimiter (which should be the case), the function runs again in a\n * more conservative way, stopping the string at the first next delimiter\n * and fixing the string by inserting a quote there, or stopping at a\n * stop index detected in the first iteration.\n */\n function parseString() {\n let stopAtDelimiter = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;\n let stopAtIndex = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : -1;\n let skipEscapeChars = text[i] === '\\\\';\n if (skipEscapeChars) {\n // repair: remove the first escape character\n i++;\n skipEscapeChars = true;\n }\n if (isQuote(text[i])) {\n // double quotes are correct JSON,\n // single quotes come from JavaScript for example, we assume it will have a correct single end quote too\n // otherwise, we will match any double-quote-like start with a double-quote-like end,\n // or any single-quote-like start with a single-quote-like end\n const isEndQuote = isDoubleQuote(text[i]) ? isDoubleQuote : isSingleQuote(text[i]) ? isSingleQuote : isSingleQuoteLike(text[i]) ? isSingleQuoteLike : isDoubleQuoteLike;\n const iBefore = i;\n const oBefore = output.length;\n let str = '\"';\n i++;\n while (true) {\n if (i >= text.length) {\n // end of text, we are missing an end quote\n\n const iPrev = prevNonWhitespaceIndex(i - 1);\n if (!stopAtDelimiter && isDelimiter(text.charAt(iPrev))) {\n // if the text ends with a delimiter, like [\"hello],\n // so the missing end quote should be inserted before this delimiter\n // retry parsing the string, stopping at the first next delimiter\n i = iBefore;\n output = output.substring(0, oBefore);\n return parseString(true);\n }\n\n // repair missing quote\n str = insertBeforeLastWhitespace(str, '\"');\n output += str;\n return true;\n }\n if (i === stopAtIndex) {\n // use the stop index detected in the first iteration, and repair end quote\n str = insertBeforeLastWhitespace(str, '\"');\n output += str;\n return true;\n }\n if (isEndQuote(text[i])) {\n // end quote\n // let us check what is before and after the quote to verify whether this is a legit end quote\n const iQuote = i;\n const oQuote = str.length;\n str += '\"';\n i++;\n output += str;\n parseWhitespaceAndSkipComments(false);\n if (stopAtDelimiter || i >= text.length || isDelimiter(text[i]) || isQuote(text[i]) || isDigit(text[i])) {\n // The quote is followed by the end of the text, a delimiter,\n // or a next value. So the quote is indeed the end of the string.\n parseConcatenatedString();\n return true;\n }\n const iPrevChar = prevNonWhitespaceIndex(iQuote - 1);\n const prevChar = text.charAt(iPrevChar);\n if (prevChar === ',') {\n // A comma followed by a quote, like '{\"a\":\"b,c,\"d\":\"e\"}'.\n // We assume that the quote is a start quote, and that the end quote\n // should have been located right before the comma but is missing.\n i = iBefore;\n output = output.substring(0, oBefore);\n return parseString(false, iPrevChar);\n }\n if (isDelimiter(prevChar)) {\n // This is not the right end quote: it is preceded by a delimiter,\n // and NOT followed by a delimiter. So, there is an end quote missing\n // parse the string again and then stop at the first next delimiter\n i = iBefore;\n output = output.substring(0, oBefore);\n return parseString(true);\n }\n\n // revert to right after the quote but before any whitespace, and continue parsing the string\n output = output.substring(0, oBefore);\n i = iQuote + 1;\n\n // repair unescaped quote\n str = `${str.substring(0, oQuote)}\\\\${str.substring(oQuote)}`;\n } else if (stopAtDelimiter && isUnquotedStringDelimiter(text[i])) {\n // we're in the mode to stop the string at the first delimiter\n // because there is an end quote missing\n\n // test start of an url like \"https://...\" (this would be parsed as a comment)\n if (text[i - 1] === ':' && regexUrlStart.test(text.substring(iBefore + 1, i + 2))) {\n while (i < text.length && regexUrlChar.test(text[i])) {\n str += text[i];\n i++;\n }\n }\n\n // repair missing quote\n str = insertBeforeLastWhitespace(str, '\"');\n output += str;\n parseConcatenatedString();\n return true;\n } else if (text[i] === '\\\\') {\n // handle escaped content like \\n or \\u2605\n const char = text.charAt(i + 1);\n const escapeChar = escapeCharacters[char];\n if (escapeChar !== undefined) {\n str += text.slice(i, i + 2);\n i += 2;\n } else if (char === 'u') {\n let j = 2;\n while (j < 6 && isHex(text[i + j])) {\n j++;\n }\n if (j === 6) {\n str += text.slice(i, i + 6);\n i += 6;\n } else if (i + j >= text.length) {\n // repair invalid or truncated unicode char at the end of the text\n // by removing the unicode char and ending the string here\n i = text.length;\n } else {\n throwInvalidUnicodeCharacter();\n }\n } else {\n // repair invalid escape character: remove it\n str += char;\n i += 2;\n }\n } else {\n // handle regular characters\n const char = text.charAt(i);\n if (char === '\"' && text[i - 1] !== '\\\\') {\n // repair unescaped double quote\n str += `\\\\${char}`;\n i++;\n } else if (isControlCharacter(char)) {\n // unescaped control character\n str += controlCharacters[char];\n i++;\n } else {\n if (!isValidStringCharacter(char)) {\n throwInvalidCharacter(char);\n }\n str += char;\n i++;\n }\n }\n if (skipEscapeChars) {\n // repair: skipped escape character (nothing to do)\n skipEscapeCharacter();\n }\n }\n }\n return false;\n }\n\n /**\n * Repair concatenated strings like \"hello\" + \"world\", change this into \"helloworld\"\n */\n function parseConcatenatedString() {\n let processed = false;\n parseWhitespaceAndSkipComments();\n while (text[i] === '+') {\n processed = true;\n i++;\n parseWhitespaceAndSkipComments();\n\n // repair: remove the end quote of the first string\n output = stripLastOccurrence(output, '\"', true);\n const start = output.length;\n const parsedStr = parseString();\n if (parsedStr) {\n // repair: remove the start quote of the second string\n output = removeAtIndex(output, start, 1);\n } else {\n // repair: remove the + because it is not followed by a string\n output = insertBeforeLastWhitespace(output, '\"');\n }\n }\n return processed;\n }\n\n /**\n * Parse a number like 2.4 or 2.4e6\n */\n function parseNumber() {\n const start = i;\n if (text[i] === '-') {\n i++;\n if (atEndOfNumber()) {\n repairNumberEndingWithNumericSymbol(start);\n return true;\n }\n if (!isDigit(text[i])) {\n i = start;\n return false;\n }\n }\n\n // Note that in JSON leading zeros like \"00789\" are not allowed.\n // We will allow all leading zeros here though and at the end of parseNumber\n // check against trailing zeros and repair that if needed.\n // Leading zeros can have meaning, so we should not clear them.\n while (isDigit(text[i])) {\n i++;\n }\n if (text[i] === '.') {\n i++;\n if (atEndOfNumber()) {\n repairNumberEndingWithNumericSymbol(start);\n return true;\n }\n if (!isDigit(text[i])) {\n i = start;\n return false;\n }\n while (isDigit(text[i])) {\n i++;\n }\n }\n if (text[i] === 'e' || text[i] === 'E') {\n i++;\n if (text[i] === '-' || text[i] === '+') {\n i++;\n }\n if (atEndOfNumber()) {\n repairNumberEndingWithNumericSymbol(start);\n return true;\n }\n if (!isDigit(text[i])) {\n i = start;\n return false;\n }\n while (isDigit(text[i])) {\n i++;\n }\n }\n\n // if we're not at the end of the number by this point, allow this to be parsed as another type\n if (!atEndOfNumber()) {\n i = start;\n return false;\n }\n if (i > start) {\n // repair a number with leading zeros like \"00789\"\n const num = text.slice(start, i);\n const hasInvalidLeadingZero = /^0\\d/.test(num);\n output += hasInvalidLeadingZero ? `\"${num}\"` : num;\n return true;\n }\n return false;\n }\n\n /**\n * Parse keywords true, false, null\n * Repair Python keywords True, False, None\n */\n function parseKeywords() {\n return parseKeyword('true', 'true') || parseKeyword('false', 'false') || parseKeyword('null', 'null') ||\n // repair Python keywords True, False, None\n parseKeyword('True', 'true') || parseKeyword('False', 'false') || parseKeyword('None', 'null');\n }\n function parseKeyword(name, value) {\n if (text.slice(i, i + name.length) === name) {\n output += value;\n i += name.length;\n return true;\n }\n return false;\n }\n\n /**\n * Repair an unquoted string by adding quotes around it\n * Repair a MongoDB function call like NumberLong(\"2\")\n * Repair a JSONP function call like callback({...});\n */\n function parseUnquotedString(isKey) {\n // note that the symbol can end with whitespaces: we stop at the next delimiter\n // also, note that we allow strings to contain a slash / in order to support repairing regular expressions\n const start = i;\n if (isFunctionNameCharStart(text[i])) {\n while (i < text.length && isFunctionNameChar(text[i])) {\n i++;\n }\n let j = i;\n while (isWhitespace(text, j)) {\n j++;\n }\n if (text[j] === '(') {\n // repair a MongoDB function call like NumberLong(\"2\")\n // repair a JSONP function call like callback({...});\n i = j + 1;\n parseValue();\n if (text[i] === ')') {\n // repair: skip close bracket of function call\n i++;\n if (text[i] === ';') {\n // repair: skip semicolon after JSONP call\n i++;\n }\n }\n return true;\n }\n }\n while (i < text.length && !isUnquotedStringDelimiter(text[i]) && !isQuote(text[i]) && (!isKey || text[i] !== ':')) {\n i++;\n }\n\n // test start of an url like \"https://...\" (this would be parsed as a comment)\n if (text[i - 1] === ':' && regexUrlStart.test(text.substring(start, i + 2))) {\n while (i < text.length && regexUrlChar.test(text[i])) {\n i++;\n }\n }\n if (i > start) {\n // repair unquoted string\n // also, repair undefined into null\n\n // first, go back to prevent getting trailing whitespaces in the string\n while (isWhitespace(text, i - 1) && i > 0) {\n i--;\n }\n const symbol = text.slice(start, i);\n output += symbol === 'undefined' ? 'null' : JSON.stringify(symbol);\n if (text[i] === '\"') {\n // we had a missing start quote, but now we encountered the end quote, so we can skip that one\n i++;\n }\n return true;\n }\n }\n function parseRegex() {\n if (text[i] === '/') {\n const start = i;\n i++;\n while (i < text.length && (text[i] !== '/' || text[i - 1] === '\\\\')) {\n i++;\n }\n i++;\n output += `\"${text.substring(start, i)}\"`;\n return true;\n }\n }\n function prevNonWhitespaceIndex(start) {\n let prev = start;\n while (prev > 0 && isWhitespace(text, prev)) {\n prev--;\n }\n return prev;\n }\n function atEndOfNumber() {\n return i >= text.length || isDelimiter(text[i]) || isWhitespace(text, i);\n }\n function repairNumberEndingWithNumericSymbol(start) {\n // repair numbers cut off at the end\n // this will only be called when we end after a '.', '-', or 'e' and does not\n // change the number more than it needs to make it valid JSON\n output += `${text.slice(start, i)}0`;\n }\n function throwInvalidCharacter(char) {\n throw new JSONRepairError(`Invalid character ${JSON.stringify(char)}`, i);\n }\n function throwUnexpectedCharacter() {\n throw new JSONRepairError(`Unexpected character ${JSON.stringify(text[i])}`, i);\n }\n function throwUnexpectedEnd() {\n throw new JSONRepairError('Unexpected end of json string', text.length);\n }\n function throwObjectKeyExpected() {\n throw new JSONRepairError('Object key expected', i);\n }\n function throwColonExpected() {\n throw new JSONRepairError('Colon expected', i);\n }\n function throwInvalidUnicodeCharacter() {\n const chars = text.slice(i, i + 6);\n throw new JSONRepairError(`Invalid unicode character \"${chars}\"`, i);\n }\n}\nfunction atEndOfBlockComment(text, i) {\n return text[i] === '*' && text[i + 1] === '/';\n}\n//# sourceMappingURL=jsonrepair.js.map"],"names":[],"mappings":";;;;;;EAAO,MAAM,eAAe,SAAS,KAAK,CAAC;EAC3C,EAAE,WAAW,CAAC,OAAO,EAAE,QAAQ,EAAE;EACjC,IAAI,KAAK,CAAC,CAAC,EAAE,OAAO,CAAC,aAAa,EAAE,QAAQ,CAAC,CAAC,CAAC;EAC/C,IAAI,IAAI,CAAC,QAAQ,GAAG,QAAQ;EAC5B;EACA;;ECLA,MAAM,SAA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qB,EAAE,CAAC,CAAC;EACvD;EACA,EAAE,SAAS,kBAAkB,GAAG;EAChC,IAAI,MAAM,IAAI,eAAe,CAAC,gBAAgB,EAAE,CAAC,CAAC;EAClD;EACA,EAAE,SAAS,4BAA4B,GAAG;EAC1C,IAAI,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC;EACtC,IAAI,MAAM,IAAI,eAAe,CAAC,CAAC,2BAA2B,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;EACxE;EACA;EACA,SAAS,mBAAmB,CAAC,IAAI,EAAE,CAAC,EAAE;EACtC,EAAE,OAAO,IAAI,CAAC,CAAC,CAAC,KAAK,GAAG,IAAI,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,GAAG;EAC/C;;;;;;;;;"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/umd/jsonrepair.min.js b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/umd/jsonrepair.min.js new file mode 100644 index 0000000000000000000000000000000000000000..efe0f47cb6de6e3d792814fab959ae01a4389455 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/umd/jsonrepair.min.js @@ -0,0 +1,3 @@ +((t,n)=>{"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n((t="undefined"!=typeof globalThis?globalThis:t||self).JSONRepair={})})(this,function(t){class x extends Error{constructor(t,n){super(t+" at position "+n),this.position=n}}let r=32,e=10,i=9,f=13,a=160,h=8192,y=8202,O=8239,N=8287,J=12288;function S(t){return"0"<=t&&t<="9"}function j(t){return",:[]/{}()\n+".includes(t)}function k(t){return"a"<=t&&t<="z"||"A"<=t&&t<="Z"||"_"===t||"$"===t}function C(t){return"a"<=t&&t<="z"||"A"<=t&&t<="Z"||"_"===t||"$"===t||"0"<=t&&t<="9"}let m=/^(http|https|ftp|mailto|file|data|irc):\/\/$/,z=/^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;function E(t){return",[]/{}\n+".includes(t)}function I(t){return _(t)||n.test(t)}let n=/^[[{\w-]$/;function T(t,n){t=t.charCodeAt(n);return t===r||t===e||t===i||t===f}function Z(t,n){t=t.charCodeAt(n);return t===r||t===i||t===f}function _(t){return F(t)||U(t)}function F(t){return'"'===t||"“"===t||"”"===t}function R(t){return'"'===t}function U(t){return"'"===t||"‘"===t||"’"===t||"`"===t||"´"===t}function q(t){return"'"===t}function B(t,n,r){r=2=g.length)return v;throw new x("Unexpected character "+JSON.stringify(g[d]),d);function f(){b();var t=(()=>{if("{"!==g[d])return!1;{v+="{",d++,b(),p(",")&&b();let n=!0;for(;d{throw new x("Object key expected",d)})();break}b();var r=u(":"),e=d>=g.length,i=(r||(I(g[d])||e?v=D(v,":"):c()),f());i||(r||e?v+="null":c())}return"}"===g[d]?(v+="}",d++):v=D(v,"}"),!0}})()||(()=>{if("["!==g[d])return!1;{v+="[",d++,b(),p(",")&&b();let t=!0;for(;d{var t,n,r=d;if("-"===g[d]){if(d++,i())return s(r),!0;if(!S(g[d]))return d=r,!1}for(;S(g[d]);)d++;if("."===g[d]){if(d++,i())return s(r),!0;if(!S(g[d]))return d=r,!1;for(;S(g[d]);)d++}if("e"===g[d]||"E"===g[d]){if(d++,"-"!==g[d]&&"+"!==g[d]||d++,i())return s(r),!0;if(!S(g[d]))return d=r,!1;for(;S(g[d]);)d++}if(i()){if(d>r)return t=g.slice(r,d),n=/^0\d/.test(t),v+=n?`"${t}"`:t,!0}else d=r;return!1})()||r("true","true")||r("false","false")||r("null","null")||r("True","true")||r("False","false")||r("None","null")||l(!1)||(()=>{if("/"===g[d]){var t=d;for(d++;d{if("/"===g[d]&&"*"===g[d+1]){for(;d"*"===t[n]&&"/"===t[n+1])(g,d);)d++;d+=2}else{if("/"!==g[d]||"/"!==g[d+1])return!1;for(;d=h&&n<=y||n===O||n===N||n===J))break;i+=" "}d++}return 0{for(var n of t){var r=d+n.length;if(g.slice(d,r)===n)return d=r,1}})(t)){if(k(g[d]))for(;d=g.length)return l=A(d-1),!r&&j(g.charAt(l))?(d=u,v=v.substring(0,o),w(!0)):(n=D(n,'"'),v+=n,!0);if(d===e)return n=D(n,'"'),v+=n,!0;if(f(g[d])){var l=d,s=n.length;if(n+='"',d++,v+=n,b(!1),r||d>=g.length||j(g[d])||_(g[d])||S(g[d]))return $(),!0;var c=A(l-1),a=g.charAt(c);if(","===a)return d=u,v=v.substring(0,o),w(!1,c);if(j(a))return d=u,v=v.substring(0,o),w(!0);v=v.substring(0,o),d=l+1,n=n.substring(0,s)+"\\"+n.substring(s)}else{if(r&&E(g[d])){if(":"===g[d-1]&&m.test(g.substring(u+1,d+2)))for(;d=g.length))throw a=void 0,a=g.slice(d,d+6),new x(`Invalid unicode character "${a}"`,d);d=g.length}}else n+=c,d+=2}else{var h,s=g.charAt(d);if('"'===s&&"\\"!==g[d-1])n+="\\"+s;else if("\n"===(h=s)||"\r"===h||"\t"===h||"\b"===h||"\f"===h)n+=G[s];else{if(!(" "<=s))throw h=void 0,h=s,new x("Invalid character "+JSON.stringify(h),d);n+=s}d++}}i&&p("\\")}}return!1}function $(){let t=!1;for(b();"+"===g[d];){t=!0,d++,b();var n=(v=B(v,'"',!0)).length,r=w();v=r?(r=v,n=n,e=1,r.substring(0,n)+r.substring(n+e)):D(v,'"')}var e;t}function r(t,n){return g.slice(d,d+t.length)===t&&(v+=n,d+=t.length,!0)}function l(t){var n=d;if(k(g[d])){for(;dn){for(;T(g,d-1)&&0=g.length||j(g[d])||T(g,d)}function s(t){v+=g.slice(t,d)+"0"}function c(){throw new x("Colon expected",d)}}}); \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/umd/jsonrepair.min.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/umd/jsonrepair.min.js.map new file mode 100644 index 0000000000000000000000000000000000000000..cd0eacbf2958a368fad5dc26e1d27b2139f9ad1c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/umd/jsonrepair.min.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["lib/umd/jsonrepair.js"],"names":["global","factory","exports","module","define","amd","globalThis","self","JSONRepair","this","JSONRepairError","Error","constructor","message","position","super","codeSpace","codeNewline","codeTab","codeReturn","codeNonBreakingSpace","codeEnQuad","codeHairSpace","codeNarrowNoBreakSpace","codeMediumMathematicalSpace","codeIdeographicSpace","isDigit","char","isDelimiter","includes","isFunctionNameCharStart","isFunctionNameChar","regexUrlStart","regexUrlChar","isUnquotedStringDelimiter","isStartOfValue","isQuote","regexStartOfValue","test","isWhitespace","text","index","code","charCodeAt","isWhitespaceExceptNewline","isDoubleQuoteLike","isSingleQuoteLike","isDoubleQuote","isSingleQuote","stripLastOccurrence","textToStrip","stripRemainingText","arguments","length","undefined","lastIndexOf","substring","insertBeforeLastWhitespace","textToInsert","let","controlCharacters","\b","\f","\n","\r","\t","escapeCharacters","\"","\\","/","b","f","n","r","t","jsonrepair","i","output","parseMarkdownCodeBlock","parseValue","processedComma","parseCharacter","parseWhitespaceAndSkipComments","parseNewlineDelimitedJSON","initial","processedValue","JSON","stringify","processed","skipCharacter","skipEllipsis","parseString","parseUnquotedString","processedColon","truncatedText","throwColonExpected","num","hasInvalidLeadingZero","start","atEndOfNumber","repairNumberEndingWithNumericSymbol","slice","parseKeyword","skipNewline","changed","parseWhitespace","_isWhiteSpace","whitespace","blocks","block","end","stopAtDelimiter","stopAtIndex","skipEscapeChars","isEndQuote","iBefore","oBefore","str","iPrev","prevNonWhitespaceIndex","charAt","iQuote","oQuote","parseConcatenatedString","iPrevChar","prevChar","j","chars","parsedStr","count","name","value","isKey","symbol","prev"],"mappings":"CAAA,CAAWA,EAAQC,KACE,UAAnB,OAAOC,SAA0C,aAAlB,OAAOC,OAAyBF,EAAQC,OAAO,EAC5D,YAAlB,OAAOE,QAAyBA,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/C,CAKF,CAQD,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/umd/package.json b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/umd/package.json new file mode 100644 index 0000000000000000000000000000000000000000..5bbefffbabee392d1855491b84dc0a716b6a3bf2 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/jsonrepair/lib/umd/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/partial-json-parser/parser.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/partial-json-parser/parser.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..f0b5da67156ef4b1c1eb70cd9f7d300452644c86 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/partial-json-parser/parser.d.mts @@ -0,0 +1,7 @@ +declare class PartialJSON extends Error { +} +declare class MalformedJSON extends Error { +} +declare const partialParse: (input: string) => any; +export { partialParse, PartialJSON, MalformedJSON }; +//# sourceMappingURL=parser.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/partial-json-parser/parser.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/partial-json-parser/parser.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..1f7a0be65e7b47e344a93d71231c34a98198c6e7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/partial-json-parser/parser.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"parser.d.mts","sourceRoot":"","sources":["../../src/_vendor/partial-json-parser/parser.ts"],"names":[],"mappings":"AAkCA,cAAM,WAAY,SAAQ,KAAK;CAAG;AAElC,cAAM,aAAc,SAAQ,KAAK;CAAG;AAgNpC,QAAA,MAAM,YAAY,GAAI,OAAO,MAAM,QAA4C,CAAC;AAEhF,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,aAAa,EAAE,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/partial-json-parser/parser.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/partial-json-parser/parser.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5ef5c37d99f9e6f7dad42ec1cf85c274772a758a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/partial-json-parser/parser.d.ts @@ -0,0 +1,7 @@ +declare class PartialJSON extends Error { +} +declare class MalformedJSON extends Error { +} +declare const partialParse: (input: string) => any; +export { partialParse, PartialJSON, MalformedJSON }; +//# sourceMappingURL=parser.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/partial-json-parser/parser.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/partial-json-parser/parser.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..764954adcfc40f2f897bf29db144334f6b9cb41e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/partial-json-parser/parser.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"parser.d.ts","sourceRoot":"","sources":["../../src/_vendor/partial-json-parser/parser.ts"],"names":[],"mappings":"AAkCA,cAAM,WAAY,SAAQ,KAAK;CAAG;AAElC,cAAM,aAAc,SAAQ,KAAK;CAAG;AAgNpC,QAAA,MAAM,YAAY,GAAI,OAAO,MAAM,QAA4C,CAAC;AAEhF,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,aAAa,EAAE,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/partial-json-parser/parser.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/partial-json-parser/parser.js new file mode 100644 index 0000000000000000000000000000000000000000..83126bcf33f1e0f5110f36d27d4a00844b436d44 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/partial-json-parser/parser.js @@ -0,0 +1,246 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MalformedJSON = exports.PartialJSON = exports.partialParse = void 0; +const STR = 0b000000001; +const NUM = 0b000000010; +const ARR = 0b000000100; +const OBJ = 0b000001000; +const NULL = 0b000010000; +const BOOL = 0b000100000; +const NAN = 0b001000000; +const INFINITY = 0b010000000; +const MINUS_INFINITY = 0b100000000; +const INF = INFINITY | MINUS_INFINITY; +const SPECIAL = NULL | BOOL | INF | NAN; +const ATOM = STR | NUM | SPECIAL; +const COLLECTION = ARR | OBJ; +const ALL = ATOM | COLLECTION; +const Allow = { + STR, + NUM, + ARR, + OBJ, + NULL, + BOOL, + NAN, + INFINITY, + MINUS_INFINITY, + INF, + SPECIAL, + ATOM, + COLLECTION, + ALL, +}; +// The JSON string segment was unable to be parsed completely +class PartialJSON extends Error { +} +exports.PartialJSON = PartialJSON; +class MalformedJSON extends Error { +} +exports.MalformedJSON = MalformedJSON; +/** + * Parse incomplete JSON + * @param {string} jsonString Partial JSON to be parsed + * @param {number} allowPartial Specify what types are allowed to be partial, see {@link Allow} for details + * @returns The parsed JSON + * @throws {PartialJSON} If the JSON is incomplete (related to the `allow` parameter) + * @throws {MalformedJSON} If the JSON is malformed + */ +function parseJSON(jsonString, allowPartial = Allow.ALL) { + if (typeof jsonString !== 'string') { + throw new TypeError(`expecting str, got ${typeof jsonString}`); + } + if (!jsonString.trim()) { + throw new Error(`${jsonString} is empty`); + } + return _parseJSON(jsonString.trim(), allowPartial); +} +const _parseJSON = (jsonString, allow) => { + const length = jsonString.length; + let index = 0; + const markPartialJSON = (msg) => { + throw new PartialJSON(`${msg} at position ${index}`); + }; + const throwMalformedError = (msg) => { + throw new MalformedJSON(`${msg} at position ${index}`); + }; + const parseAny = () => { + skipBlank(); + if (index >= length) + markPartialJSON('Unexpected end of input'); + if (jsonString[index] === '"') + return parseStr(); + if (jsonString[index] === '{') + return parseObj(); + if (jsonString[index] === '[') + return parseArr(); + if (jsonString.substring(index, index + 4) === 'null' || + (Allow.NULL & allow && length - index < 4 && 'null'.startsWith(jsonString.substring(index)))) { + index += 4; + return null; + } + if (jsonString.substring(index, index + 4) === 'true' || + (Allow.BOOL & allow && length - index < 4 && 'true'.startsWith(jsonString.substring(index)))) { + index += 4; + return true; + } + if (jsonString.substring(index, index + 5) === 'false' || + (Allow.BOOL & allow && length - index < 5 && 'false'.startsWith(jsonString.substring(index)))) { + index += 5; + return false; + } + if (jsonString.substring(index, index + 8) === 'Infinity' || + (Allow.INFINITY & allow && length - index < 8 && 'Infinity'.startsWith(jsonString.substring(index)))) { + index += 8; + return Infinity; + } + if (jsonString.substring(index, index + 9) === '-Infinity' || + (Allow.MINUS_INFINITY & allow && + 1 < length - index && + length - index < 9 && + '-Infinity'.startsWith(jsonString.substring(index)))) { + index += 9; + return -Infinity; + } + if (jsonString.substring(index, index + 3) === 'NaN' || + (Allow.NAN & allow && length - index < 3 && 'NaN'.startsWith(jsonString.substring(index)))) { + index += 3; + return NaN; + } + return parseNum(); + }; + const parseStr = () => { + const start = index; + let escape = false; + index++; // skip initial quote + while (index < length && (jsonString[index] !== '"' || (escape && jsonString[index - 1] === '\\'))) { + escape = jsonString[index] === '\\' ? !escape : false; + index++; + } + if (jsonString.charAt(index) == '"') { + try { + return JSON.parse(jsonString.substring(start, ++index - Number(escape))); + } + catch (e) { + throwMalformedError(String(e)); + } + } + else if (Allow.STR & allow) { + try { + return JSON.parse(jsonString.substring(start, index - Number(escape)) + '"'); + } + catch (e) { + // SyntaxError: Invalid escape sequence + return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf('\\')) + '"'); + } + } + markPartialJSON('Unterminated string literal'); + }; + const parseObj = () => { + index++; // skip initial brace + skipBlank(); + const obj = {}; + try { + while (jsonString[index] !== '}') { + skipBlank(); + if (index >= length && Allow.OBJ & allow) + return obj; + const key = parseStr(); + skipBlank(); + index++; // skip colon + try { + const value = parseAny(); + Object.defineProperty(obj, key, { value, writable: true, enumerable: true, configurable: true }); + } + catch (e) { + if (Allow.OBJ & allow) + return obj; + else + throw e; + } + skipBlank(); + if (jsonString[index] === ',') + index++; // skip comma + } + } + catch (e) { + if (Allow.OBJ & allow) + return obj; + else + markPartialJSON("Expected '}' at end of object"); + } + index++; // skip final brace + return obj; + }; + const parseArr = () => { + index++; // skip initial bracket + const arr = []; + try { + while (jsonString[index] !== ']') { + arr.push(parseAny()); + skipBlank(); + if (jsonString[index] === ',') { + index++; // skip comma + } + } + } + catch (e) { + if (Allow.ARR & allow) { + return arr; + } + markPartialJSON("Expected ']' at end of array"); + } + index++; // skip final bracket + return arr; + }; + const parseNum = () => { + if (index === 0) { + if (jsonString === '-' && Allow.NUM & allow) + markPartialJSON("Not sure what '-' is"); + try { + return JSON.parse(jsonString); + } + catch (e) { + if (Allow.NUM & allow) { + try { + if ('.' === jsonString[jsonString.length - 1]) + return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf('.'))); + return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf('e'))); + } + catch (e) { } + } + throwMalformedError(String(e)); + } + } + const start = index; + if (jsonString[index] === '-') + index++; + while (jsonString[index] && !',]}'.includes(jsonString[index])) + index++; + if (index == length && !(Allow.NUM & allow)) + markPartialJSON('Unterminated number literal'); + try { + return JSON.parse(jsonString.substring(start, index)); + } + catch (e) { + if (jsonString.substring(start, index) === '-' && Allow.NUM & allow) + markPartialJSON("Not sure what '-' is"); + try { + return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf('e'))); + } + catch (e) { + throwMalformedError(String(e)); + } + } + }; + const skipBlank = () => { + while (index < length && ' \n\r\t'.includes(jsonString[index])) { + index++; + } + }; + return parseAny(); +}; +// using this function with malformed JSON is undefined behavior +const partialParse = (input) => parseJSON(input, Allow.ALL ^ Allow.NUM); +exports.partialParse = partialParse; +//# sourceMappingURL=parser.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/partial-json-parser/parser.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/partial-json-parser/parser.js.map new file mode 100644 index 0000000000000000000000000000000000000000..c643703dd5aa4f528efa6f970da29061f297f4ca --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/partial-json-parser/parser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"parser.js","sourceRoot":"","sources":["../../src/_vendor/partial-json-parser/parser.ts"],"names":[],"mappings":";;;AAAA,MAAM,GAAG,GAAG,WAAW,CAAC;AACxB,MAAM,GAAG,GAAG,WAAW,CAAC;AACxB,MAAM,GAAG,GAAG,WAAW,CAAC;AACxB,MAAM,GAAG,GAAG,WAAW,CAAC;AACxB,MAAM,IAAI,GAAG,WAAW,CAAC;AACzB,MAAM,IAAI,GAAG,WAAW,CAAC;AACzB,MAAM,GAAG,GAAG,WAAW,CAAC;AACxB,MAAM,QAAQ,GAAG,WAAW,CAAC;AAC7B,MAAM,cAAc,GAAG,WAAW,CAAC;AAEnC,MAAM,GAAG,GAAG,QAAQ,GAAG,cAAc,CAAC;AACtC,MAAM,OAAO,GAAG,IAAI,GAAG,IAAI,GAAG,GAAG,GAAG,GAAG,CAAC;AACxC,MAAM,IAAI,GAAG,GAAG,GAAG,GAAG,GAAG,OAAO,CAAC;AACjC,MAAM,UAAU,GAAG,GAAG,GAAG,GAAG,CAAC;AAC7B,MAAM,GAAG,GAAG,IAAI,GAAG,UAAU,CAAC;AAE9B,MAAM,KAAK,GAAG;IACZ,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,IAAI;IACJ,IAAI;IACJ,GAAG;IACH,QAAQ;IACR,cAAc;IACd,GAAG;IACH,OAAO;IACP,IAAI;IACJ,UAAU;IACV,GAAG;CACJ,CAAC;AAEF,6DAA6D;AAC7D,MAAM,WAAY,SAAQ,KAAK;CAAG;AAoNX,kCAAW;AAlNlC,MAAM,aAAc,SAAQ,KAAK;CAAG;AAkNA,sCAAa;AAhNjD;;;;;;;GA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KAAK,EAAE,CAAC;QAEzE,IAAI,KAAK,IAAI,MAAM,IAAI,CAAC,CAAC,KAAK,CAAC,GAAG,GAAG,KAAK,CAAC;YAAE,eAAe,CAAC,6BAA6B,CAAC,CAAC;QAE5F,IAAI,CAAC;YACH,OAAO,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,SAAS,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC;QACxD,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,IAAI,UAAU,CAAC,SAAS,CAAC,KAAK,EAAE,KAAK,CAAC,KAAK,GAAG,IAAI,KAAK,CAAC,GAAG,GAAG,KAAK;gBACjE,eAAe,CAAC,sBAAsB,CAAC,CAAC;YAC1C,IAAI,CAAC;gBACH,OAAO,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,SAAS,CAAC,KAAK,EAAE,UAAU,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;YAC9E,CAAC;YAAC,OAAO,CAAC,EAAE,CAAC;gBACX,mBAAmB,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;YACjC,CAAC;QACH,CAAC;IACH,CAAC,CAAC;IAEF,MAAM,SAAS,GAAG,GAAG,EAAE;QACrB,OAAO,KAAK,GAAG,MAAM,IAAI,SAAS,CAAC,QAAQ,CAAC,UAAU,CAAC,KAAK,CAAE,CAAC,EAAE,CAAC;YAChE,KAAK,EAAE,CAAC;QACV,CAAC;IACH,CAAC,CAAC;IAEF,OAAO,QAAQ,EAAE,CAAC;AACpB,CAAC,CAAC;AAEF,gEAAgE;AAChE,MAAM,YAAY,GAAG,CAAC,KAAa,EAAE,EAAE,CAAC,SAAS,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC;AAEvE,oCAAY"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/partial-json-parser/parser.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/partial-json-parser/parser.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f8954e13a244cc24509ef00300e00d4888d10974 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/partial-json-parser/parser.mjs @@ -0,0 +1,241 @@ +const STR = 0b000000001; +const NUM = 0b000000010; +const ARR = 0b000000100; +const OBJ = 0b000001000; +const NULL = 0b000010000; +const BOOL = 0b000100000; +const NAN = 0b001000000; +const INFINITY = 0b010000000; +const MINUS_INFINITY = 0b100000000; +const INF = INFINITY | MINUS_INFINITY; +const SPECIAL = NULL | BOOL | INF | NAN; +const ATOM = STR | NUM | SPECIAL; +const COLLECTION = ARR | OBJ; +const ALL = ATOM | COLLECTION; +const Allow = { + STR, + NUM, + ARR, + OBJ, + NULL, + BOOL, + NAN, + INFINITY, + MINUS_INFINITY, + INF, + SPECIAL, + ATOM, + COLLECTION, + ALL, +}; +// The JSON string segment was unable to be parsed completely +class PartialJSON extends Error { +} +class MalformedJSON extends Error { +} +/** + * Parse incomplete JSON + * @param {string} jsonString Partial JSON to be parsed + * @param {number} allowPartial Specify what types are allowed to be partial, see {@link Allow} for details + * @returns The parsed JSON + * @throws {PartialJSON} If the JSON is incomplete (related to the `allow` parameter) + * @throws {MalformedJSON} If the JSON is malformed + */ +function parseJSON(jsonString, allowPartial = Allow.ALL) { + if (typeof jsonString !== 'string') { + throw new TypeError(`expecting str, got ${typeof jsonString}`); + } + if (!jsonString.trim()) { + throw new Error(`${jsonString} is empty`); + } + return _parseJSON(jsonString.trim(), allowPartial); +} +const _parseJSON = (jsonString, allow) => { + const length = jsonString.length; + let index = 0; + const markPartialJSON = (msg) => { + throw new PartialJSON(`${msg} at position ${index}`); + }; + const throwMalformedError = (msg) => { + throw new MalformedJSON(`${msg} at position ${index}`); + }; + const parseAny = () => { + skipBlank(); + if (index >= length) + markPartialJSON('Unexpected end of input'); + if (jsonString[index] === '"') + return parseStr(); + if (jsonString[index] === '{') + return parseObj(); + if (jsonString[index] === '[') + return parseArr(); + if (jsonString.substring(index, index + 4) === 'null' || + (Allow.NULL & allow && length - index < 4 && 'null'.startsWith(jsonString.substring(index)))) { + index += 4; + return null; + } + if (jsonString.substring(index, index + 4) === 'true' || + (Allow.BOOL & allow && length - index < 4 && 'true'.startsWith(jsonString.substring(index)))) { + index += 4; + return true; + } + if (jsonString.substring(index, index + 5) === 'false' || + (Allow.BOOL & allow && length - index < 5 && 'false'.startsWith(jsonString.substring(index)))) { + index += 5; + return false; + } + if (jsonString.substring(index, index + 8) === 'Infinity' || + (Allow.INFINITY & allow && length - index < 8 && 'Infinity'.startsWith(jsonString.substring(index)))) { + index += 8; + return Infinity; + } + if (jsonString.substring(index, index + 9) === '-Infinity' || + (Allow.MINUS_INFINITY & allow && + 1 < length - index && + length - index < 9 && + '-Infinity'.startsWith(jsonString.substring(index)))) { + index += 9; + return -Infinity; + } + if (jsonString.substring(index, index + 3) === 'NaN' || + (Allow.NAN & allow && length - index < 3 && 'NaN'.startsWith(jsonString.substring(index)))) { + index += 3; + return NaN; + } + return parseNum(); + }; + const parseStr = () => { + const start = index; + let escape = false; + index++; // skip initial quote + while (index < length && (jsonString[index] !== '"' || (escape && jsonString[index - 1] === '\\'))) { + escape = jsonString[index] === '\\' ? !escape : false; + index++; + } + if (jsonString.charAt(index) == '"') { + try { + return JSON.parse(jsonString.substring(start, ++index - Number(escape))); + } + catch (e) { + throwMalformedError(String(e)); + } + } + else if (Allow.STR & allow) { + try { + return JSON.parse(jsonString.substring(start, index - Number(escape)) + '"'); + } + catch (e) { + // SyntaxError: Invalid escape sequence + return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf('\\')) + '"'); + } + } + markPartialJSON('Unterminated string literal'); + }; + const parseObj = () => { + index++; // skip initial brace + skipBlank(); + const obj = {}; + try { + while (jsonString[index] !== '}') { + skipBlank(); + if (index >= length && Allow.OBJ & allow) + return obj; + const key = parseStr(); + skipBlank(); + index++; // skip colon + try { + const value = parseAny(); + Object.defineProperty(obj, key, { value, writable: true, enumerable: true, configurable: true }); + } + catch (e) { + if (Allow.OBJ & allow) + return obj; + else + throw e; + } + skipBlank(); + if (jsonString[index] === ',') + index++; // skip comma + } + } + catch (e) { + if (Allow.OBJ & allow) + return obj; + else + markPartialJSON("Expected '}' at end of object"); + } + index++; // skip final brace + return obj; + }; + const parseArr = () => { + index++; // skip initial bracket + const arr = []; + try { + while (jsonString[index] !== ']') { + arr.push(parseAny()); + skipBlank(); + if (jsonString[index] === ',') { + index++; // skip comma + } + } + } + catch (e) { + if (Allow.ARR & allow) { + return arr; + } + markPartialJSON("Expected ']' at end of array"); + } + index++; // skip final bracket + return arr; + }; + const parseNum = () => { + if (index === 0) { + if (jsonString === '-' && Allow.NUM & allow) + markPartialJSON("Not sure what '-' is"); + try { + return JSON.parse(jsonString); + } + catch (e) { + if (Allow.NUM & allow) { + try { + if ('.' === jsonString[jsonString.length - 1]) + return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf('.'))); + return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf('e'))); + } + catch (e) { } + } + throwMalformedError(String(e)); + } + } + const start = index; + if (jsonString[index] === '-') + index++; + while (jsonString[index] && !',]}'.includes(jsonString[index])) + index++; + if (index == length && !(Allow.NUM & allow)) + markPartialJSON('Unterminated number literal'); + try { + return JSON.parse(jsonString.substring(start, index)); + } + catch (e) { + if (jsonString.substring(start, index) === '-' && Allow.NUM & allow) + markPartialJSON("Not sure what '-' is"); + try { + return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf('e'))); + } + catch (e) { + throwMalformedError(String(e)); + } + } + }; + const skipBlank = () => { + while (index < length && ' \n\r\t'.includes(jsonString[index])) { + index++; + } + }; + return parseAny(); +}; +// using this function with malformed JSON is undefined behavior +const partialParse = (input) => parseJSON(input, Allow.ALL ^ Allow.NUM); +export { partialParse, PartialJSON, MalformedJSON }; +//# sourceMappingURL=parser.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/partial-json-parser/parser.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/partial-json-parser/parser.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..0af222828c8e44e5c9c053d6a257df0cb1652ea2 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/partial-json-parser/parser.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"parser.mjs","sourceRoot":"","sources":["../../src/_vendor/partial-json-parser/parser.ts"],"names":[],"mappings":"AAAA,MAAM,GAAG,GAAG,WAAW,CAAC;AACxB,MAAM,GAAG,GAAG,WAAW,CAAC;AACxB,MAAM,GAAG,GAAG,WAAW,CAAC;AACxB,MAAM,GAAG,GAAG,WAAW,CAAC;AACxB,MAAM,IAAI,GAAG,WAAW,CAAC;AACzB,MAAM,IAAI,GAAG,WAAW,CAAC;AACzB,MAAM,GAAG,GAAG,WAAW,CAAC;AACxB,MAAM,QAAQ,GAAG,WAAW,CAAC;AAC7B,MAAM,cAAc,GAAG,WAAW,CAAC;AAEnC,MAAM,GAAG,GAAG,QAAQ,GAAG,cAAc,CAAC;AACtC,MAAM,OAAO,GAAG,IAAI,GAAG,IAAI,GAAG,GAAG,GAAG,GAAG,CAAC;AACxC,MAAM,IAAI,GAAG,GAAG,GAAG,GAAG,GAAG,OAAO,CAAC;AACjC,MAAM,UAAU,GAAG,GAAG,GAAG,GAAG,CAAC;AAC7B,MAAM,GAAG,GAAG,IAAI,GAAG,UAAU,CAAC;AAE9B,MAAM,KAAK,GAAG;IACZ,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,IAAI;IACJ,IAAI;IACJ,GAAG;IACH,QAAQ;IACR,cAAc;IACd,GAAG;IACH,OAAO;IACP,IAAI;IACJ,UAAU;IACV,GAAG;CACJ,CAAC;AAEF,6DAA6D;AAC7D,MAAM,WAAY,SAAQ,KAAK;CAAG;AAElC,MAAM,aAAc,SAAQ,KAAK;CAAG;AAEpC;;;;;;;GAO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endor/zod-to-json-schema/Options.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Options.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..7c4fab4a3e857ab5730ab788ca5436d0d44a32f3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Options.d.mts @@ -0,0 +1,32 @@ +import { ZodSchema, ZodTypeDef } from 'zod'; +import { Refs, Seen } from "./Refs.mjs"; +import { JsonSchema7Type } from "./parseDef.mjs"; +export type Targets = 'jsonSchema7' | 'jsonSchema2019-09' | 'openApi3'; +export type DateStrategy = 'format:date-time' | 'format:date' | 'string' | 'integer'; +export declare const ignoreOverride: unique symbol; +export type Options = { + name: string | undefined; + $refStrategy: 'root' | 'relative' | 'none' | 'seen' | 'extract-to-root'; + basePath: string[]; + effectStrategy: 'input' | 'any'; + pipeStrategy: 'input' | 'output' | 'all'; + dateStrategy: DateStrategy | DateStrategy[]; + mapStrategy: 'entries' | 'record'; + removeAdditionalStrategy: 'passthrough' | 'strict'; + nullableStrategy: 'from-target' | 'property'; + target: Target; + strictUnions: boolean; + definitionPath: string; + definitions: Record; + errorMessages: boolean; + markdownDescription: boolean; + patternStrategy: 'escape' | 'preserve'; + applyRegexFlags: boolean; + emailStrategy: 'format:email' | 'format:idn-email' | 'pattern:zod'; + base64Strategy: 'format:binary' | 'contentEncoding:base64' | 'pattern:zod'; + nameStrategy: 'ref' | 'duplicate-ref' | 'title'; + override?: (def: ZodTypeDef, refs: Refs, seen: Seen | undefined, forceResolution?: boolean) => JsonSchema7Type | undefined | typeof ignoreOverride; + openaiStrictMode?: boolean; +}; +export declare const getDefaultOptions: (options: Partial> | string | undefined) => Options; +//# sourceMappingURL=Options.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Options.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Options.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..b17456febdf50de26ee817e448c0b70760dd7e21 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Options.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"Options.d.mts","sourceRoot":"","sources":["../../src/_vendor/zod-to-json-schema/Options.ts"],"names":[],"mappings":"OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,KAAK;OACpC,EAAE,IAAI,EAAE,IAAI,EAAE;OACd,EAAE,eAAe,EAAE;AAE1B,MAAM,MAAM,OAAO,GAAG,aAAa,GAAG,mBAAmB,GAAG,UAAU,CAAC;AAEvE,MAAM,MAAM,YAAY,GAAG,kBAAkB,GAAG,aAAa,GAAG,QAAQ,GAAG,SAAS,CAAC;AAErF,eAAO,MAAM,cAAc,eAA8D,CAAC;AAE1F,MAAM,MAAM,OAAO,CAAC,MAAM,SAAS,OAAO,GAAG,aAAa,IAAI;IAC5D,IAAI,EAAE,MAAM,GAAG,SAAS,CAAC;IACzB,YAAY,EAAE,MAAM,GAAG,UAAU,GAAG,MAAM,GAAG,MAAM,GAAG,iBAAiB,CAAC;IACxE,QAAQ,EAAE,MAAM,EAAE,CAAC;IACnB,cAAc,EAAE,OAAO,GAAG,KAAK,CAAC;IAChC,YAAY,EAAE,OAAO,GAAG,QAAQ,GAAG,KAAK,CAAC;IACzC,YAAY,EAAE,YAAY,GAAG,YAAY,EAAE,CAAC;IAC5C,WAAW,EAAE,SAAS,GAAG,QAAQ,CAAC;IAClC,wBAAwB,EAAE,aAAa,GAAG,QAAQ,CAAC;IACnD,gBAAgB,EAAE,aAAa,GAAG,UAAU,CAAC;IAC7C,MAAM,EAAE,MAAM,CAAC;IACf,YAAY,EAAE,OAAO,CAAC;IACtB,cAAc,EAAE,MAAM,CAAC;IACvB,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,GAAG,UAAU,CAAC,CAAC;IACpD,aAAa,EAAE,OAAO,CAAC;IACvB,mBAAmB,EAAE,OAAO,CAAC;IAC7B,eAAe,EAAE,QAAQ,GAAG,UAAU,CAAC;IACvC,eAAe,EAAE,OAAO,CAAC;IACzB,aAAa,EAAE,cAAc,GAAG,kBAAkB,GAAG,aAAa,CAAC;IACnE,cAAc,EAAE,eAAe,GAAG,wBAAwB,GAAG,aAAa,CAAC;IAC3E,YAAY,EAAE,KAAK,GAAG,eAAe,GAAG,OAAO,CAAC;IAChD,QAAQ,CAAC,EAAE,CACT,GAAG,EAAE,UAAU,EACf,IAAI,EAAE,IAAI,EACV,IAAI,EAAE,IAAI,GAAG,SAAS,EACtB,eAAe,CAAC,EAAE,OAAO,KACtB,eAAe,GAAG,SAAS,GAAG,OAAO,cAAc,CAAC;IACzD,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC5B,CAAC;AAuBF,eAAO,MAAM,iBAAiB,GAAI,MAAM,SAAS,OAAO,EACtD,SAAS,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,GAAG,MAAM,GAAG,SAAS,KAgB5C,OAAO,CAAC,MAAM,CACzB,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Options.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Options.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3486d1a85edd7eaa3a2962582e6420ef3b145931 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Options.d.ts @@ -0,0 +1,32 @@ +import { ZodSchema, ZodTypeDef } from 'zod'; +import { Refs, Seen } from "./Refs.js"; +import { JsonSchema7Type } from "./parseDef.js"; +export type Targets = 'jsonSchema7' | 'jsonSchema2019-09' | 'openApi3'; +export type DateStrategy = 'format:date-time' | 'format:date' | 'string' | 'integer'; +export declare const ignoreOverride: unique symbol; +export type Options = { + name: string | undefined; + $refStrategy: 'root' | 'relative' | 'none' | 'seen' | 'extract-to-root'; + basePath: string[]; + effectStrategy: 'input' | 'any'; + pipeStrategy: 'input' | 'output' | 'all'; + dateStrategy: DateStrategy | DateStrategy[]; + mapStrategy: 'entries' | 'record'; + removeAdditionalStrategy: 'passthrough' | 'strict'; + nullableStrategy: 'from-target' | 'property'; + target: Target; + strictUnions: boolean; + definitionPath: string; + definitions: Record; + errorMessages: boolean; + markdownDescription: boolean; + patternStrategy: 'escape' | 'preserve'; + applyRegexFlags: boolean; + emailStrategy: 'format:email' | 'format:idn-email' | 'pattern:zod'; + base64Strategy: 'format:binary' | 'contentEncoding:base64' | 'pattern:zod'; + nameStrategy: 'ref' | 'duplicate-ref' | 'title'; + override?: (def: ZodTypeDef, refs: Refs, seen: Seen | undefined, forceResolution?: boolean) => JsonSchema7Type | undefined | typeof ignoreOverride; + openaiStrictMode?: boolean; +}; +export declare const getDefaultOptions: (options: Partial> | string | undefined) => Options; +//# sourceMappingURL=Options.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Options.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Options.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..9bb7e7114b87f31b1ce2eda51c01d1186f7fe527 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Options.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Options.d.ts","sourceRoot":"","sources":["../../src/_vendor/zod-to-json-schema/Options.ts"],"names":[],"mappings":"OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,KAAK;OACpC,EAAE,IAAI,EAAE,IAAI,EAAE;OACd,EAAE,eAAe,EAAE;AAE1B,MAAM,MAAM,OAAO,GAAG,aAAa,GAAG,mBAAmB,GAAG,UAAU,CAAC;AAEvE,MAAM,MAAM,YAAY,GAAG,kBAAkB,GAAG,aAAa,GAAG,QAAQ,GAAG,SA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E,OAAO,CAAC;CAC5B,CAAC;AAuBF,eAAO,MAAM,iBAAiB,GAAI,MAAM,SAAS,OAAO,EACtD,SAAS,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,GAAG,MAAM,GAAG,SAAS,KAgB5C,OAAO,CAAC,MAAM,CACzB,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Options.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Options.js new file mode 100644 index 0000000000000000000000000000000000000000..ce8822c3dcb9ffa71f13b8ffcbd649a1214890f7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Options.js @@ -0,0 +1,42 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getDefaultOptions = exports.ignoreOverride = void 0; +exports.ignoreOverride = Symbol('Let zodToJsonSchema decide on which parser to use'); +const defaultOptions = { + name: undefined, + $refStrategy: 'root', + effectStrategy: 'input', + pipeStrategy: 'all', + dateStrategy: 'format:date-time', + mapStrategy: 'entries', + nullableStrategy: 'from-target', + removeAdditionalStrategy: 'passthrough', + definitionPath: 'definitions', + target: 'jsonSchema7', + strictUnions: false, + errorMessages: false, + markdownDescription: false, + patternStrategy: 'escape', + applyRegexFlags: false, + emailStrategy: 'format:email', + base64Strategy: 'contentEncoding:base64', + nameStrategy: 'ref', +}; +const getDefaultOptions = (options) => { + // We need to add `definitions` here as we may mutate it + return (typeof options === 'string' ? + { + ...defaultOptions, + basePath: ['#'], + definitions: {}, + name: options, + } + : { + ...defaultOptions, + basePath: ['#'], + definitions: {}, + ...options, + }); +}; +exports.getDefaultOptions = getDefaultOptions; +//# sourceMappingURL=Options.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Options.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Options.js.map new file mode 100644 index 0000000000000000000000000000000000000000..b35ca3887b9aba36a02cea788cb94ac2a13839c3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Options.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Options.js","sourceRoot":"","sources":["../../src/_vendor/zod-to-json-schema/Options.ts"],"names":[],"mappings":";;;AAQa,QAAA,cAAc,GAAG,MAAM,CAAC,mDAAmD,CAAC,CAAC;AAgC1F,MAAM,cAAc,GAA8C;IAChE,IAAI,EAAE,SAAS;IACf,YAAY,EAAE,MAAM;IACpB,cAAc,EAAE,OAAO;IACvB,YAAY,EAAE,KAAK;IACnB,YAAY,EAAE,kBAAkB;IAChC,WAAW,EAAE,SAAS;IACtB,gBAAgB,EAAE,aAAa;IAC/B,wBAAwB,EAAE,aAAa;IACvC,cAAc,EAAE,aAAa;IAC7B,MAAM,EAAE,aAAa;IACrB,YAAY,EAAE,KAAK;IACnB,aAAa,EAAE,KAAK;IACpB,mBAAmB,EAAE,KAAK;IAC1B,eAAe,EAAE,QAAQ;IACzB,eAAe,EAAE,KAAK;IACtB,aAAa,EAAE,cAAc;IAC7B,cAAc,EAAE,wBAAwB;IACxC,YAAY,EAAE,KAAK;CACpB,CAAC;AAEK,MAAM,iBAAiB,GAAG,CAC/B,OAAsD,EACtD,EAAE;IACF,wDAAwD;IACxD,OAAO,CACL,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC;QAC3B;YACE,GAAG,cAAc;YACjB,QAAQ,EAAE,CAAC,GAAG,CAAC;YACf,WAAW,EAAE,EAAE;YACf,IAAI,EAAE,OAAO;SACd;QACH,CAAC,CAAC;YACE,GAAG,cAAc;YACjB,QAAQ,EAAE,CAAC,GAAG,CAAC;YACf,WAAW,EAAE,EAAE;YACf,GAAG,OAAO;SACX,CAAoB,CAAC;AAC5B,CAAC,CAAC;AAlBW,QAAA,iBAAiB,qBAkB5B"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Options.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Options.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8e199f8dcfb8488d353a3e41dc576cd952eed441 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Options.mjs @@ -0,0 +1,38 @@ +export const ignoreOverride = Symbol('Let zodToJsonSchema decide on which parser to use'); +const defaultOptions = { + name: undefined, + $refStrategy: 'root', + effectStrategy: 'input', + pipeStrategy: 'all', + dateStrategy: 'format:date-time', + mapStrategy: 'entries', + nullableStrategy: 'from-target', + removeAdditionalStrategy: 'passthrough', + definitionPath: 'definitions', + target: 'jsonSchema7', + strictUnions: false, + errorMessages: false, + markdownDescription: false, + patternStrategy: 'escape', + applyRegexFlags: false, + emailStrategy: 'format:email', + base64Strategy: 'contentEncoding:base64', + nameStrategy: 'ref', +}; +export const getDefaultOptions = (options) => { + // We need to add `definitions` here as we may mutate it + return (typeof options === 'string' ? + { + ...defaultOptions, + basePath: ['#'], + definitions: {}, + name: options, + } + : { + ...defaultOptions, + basePath: ['#'], + definitions: {}, + ...options, + }); +}; +//# sourceMappingURL=Options.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Options.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Options.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..10a07a62ca8ce791e77b16e5bde12c5d3165022d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Options.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"Options.mjs","sourceRoot":"","sources":["../../src/_vendor/zod-to-json-schema/Options.ts"],"names":[],"mappings":"AAQA,MAAM,CAAC,MAAM,cAAc,GAAG,MAAM,CAAC,mDAAmD,CAAC,CAAC;AAgC1F,MAAM,cAAc,GAA8C;IAChE,IAAI,EAAE,SAAS;IACf,YAAY,EAAE,MAAM;IACpB,cAAc,EAAE,OAAO;IACvB,YAAY,EAAE,KAAK;IACnB,YAAY,EAAE,kBAAkB;IAChC,WAAW,EAAE,SAAS;IACtB,gBAAgB,EAAE,aAAa;IAC/B,wBAAwB,EAAE,aAAa;IACvC,cAAc,EAAE,aAAa;IAC7B,MAAM,EAAE,aAAa;IACrB,YAAY,EAAE,KAAK;IACnB,aAAa,EAAE,KAAK;IACpB,mBAAmB,EAAE,KAAK;IAC1B,eAAe,EAAE,QAAQ;IACzB,eAAe,EAAE,KAAK;IACtB,aAAa,EAAE,cAAc;IAC7B,cAAc,EAAE,wBAAwB;IACxC,YAAY,EAAE,KAAK;CACpB,CAAC;AAEF,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAC/B,OAAsD,EACtD,EAAE;IACF,wDAAwD;IACxD,OAAO,CACL,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC;QAC3B;YACE,GAAG,cAAc;YACjB,QAAQ,EAAE,CAAC,GAAG,CAAC;YACf,WAAW,EAAE,EAAE;YACf,IAAI,EAAE,OAAO;SACd;QACH,CAAC,CAAC;YACE,GAAG,cAAc;YACjB,QAAQ,EAAE,CAAC,GAAG,CAAC;YACf,WAAW,EAAE,EAAE;YACf,GAAG,OAAO;SACX,CAAoB,CAAC;AAC5B,CAAC,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Refs.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Refs.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..972c78c81179244c9109d3a28f839f18b58e2537 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Refs.d.mts @@ -0,0 +1,21 @@ +import type { ZodTypeDef } from 'zod'; +import { Options, Targets } from "./Options.mjs"; +import { JsonSchema7Type } from "./parseDef.mjs"; +export type Refs = { + seen: Map; + /** + * Set of all the `$ref`s we created, e.g. `Set(['#/$defs/ui'])` + * this notable does not include any `definitions` that were + * explicitly given as an option. + */ + seenRefs: Set; + currentPath: string[]; + propertyPath: string[] | undefined; +} & Options; +export type Seen = { + def: ZodTypeDef; + path: string[]; + jsonSchema: JsonSchema7Type | undefined; +}; +export declare const getRefs: (options?: string | Partial>) => Refs; +//# sourceMappingURL=Refs.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Refs.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Refs.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..b355f82de157d27c42322d08a7959ef926454b41 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Refs.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"Refs.d.mts","sourceRoot":"","sources":["../../src/_vendor/zod-to-json-schema/Refs.ts"],"names":[],"mappings":"OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,KAAK;OAC9B,EAAqB,OAAO,EAAE,OAAO,EAAE;OACvC,EAAE,eAAe,EAAE;AAG1B,MAAM,MAAM,IAAI,GAAG;IACjB,IAAI,EAAE,GAAG,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;IAC5B;;;;OAIG;IACH,QAAQ,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IACtB,WAAW,EAAE,MAAM,EAAE,CAAC;IACtB,YAAY,EAAE,MAAM,EAAE,GAAG,SAAS,CAAC;CACpC,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;AAErB,MAAM,MAAM,IAAI,GAAG;IACjB,GAAG,EAAE,UAAU,CAAC;IAChB,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,UAAU,EAAE,eAAe,GAAG,SAAS,CAAC;CACzC,CAAC;AAEF,eAAO,MAAM,OAAO,GAAI,UAAU,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,KAAG,IAuBtE,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Refs.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Refs.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..39db1f72c33f82b0dc675a6cae3c4653c5584bec --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Refs.d.ts @@ -0,0 +1,21 @@ +import type { ZodTypeDef } from 'zod'; +import { Options, Targets } from "./Options.js"; +import { JsonSchema7Type } from "./parseDef.js"; +export type Refs = { + seen: Map; + /** + * Set of all the `$ref`s we created, e.g. `Set(['#/$defs/ui'])` + * this notable does not include any `definitions` that were + * explicitly given as an option. + */ + seenRefs: Set; + currentPath: string[]; + propertyPath: string[] | undefined; +} & Options; +export type Seen = { + def: ZodTypeDef; + path: string[]; + jsonSchema: JsonSchema7Type | undefined; +}; +export declare const getRefs: (options?: string | Partial>) => Refs; +//# sourceMappingURL=Refs.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Refs.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Refs.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..e1b5216c78cccde5dcd312981041a29a01284a31 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Refs.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Refs.d.ts","sourceRoot":"","sources":["../../src/_vendor/zod-to-json-schema/Refs.ts"],"names":[],"mappings":"OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,KAAK;OAC9B,EAAqB,OAAO,EAAE,OAAO,EAAE;OACvC,EAAE,eAAe,EAAE;AAG1B,MAAM,MAAM,IAAI,GAAG;IACjB,IAAI,EAAE,GAAG,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;IAC5B;;;;OAIG;IACH,QAAQ,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IACtB,WAAW,EAAE,MAAM,EAAE,CAAC;IACtB,YAAY,EAAE,MAAM,EAAE,GAAG,SAAS,CAAC;CACpC,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;AAErB,MAAM,MAAM,IAAI,GAAG;IACjB,GAAG,EAAE,UAAU,CAAC;IAChB,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,UAAU,EAAE,eAAe,GAAG,SAAS,CAAC;CACzC,CAAC;AAEF,eAAO,MAAM,OAAO,GAAI,UAAU,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,KAAG,IAuBtE,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Refs.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Refs.js new file mode 100644 index 0000000000000000000000000000000000000000..e89ba020abb141f5dbb561cb9a34304ef97c4a0a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Refs.js @@ -0,0 +1,28 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getRefs = void 0; +const Options_1 = require("./Options.js"); +const util_1 = require("./util.js"); +const getRefs = (options) => { + const _options = (0, Options_1.getDefaultOptions)(options); + const currentPath = _options.name !== undefined ? + [..._options.basePath, _options.definitionPath, _options.name] + : _options.basePath; + return { + ..._options, + currentPath: currentPath, + propertyPath: undefined, + seenRefs: new Set(), + seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [ + (0, util_1.zodDef)(def), + { + def: (0, util_1.zodDef)(def), + path: [..._options.basePath, _options.definitionPath, name], + // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now. + jsonSchema: undefined, + }, + ])), + }; +}; +exports.getRefs = getRefs; +//# sourceMappingURL=Refs.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Refs.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Refs.js.map new file mode 100644 index 0000000000000000000000000000000000000000..f48077cb4139d57d51f7e6552fc6e7c0f77b9d5d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Refs.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Refs.js","sourceRoot":"","sources":["../../src/_vendor/zod-to-json-schema/Refs.ts"],"names":[],"mappings":";;;AACA,0CAAgE;AAEhE,oCAAgC;AAoBzB,MAAM,OAAO,GAAG,CAAC,OAA4C,EAAQ,EAAE;IAC5E,MAAM,QAAQ,GAAG,IAAA,2BAAiB,EAAC,OAAO,CAAC,CAAC;IAC5C,MAAM,WAAW,GACf,QAAQ,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC;QAC3B,CAAC,GAAG,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC,cAAc,EAAE,QAAQ,CAAC,IAAI,CAAC;QAChE,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC;IACtB,OAAO;QACL,GAAG,QAAQ;QACX,WAAW,EAAE,WAAW;QACxB,YAAY,EAAE,SAAS;QACvB,QAAQ,EAAE,IAAI,GAAG,EAAE;QACnB,IAAI,EAAE,IAAI,GAAG,CACX,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,EAAE,CAAC;YACxD,IAAA,aAAM,EAAC,GAAG,CAAC;YACX;gBACE,GAAG,EAAE,IAAA,aAAM,EAAC,GAAG,CAAC;gBAChB,IAAI,EAAE,CAAC,GAAG,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC,cAAc,EAAE,IAAI,CAAC;gBAC3D,kHAAkH;gBAClH,UAAU,EAAE,SAAS;aACtB;SACF,CAAC,CACH;KACF,CAAC;AACJ,CAAC,CAAC;AAvBW,QAAA,OAAO,WAuBlB"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Refs.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Refs.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7269765c734c69408f8bb8beec1f05b31225c8f2 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Refs.mjs @@ -0,0 +1,24 @@ +import { getDefaultOptions } from "./Options.mjs"; +import { zodDef } from "./util.mjs"; +export const getRefs = (options) => { + const _options = getDefaultOptions(options); + const currentPath = _options.name !== undefined ? + [..._options.basePath, _options.definitionPath, _options.name] + : _options.basePath; + return { + ..._options, + currentPath: currentPath, + propertyPath: undefined, + seenRefs: new Set(), + seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [ + zodDef(def), + { + def: zodDef(def), + path: [..._options.basePath, _options.definitionPath, name], + // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now. + jsonSchema: undefined, + }, + ])), + }; +}; +//# sourceMappingURL=Refs.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Refs.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Refs.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..f73333d325f9eb7fe35108022615339926b646ea --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/Refs.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"Refs.mjs","sourceRoot":"","sources":["../../src/_vendor/zod-to-json-schema/Refs.ts"],"names":[],"mappings":"OACO,EAAE,iBAAiB,EAAoB;OAEvC,EAAE,MAAM,EAAE;AAoBjB,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,OAA4C,EAAQ,EAAE;IAC5E,MAAM,QAAQ,GAAG,iBAAiB,CAAC,OAAO,CAAC,CAAC;IAC5C,MAAM,WAAW,GACf,QAAQ,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC;QAC3B,CAAC,GAAG,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC,cAAc,EAAE,QAAQ,CAAC,IAAI,CAAC;QAChE,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC;IACtB,OAAO;QACL,GAAG,QAAQ;QACX,WAAW,EAAE,WAAW;QACxB,YAAY,EAAE,SAAS;QACvB,QAAQ,EAAE,IAAI,GAAG,EAAE;QACnB,IAAI,EAAE,IAAI,GAAG,CACX,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,EAAE,CAAC;YACxD,MAAM,CAAC,GAAG,CAAC;YACX;gBACE,GAAG,EAAE,MAAM,CAAC,GAAG,CAAC;gBAChB,IAAI,EAAE,CAAC,GAAG,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC,cAAc,EAAE,IAAI,CAAC;gBAC3D,kHAAkH;gBAClH,UAAU,EAAE,SAAS;aACtB;SACF,CAAC,CACH;KACF,CAAC;AACJ,CAAC,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/errorMessages.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/errorMessages.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..5b045c7aebceb324f8d003e3ec0e40924ac2fd52 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/errorMessages.d.mts @@ -0,0 +1,12 @@ +import { JsonSchema7TypeUnion } from "./parseDef.mjs"; +import { Refs } from "./Refs.mjs"; +export type ErrorMessages = Partial>; +export declare function addErrorMessage; +}>(res: T, key: keyof T, errorMessage: string | undefined, refs: Refs): void; +export declare function setResponseValueAndErrors; +}, Key extends keyof Omit>(res: Json7Type, key: Key, value: Json7Type[Key], errorMessage: string | undefined, refs: Refs): void; +//# sourceMappingURL=errorMessages.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/errorMessages.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/errorMessages.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..6e57dfea66bd54cf9f6d8302d34e89476b8ca0f6 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/errorMessages.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"errorMessages.d.mts","sourceRoot":"","sources":["../../src/_vendor/zod-to-json-schema/errorMessages.ts"],"names":[],"mappings":"OAAO,EAAE,oBAAoB,EAAE;OACxB,EAAE,IAAI,EAAE;AAEf,MAAM,MAAM,aAAa,CAAC,CAAC,SAAS,oBAAoB,EAAE,cAAc,SAAS,MAAM,GAAG,EAAE,IAAI,OAAO,CACrG,IAAI,CAAC;KAAG,GAAG,IAAI,MAAM,CAAC,GAAG,MAAM;CAAE,EAAE,cAAc,GAAG,MAAM,GAAG,eAAe,CAAC,CAC9E,CAAC;AAEF,wBAAgB,eAAe,CAAC,CAAC,SAAS;IAAE,YAAY,CAAC,EAAE,aAAa,CAAC,GAAG,CAAC,CAAA;CAAE,EAC7E,GAAG,EAAE,CAAC,EACN,GAAG,EAAE,MAAM,CAAC,EACZ,YAAY,EAAE,MAAM,GAAG,SAAS,EAChC,IAAI,EAAE,IAAI,QASX;AAED,wBAAgB,yBAAyB,CACvC,SAAS,SAAS,oBAAoB,GAAG;IACvC,YAAY,CAAC,EAAE,aAAa,CAAC,SAAS,CAAC,CAAC;CACzC,EACD,GAAG,SAAS,MAAM,IAAI,CAAC,SAAS,EAAE,cAAc,CAAC,EACjD,GAAG,EAAE,SAAS,EAAE,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,SAAS,CAAC,GAAG,CAAC,EAAE,YAAY,EAAE,MAAM,GAAG,SAAS,EAAE,IAAI,EAAE,IAAI,QAG9F"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/errorMessages.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/errorMessages.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6d61f11ae20e569b560e5d1914f2449c5ed11da8 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/errorMessages.d.ts @@ -0,0 +1,12 @@ +import { JsonSchema7TypeUnion } from "./parseDef.js"; +import { Refs } from "./Refs.js"; +export type ErrorMessages = Partial>; +export declare function addErrorMessage; +}>(res: T, key: keyof T, errorMessage: string | undefined, refs: Refs): void; +export declare function setResponseValueAndErrors; +}, Key extends keyof Omit>(res: Json7Type, key: Key, value: Json7Type[Key], errorMessage: string | undefined, refs: Refs): void; +//# sourceMappingURL=errorMessages.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/errorMessages.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/errorMessages.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..9f16bd1dac576a19e73ceaabed041e38f0b18006 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/errorMessages.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"errorMessages.d.ts","sourceRoot":"","sources":["../../src/_vendor/zod-to-json-schema/errorMessages.ts"],"names":[],"mappings":"OAAO,EAAE,oBAAoB,EAAE;OACxB,EAAE,IAAI,EAAE;AAEf,MAAM,MAAM,aAAa,CAAC,CAAC,SAAS,oBAAoB,EAAE,cAAc,SAAS,MAAM,GAAG,EAAE,IAAI,OAAO,CACrG,IAAI,CAAC;KAAG,GAAG,IAAI,MAAM,CAAC,GAAG,MAAM;CAAE,EAAE,cAAc,GAAG,MAAM,GAAG,eAAe,CAAC,CAC9E,CAAC;AAEF,wBAAgB,eAAe,CAAC,CAAC,SAAS;IAAE,YAAY,CAAC,EAAE,aAAa,CAAC,GAAG,CAAC,CAAA;CAAE,EAC7E,GAAG,EAAE,CAAC,EACN,GAAG,EAAE,MAAM,CAAC,EACZ,YAAY,EAAE,MAAM,GAAG,SAAS,EAChC,IAAI,EAAE,IAAI,QASX;AAED,wBAAgB,yBAAyB,CACvC,SAAS,SAAS,oBAAoB,GAAG;IACvC,YAAY,CAAC,EAAE,aAAa,CAAC,SAAS,CAAC,CAAC;CACzC,EACD,GAAG,SAAS,MAAM,IAAI,CAAC,SAAS,EAAE,cAAc,CAAC,EACjD,GAAG,EAAE,SAAS,EAAE,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,SAAS,CAAC,GAAG,CAAC,EAAE,YAAY,EAAE,MAAM,GAAG,SAAS,EAAE,IAAI,EAAE,IAAI,QAG9F"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/errorMessages.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/errorMessages.js new file mode 100644 index 0000000000000000000000000000000000000000..c3fd33fee9bda4e09c12e4ea4aa9e40fad3ae6df --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/errorMessages.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.addErrorMessage = addErrorMessage; +exports.setResponseValueAndErrors = setResponseValueAndErrors; +function addErrorMessage(res, key, errorMessage, refs) { + if (!refs?.errorMessages) + return; + if (errorMessage) { + res.errorMessage = { + ...res.errorMessage, + [key]: errorMessage, + }; + } +} +function setResponseValueAndErrors(res, key, value, errorMessage, refs) { + res[key] = value; + addErrorMessage(res, key, errorMessage, refs); +} +//# sourceMappingURL=errorMessages.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/errorMessages.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/errorMessages.js.map new file mode 100644 index 0000000000000000000000000000000000000000..1d5acee808e892a8198e4a40b212db2e8d17bfe3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/errorMessages.js.map @@ -0,0 +1 @@ +{"version":3,"file":"errorMessages.js","sourceRoot":"","sources":["../../src/_vendor/zod-to-json-schema/errorMessages.ts"],"names":[],"mappings":";;AAOA,0CAaC;AAED,8DAQC;AAvBD,SAAgB,eAAe,CAC7B,GAAM,EACN,GAAY,EACZ,YAAgC,EAChC,IAAU;IAEV,IAAI,CAAC,IAAI,EAAE,aAAa;QAAE,OAAO;IACjC,IAAI,YAAY,EAAE,CAAC;QACjB,GAAG,CAAC,YAAY,GAAG;YACjB,GAAG,GAAG,CAAC,YAAY;YACnB,CAAC,GAAG,CAAC,EAAE,YAAY;SACpB,CAAC;IACJ,CAAC;AACH,CAAC;AAED,SAAgB,yBAAyB,CAKvC,GAAc,EAAE,GAAQ,EAAE,KAAqB,EAAE,YAAgC,EAAE,IAAU;IAC7F,GAAG,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;IACjB,eAAe,CAAC,GAAG,EAAE,GAAG,EAAE,YAAY,EAAE,IAAI,CAAC,CAAC;AAChD,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/errorMessages.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/errorMessages.mjs new file mode 100644 index 0000000000000000000000000000000000000000..750f0c9ad36b025e8a57f679608b9294f7fa52e2 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/errorMessages.mjs @@ -0,0 +1,15 @@ +export function addErrorMessage(res, key, errorMessage, refs) { + if (!refs?.errorMessages) + return; + if (errorMessage) { + res.errorMessage = { + ...res.errorMessage, + [key]: errorMessage, + }; + } +} +export function setResponseValueAndErrors(res, key, value, errorMessage, refs) { + res[key] = value; + addErrorMessage(res, key, errorMessage, refs); +} +//# sourceMappingURL=errorMessages.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/errorMessages.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/errorMessages.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..a15c574c9144f2a31b146320404161e09ad3ce3b --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/errorMessages.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"errorMessages.mjs","sourceRoot":"","sources":["../../src/_vendor/zod-to-json-schema/errorMessages.ts"],"names":[],"mappings":"AAOA,MAAM,UAAU,eAAe,CAC7B,GAAM,EACN,GAAY,EACZ,YAAgC,EAChC,IAAU;IAEV,IAAI,CAAC,IAAI,EAAE,aAAa;QAAE,OAAO;IACjC,IAAI,YAAY,EAAE,CAAC;QACjB,GAAG,CAAC,YAAY,GAAG;YACjB,GAAG,GAAG,CAAC,YAAY;YACnB,CAAC,GAAG,CAAC,EAAE,YAAY;SACpB,CAAC;IACJ,CAAC;AACH,CAAC;AAED,MAAM,UAAU,yBAAyB,CAKvC,GAAc,EAAE,GAAQ,EAAE,KAAqB,EAAE,YAAgC,EAAE,IAAU;IAC7F,GAAG,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;IACjB,eAAe,CAAC,GAAG,EAAE,GAAG,EAAE,YAAY,EAAE,IAAI,CAAC,CAAC;AAChD,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/index.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..bae9e3ead8e7424e79c93e71e1d1b602f9be8de1 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/index.d.mts @@ -0,0 +1,38 @@ +export * from "./Options.mjs"; +export * from "./Refs.mjs"; +export * from "./errorMessages.mjs"; +export * from "./parseDef.mjs"; +export * from "./parsers/any.mjs"; +export * from "./parsers/array.mjs"; +export * from "./parsers/bigint.mjs"; +export * from "./parsers/boolean.mjs"; +export * from "./parsers/branded.mjs"; +export * from "./parsers/catch.mjs"; +export * from "./parsers/date.mjs"; +export * from "./parsers/default.mjs"; +export * from "./parsers/effects.mjs"; +export * from "./parsers/enum.mjs"; +export * from "./parsers/intersection.mjs"; +export * from "./parsers/literal.mjs"; +export * from "./parsers/map.mjs"; +export * from "./parsers/nativeEnum.mjs"; +export * from "./parsers/never.mjs"; +export * from "./parsers/null.mjs"; +export * from "./parsers/nullable.mjs"; +export * from "./parsers/number.mjs"; +export * from "./parsers/object.mjs"; +export * from "./parsers/optional.mjs"; +export * from "./parsers/pipeline.mjs"; +export * from "./parsers/promise.mjs"; +export * from "./parsers/readonly.mjs"; +export * from "./parsers/record.mjs"; +export * from "./parsers/set.mjs"; +export * from "./parsers/string.mjs"; +export * from "./parsers/tuple.mjs"; +export * from "./parsers/undefined.mjs"; +export * from "./parsers/union.mjs"; +export * from "./parsers/unknown.mjs"; +export * from "./zodToJsonSchema.mjs"; +import { zodToJsonSchema } from "./zodToJsonSchema.mjs"; +export default zodToJsonSchema; +//# sourceMappingURL=index.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/index.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/index.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..bbbee9537351b5cff865bab8662ffccabad3e288 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/index.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../../src/_vendor/zod-to-json-schema/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAmCO,EAAE,eAAe,EAAE;AAC1B,eAAe,eAAe,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/index.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..479fb21cc3fb4776e229c879870bda3a8b048b8c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/index.d.ts @@ -0,0 +1,38 @@ +export * from "./Options.js"; +export * from "./Refs.js"; +export * from "./errorMessages.js"; +export * from "./parseDef.js"; +export * from "./parsers/any.js"; +export * from "./parsers/array.js"; +export * from "./parsers/bigint.js"; +export * from "./parsers/boolean.js"; +export * from "./parsers/branded.js"; +export * from "./parsers/catch.js"; +export * from "./parsers/date.js"; +export * from "./parsers/default.js"; +export * from "./parsers/effects.js"; +export * from "./parsers/enum.js"; +export * from "./parsers/intersection.js"; +export * from "./parsers/literal.js"; +export * from "./parsers/map.js"; +export * from "./parsers/nativeEnum.js"; +export * from "./parsers/never.js"; +export * from "./parsers/null.js"; +export * from "./parsers/nullable.js"; +export * from "./parsers/number.js"; +export * from "./parsers/object.js"; +export * from "./parsers/optional.js"; +export * from "./parsers/pipeline.js"; +export * from "./parsers/promise.js"; +export * from "./parsers/readonly.js"; +export * from "./parsers/record.js"; +export * from "./parsers/set.js"; +export * from "./parsers/string.js"; +export * from "./parsers/tuple.js"; +export * from "./parsers/undefined.js"; +export * from "./parsers/union.js"; +export * from "./parsers/unknown.js"; +export * from "./zodToJsonSchema.js"; +import { zodToJsonSchema } from "./zodToJsonSchema.js"; +export default zodToJsonSchema; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/index.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..7bac21c3afd25f10a83e33a513ca44bbe2f0e286 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/_vendor/zod-to-json-schema/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAmCO,EAAE,eAAe,EAAE;AAC1B,eAAe,eAAe,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/index.js new file mode 100644 index 0000000000000000000000000000000000000000..b63d9e1ae606a1cb521215ce5fbebd12f0d49ceb --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/index.js @@ -0,0 +1,41 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = require("../../internal/tslib.js"); +tslib_1.__exportStar(require("./Options.js"), exports); +tslib_1.__exportStar(require("./Refs.js"), exports); +tslib_1.__exportStar(require("./errorMessages.js"), exports); +tslib_1.__exportStar(require("./parseDef.js"), exports); +tslib_1.__exportStar(require("./parsers/any.js"), exports); +tslib_1.__exportStar(require("./parsers/array.js"), exports); +tslib_1.__exportStar(require("./parsers/bigint.js"), exports); +tslib_1.__exportStar(require("./parsers/boolean.js"), exports); +tslib_1.__exportStar(require("./parsers/branded.js"), exports); +tslib_1.__exportStar(require("./parsers/catch.js"), exports); +tslib_1.__exportStar(require("./parsers/date.js"), exports); +tslib_1.__exportStar(require("./parsers/default.js"), exports); +tslib_1.__exportStar(require("./parsers/effects.js"), exports); +tslib_1.__exportStar(require("./parsers/enum.js"), exports); +tslib_1.__exportStar(require("./parsers/intersection.js"), exports); +tslib_1.__exportStar(require("./parsers/literal.js"), exports); +tslib_1.__exportStar(require("./parsers/map.js"), exports); +tslib_1.__exportStar(require("./parsers/nativeEnum.js"), exports); +tslib_1.__exportStar(require("./parsers/never.js"), exports); +tslib_1.__exportStar(require("./parsers/null.js"), exports); +tslib_1.__exportStar(require("./parsers/nullable.js"), exports); +tslib_1.__exportStar(require("./parsers/number.js"), exports); +tslib_1.__exportStar(require("./parsers/object.js"), exports); +tslib_1.__exportStar(require("./parsers/optional.js"), exports); +tslib_1.__exportStar(require("./parsers/pipeline.js"), exports); +tslib_1.__exportStar(require("./parsers/promise.js"), exports); +tslib_1.__exportStar(require("./parsers/readonly.js"), exports); +tslib_1.__exportStar(require("./parsers/record.js"), exports); +tslib_1.__exportStar(require("./parsers/set.js"), exports); +tslib_1.__exportStar(require("./parsers/string.js"), exports); +tslib_1.__exportStar(require("./parsers/tuple.js"), exports); +tslib_1.__exportStar(require("./parsers/undefined.js"), exports); +tslib_1.__exportStar(require("./parsers/union.js"), exports); +tslib_1.__exportStar(require("./parsers/unknown.js"), exports); +tslib_1.__exportStar(require("./zodToJsonSchema.js"), exports); +const zodToJsonSchema_1 = require("./zodToJsonSchema.js"); +exports.default = zodToJsonSchema_1.zodToJsonSchema; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/index.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..4fbb9bcab0e2aff7b0d34679860f8578a83170c6 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/_vendor/zod-to-json-schema/index.ts"],"names":[],"mappings":";;;AAAA,uDAA0B;AAC1B,oDAAuB;AACvB,6DAAgC;AAChC,wDAA2B;AAC3B,2DAA8B;AAC9B,6DAAgC;AAChC,8DAAiC;AACjC,+DAAkC;AAClC,+DAAkC;AAClC,6DAAgC;AAChC,4DAA+B;AAC/B,+DAAkC;AAClC,+DAAkC;AAClC,4DAA+B;AAC/B,oEAAuC;AACvC,+DAAkC;AAClC,2DAA8B;AAC9B,kEAAqC;AACrC,6DAAgC;AAChC,4DAA+B;AAC/B,gEAAmC;AACnC,8DAAiC;AACjC,8DAAiC;AACjC,gEAAmC;AACnC,gEAAmC;AACnC,+DAAkC;AAClC,gEAAmC;AACnC,8DAAiC;AACjC,2DAA8B;AAC9B,8DAAiC;AACjC,6DAAgC;AAChC,iEAAoC;AACpC,6DAAgC;AAChC,+DAAkC;AAClC,+DAAkC;AAClC,0DAAoD;AACpD,kBAAe,iCAAe,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/index.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6e444377a62dea65b741060347aabec50ea66003 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/index.mjs @@ -0,0 +1,38 @@ +export * from "./Options.mjs"; +export * from "./Refs.mjs"; +export * from "./errorMessages.mjs"; +export * from "./parseDef.mjs"; +export * from "./parsers/any.mjs"; +export * from "./parsers/array.mjs"; +export * from "./parsers/bigint.mjs"; +export * from "./parsers/boolean.mjs"; +export * from "./parsers/branded.mjs"; +export * from "./parsers/catch.mjs"; +export * from "./parsers/date.mjs"; +export * from "./parsers/default.mjs"; +export * from "./parsers/effects.mjs"; +export * from "./parsers/enum.mjs"; +export * from "./parsers/intersection.mjs"; +export * from "./parsers/literal.mjs"; +export * from "./parsers/map.mjs"; +export * from "./parsers/nativeEnum.mjs"; +export * from "./parsers/never.mjs"; +export * from "./parsers/null.mjs"; +export * from "./parsers/nullable.mjs"; +export * from "./parsers/number.mjs"; +export * from "./parsers/object.mjs"; +export * from "./parsers/optional.mjs"; +export * from "./parsers/pipeline.mjs"; +export * from "./parsers/promise.mjs"; +export * from "./parsers/readonly.mjs"; +export * from "./parsers/record.mjs"; +export * from "./parsers/set.mjs"; +export * from "./parsers/string.mjs"; +export * from "./parsers/tuple.mjs"; +export * from "./parsers/undefined.mjs"; +export * from "./parsers/union.mjs"; +export * from "./parsers/unknown.mjs"; +export * from "./zodToJsonSchema.mjs"; +import { zodToJsonSchema } from "./zodToJsonSchema.mjs"; +export default zodToJsonSchema; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/index.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..5862a5b8fd9aa980de52b77dbbea7abe3c2539ce --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../../src/_vendor/zod-to-json-schema/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAmCO,EAAE,eAAe,EAAE;AAC1B,eAAe,eAAe,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parseDef.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parseDef.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..85df1b1264591a8c2eabce166d99dcbd07e76d2b --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parseDef.d.mts @@ -0,0 +1,38 @@ +import { ZodTypeDef } from 'zod'; +import { JsonSchema7AnyType } from "./parsers/any.mjs"; +import { JsonSchema7ArrayType } from "./parsers/array.mjs"; +import { JsonSchema7BigintType } from "./parsers/bigint.mjs"; +import { JsonSchema7BooleanType } from "./parsers/boolean.mjs"; +import { JsonSchema7DateType } from "./parsers/date.mjs"; +import { JsonSchema7EnumType } from "./parsers/enum.mjs"; +import { JsonSchema7AllOfType } from "./parsers/intersection.mjs"; +import { JsonSchema7LiteralType } from "./parsers/literal.mjs"; +import { JsonSchema7MapType } from "./parsers/map.mjs"; +import { JsonSchema7NativeEnumType } from "./parsers/nativeEnum.mjs"; +import { JsonSchema7NeverType } from "./parsers/never.mjs"; +import { JsonSchema7NullType } from "./parsers/null.mjs"; +import { JsonSchema7NullableType } from "./parsers/nullable.mjs"; +import { JsonSchema7NumberType } from "./parsers/number.mjs"; +import { JsonSchema7ObjectType } from "./parsers/object.mjs"; +import { JsonSchema7RecordType } from "./parsers/record.mjs"; +import { JsonSchema7SetType } from "./parsers/set.mjs"; +import { JsonSchema7StringType } from "./parsers/string.mjs"; +import { JsonSchema7TupleType } from "./parsers/tuple.mjs"; +import { JsonSchema7UndefinedType } from "./parsers/undefined.mjs"; +import { JsonSchema7UnionType } from "./parsers/union.mjs"; +import { JsonSchema7UnknownType } from "./parsers/unknown.mjs"; +import { Refs } from "./Refs.mjs"; +type JsonSchema7RefType = { + $ref: string; +}; +type JsonSchema7Meta = { + title?: string; + default?: any; + description?: string; + markdownDescription?: string; +}; +export type JsonSchema7TypeUnion = JsonSchema7StringType | JsonSchema7ArrayType | JsonSchema7NumberType | JsonSchema7BigintType | JsonSchema7BooleanType | JsonSchema7DateType | JsonSchema7EnumType | JsonSchema7LiteralType | JsonSchema7NativeEnumType | JsonSchema7NullType | JsonSchema7NumberType | JsonSchema7ObjectType | JsonSchema7RecordType | JsonSchema7TupleType | JsonSchema7UnionType | JsonSchema7UndefinedType | JsonSchema7RefType | JsonSchema7NeverType | JsonSchema7MapType | JsonSchema7AnyType | JsonSchema7NullableType | JsonSchema7AllOfType | JsonSchema7UnknownType | JsonSchema7SetType; +export type JsonSchema7Type = JsonSchema7TypeUnion & JsonSchema7Meta; +export declare function parseDef(def: ZodTypeDef, refs: Refs, forceResolution?: boolean): JsonSchema7Type | undefined; +export {}; +//# sourceMappingURL=parseDef.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parseDef.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parseDef.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..cc204941f13dbbc20d55eea338ce7692606ae8eb --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parseDef.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"parseDef.d.mts","sourceRoot":"","sources":["../../src/_vendor/zod-to-json-schema/parseDef.ts"],"names":[],"mappings":"OAAO,EAAyB,UAAU,EAAE,MAAM,KAAK;OAChD,EAAE,kBAAkB,EAAe;OACnC,EAAE,oBAAoB,EAAiB;OACvC,EAAE,qBAAqB,EAAkB;OACzC,EAAE,sBAAsB,EAAmB;OAG3C,EAAE,mBAAmB,EAAgB;OAGrC,EAAE,mBAAmB,EAAgB;OACrC,EAAE,oBAAoB,EAAwB;OAC9C,EAAE,sBAAsB,EAAmB;OAC3C,EAAE,kBAAkB,EAAe;OACnC,EAAE,yBAAyB,EAAsB;OACjD,EAAE,oBAAoB,EAAiB;OACvC,EAAE,mBAAmB,EAAgB;OACrC,EAAE,uBAAuB,EAAoB;OAC7C,EAAE,qBAAqB,EAAkB;OACzC,EAAE,qBAAqB,EAAkB;OAIzC,EAAE,qBAAqB,EAAkB;OACzC,EAAE,kBAAkB,EAAe;OACnC,EAAE,qBAAqB,EAAkB;OACzC,EAAE,oBAAoB,EAAiB;OACvC,EAAE,wBAAwB,EAAqB;OAC/C,EAAE,oBAAoB,EAAiB;OACvC,EAAE,sBAAsB,EAAmB;OAC3C,EAAE,IAAI,EAAQ;AAIrB,KAAK,kBAAkB,GAAG;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC;AAC3C,KAAK,eAAe,GAAG;IACrB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE,GAAG,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAC9B,CAAC;AAEF,MAAM,MAAM,oBAAoB,GAC5B,qBAAqB,GACrB,oBAAoB,GACpB,qBAAqB,GACrB,qBAAqB,GACrB,sBAAsB,GACtB,mBAAmB,GACnB,mBAAmB,GACnB,sBAAsB,GACtB,yBAAyB,GACzB,mBAAmB,GACnB,qBAAqB,GACrB,qBAAqB,GACrB,qBAAqB,GACrB,oBAAoB,GACpB,oBAAoB,GACpB,wBAAwB,GACxB,kBAAkB,GAClB,oBAAoB,GACpB,kBAAkB,GAClB,kBAAkB,GAClB,uBAAuB,GACvB,oBAAoB,GACpB,sBAAsB,GACtB,kBAAkB,CAAC;AAEvB,MAAM,MAAM,eAAe,GAAG,oBAAoB,GAAG,eAAe,CAAC;AAErE,wBAAgB,QAAQ,CACtB,GAAG,EAAE,UAAU,EACf,IAAI,EAAE,IAAI,EACV,eAAe,UAAQ,GACtB,eAAe,GAAG,SAAS,CAoC7B"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parseDef.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parseDef.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..24da4864e9e706c4f9ffd08d7a39392e0f18f5c0 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parseDef.d.ts @@ -0,0 +1,38 @@ +import { ZodTypeDef } from 'zod'; +import { JsonSchema7AnyType } from "./parsers/any.js"; +import { JsonSchema7ArrayType } from "./parsers/array.js"; +import { JsonSchema7BigintType } from "./parsers/bigint.js"; +import { JsonSchema7BooleanType } from "./parsers/boolean.js"; +import { JsonSchema7DateType } from "./parsers/date.js"; +import { JsonSchema7EnumType } from "./parsers/enum.js"; +import { JsonSchema7AllOfType } from "./parsers/intersection.js"; +import { JsonSchema7LiteralType } from "./parsers/literal.js"; +import { JsonSchema7MapType } from "./parsers/map.js"; +import { JsonSchema7NativeEnumType } from "./parsers/nativeEnum.js"; +import { JsonSchema7NeverType } from "./parsers/never.js"; +import { JsonSchema7NullType } from "./parsers/null.js"; +import { JsonSchema7NullableType } from "./parsers/nullable.js"; +import { JsonSchema7NumberType } from "./parsers/number.js"; +import { JsonSchema7ObjectType } from "./parsers/object.js"; +import { JsonSchema7RecordType } from "./parsers/record.js"; +import { JsonSchema7SetType } from "./parsers/set.js"; +import { JsonSchema7StringType } from "./parsers/string.js"; +import { JsonSchema7TupleType } from "./parsers/tuple.js"; +import { JsonSchema7UndefinedType } from "./parsers/undefined.js"; +import { JsonSchema7UnionType } from "./parsers/union.js"; +import { JsonSchema7UnknownType } from "./parsers/unknown.js"; +import { Refs } from "./Refs.js"; +type JsonSchema7RefType = { + $ref: string; +}; +type JsonSchema7Meta = { + title?: string; + default?: any; + description?: string; + markdownDescription?: string; +}; +export type JsonSchema7TypeUnion = JsonSchema7StringType | JsonSchema7ArrayType | JsonSchema7NumberType | JsonSchema7BigintType | JsonSchema7BooleanType | JsonSchema7DateType | JsonSchema7EnumType | JsonSchema7LiteralType | JsonSchema7NativeEnumType | JsonSchema7NullType | JsonSchema7NumberType | JsonSchema7ObjectType | JsonSchema7RecordType | JsonSchema7TupleType | JsonSchema7UnionType | JsonSchema7UndefinedType | JsonSchema7RefType | JsonSchema7NeverType | JsonSchema7MapType | JsonSchema7AnyType | JsonSchema7NullableType | JsonSchema7AllOfType | JsonSchema7UnknownType | JsonSchema7SetType; +export type JsonSchema7Type = JsonSchema7TypeUnion & JsonSchema7Meta; +export declare function parseDef(def: ZodTypeDef, refs: Refs, forceResolution?: boolean): JsonSchema7Type | undefined; +export {}; +//# sourceMappingURL=parseDef.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parseDef.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parseDef.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..640b95886f2b3d4f35da4b8d37356c59bb7f74bb --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parseDef.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"parseDef.d.ts","sourceRoot":"","sources":["../../src/_vendor/zod-to-json-schema/parseDef.ts"],"names":[],"mappings":"OAAO,EAAyB,UAAU,EAAE,MAAM,KAAK;OAChD,EAAE,kBAAkB,EAAe;OACnC,EAAE,oBAAoB,EAAiB;OACvC,EAAE,qBAAqB,EAAkB;OACzC,EAAE,sBAAsB,EAAmB;OAG3C,EAAE,mBAAmB,EAAgB;OAGrC,EAAE,mBAAmB,EAAgB;OACrC,EAAE,oBAAoB,EAAwB;OAC9C,EAAE,sBAAsB,EAAmB;OAC3C,EAAE,kBAAkB,EAAe;OACnC,EAAE,yBAAyB,EAAsB;OACjD,EAAE,oBAAoB,EAAiB;OACvC,EAAE,mBAAmB,EAAgB;OACrC,EAAE,uBAAuB,EAAoB;OAC7C,EAAE,qBAAqB,EAAkB;OACzC,EAAE,qBAAqB,EAAkB;OAIzC,EAAE,qBAAqB,EAAkB;OACzC,EAAE,kBAAkB,EAAe;OACnC,EAAE,qBAAqB,EAAkB;OACzC,EAAE,oBAAoB,EAAiB;OACvC,EAAE,wBAAwB,EAAqB;OAC/C,EAAE,oBAAoB,EAAiB;OACvC,EAAE,sBAAsB,EAAmB;OAC3C,EAAE,IAAI,EAAQ;AAIrB,KAAK,kBAAkB,GAAG;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC;AAC3C,KAAK,eAAe,GAAG;IACrB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE,GAAG,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAC9B,CAAC;AAEF,MAAM,MAAM,oBAAoB,GAC5B,qBAAqB,GACrB,oBAAoB,GACpB,qBAAqB,GACrB,qBAAqB,GACrB,sBAAsB,GACtB,mBAAmB,GACnB,mBAAmB,GACnB,sBAAsB,GACtB,yBAAyB,GACzB,mBAAmB,GACnB,qBAAqB,GACrB,qBAAqB,GACrB,qBAAqB,GACrB,oBAAoB,GACpB,oBAAoB,GACpB,wBAAwB,GACxB,kBAAkB,GAClB,oBAAoB,GACpB,kBAAkB,GAClB,kBAAkB,GAClB,uBAAuB,GACvB,oBAAoB,GACpB,sBAAsB,GACtB,kBAAkB,CAAC;AAEvB,MAAM,MAAM,eAAe,GAAG,oBAAoB,GAAG,eAAe,CAAC;AAErE,wBAAgB,QAAQ,CACtB,GAAG,EAAE,UAAU,EACf,IAAI,EAAE,IAAI,EACV,eAAe,UAAQ,GACtB,eAAe,GAAG,SAAS,CAoC7B"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parseDef.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parseDef.js new file mode 100644 index 0000000000000000000000000000000000000000..84a82e781f070d21f1fc5f808fb8b718d71a43e8 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parseDef.js @@ -0,0 +1,186 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseDef = parseDef; +const zod_1 = require("zod"); +const any_1 = require("./parsers/any.js"); +const array_1 = require("./parsers/array.js"); +const bigint_1 = require("./parsers/bigint.js"); +const boolean_1 = require("./parsers/boolean.js"); +const branded_1 = require("./parsers/branded.js"); +const catch_1 = require("./parsers/catch.js"); +const date_1 = require("./parsers/date.js"); +const default_1 = require("./parsers/default.js"); +const effects_1 = require("./parsers/effects.js"); +const enum_1 = require("./parsers/enum.js"); +const intersection_1 = require("./parsers/intersection.js"); +const literal_1 = require("./parsers/literal.js"); +const map_1 = require("./parsers/map.js"); +const nativeEnum_1 = require("./parsers/nativeEnum.js"); +const never_1 = require("./parsers/never.js"); +const null_1 = require("./parsers/null.js"); +const nullable_1 = require("./parsers/nullable.js"); +const number_1 = require("./parsers/number.js"); +const object_1 = require("./parsers/object.js"); +const optional_1 = require("./parsers/optional.js"); +const pipeline_1 = require("./parsers/pipeline.js"); +const promise_1 = require("./parsers/promise.js"); +const record_1 = require("./parsers/record.js"); +const set_1 = require("./parsers/set.js"); +const string_1 = require("./parsers/string.js"); +const tuple_1 = require("./parsers/tuple.js"); +const undefined_1 = require("./parsers/undefined.js"); +const union_1 = require("./parsers/union.js"); +const unknown_1 = require("./parsers/unknown.js"); +const readonly_1 = require("./parsers/readonly.js"); +const Options_1 = require("./Options.js"); +function parseDef(def, refs, forceResolution = false) { + const seenItem = refs.seen.get(def); + if (refs.override) { + const overrideResult = refs.override?.(def, refs, seenItem, forceResolution); + if (overrideResult !== Options_1.ignoreOverride) { + return overrideResult; + } + } + if (seenItem && !forceResolution) { + const seenSchema = get$ref(seenItem, refs); + if (seenSchema !== undefined) { + if ('$ref' in seenSchema) { + refs.seenRefs.add(seenSchema.$ref); + } + return seenSchema; + } + } + const newItem = { def, path: refs.currentPath, jsonSchema: undefined }; + refs.seen.set(def, newItem); + const jsonSchema = selectParser(def, def.typeName, refs, forceResolution); + if (jsonSchema) { + addMeta(def, refs, jsonSchema); + } + newItem.jsonSchema = jsonSchema; + return jsonSchema; +} +const get$ref = (item, refs) => { + switch (refs.$refStrategy) { + case 'root': + return { $ref: item.path.join('/') }; + // this case is needed as OpenAI strict mode doesn't support top-level `$ref`s, i.e. + // the top-level schema *must* be `{"type": "object", "properties": {...}}` but if we ever + // need to define a `$ref`, relative `$ref`s aren't supported, so we need to extract + // the schema to `#/definitions/` and reference that. + // + // e.g. if we need to reference a schema at + // `["#","definitions","contactPerson","properties","person1","properties","name"]` + // then we'll extract it out to `contactPerson_properties_person1_properties_name` + case 'extract-to-root': + const name = item.path.slice(refs.basePath.length + 1).join('_'); + // we don't need to extract the root schema in this case, as it's already + // been added to the definitions + if (name !== refs.name && refs.nameStrategy === 'duplicate-ref') { + refs.definitions[name] = item.def; + } + return { $ref: [...refs.basePath, refs.definitionPath, name].join('/') }; + case 'relative': + return { $ref: getRelativePath(refs.currentPath, item.path) }; + case 'none': + case 'seen': { + if (item.path.length < refs.currentPath.length && + item.path.every((value, index) => refs.currentPath[index] === value)) { + console.warn(`Recursive reference detected at ${refs.currentPath.join('/')}! Defaulting to any`); + return {}; + } + return refs.$refStrategy === 'seen' ? {} : undefined; + } + } +}; +const getRelativePath = (pathA, pathB) => { + let i = 0; + for (; i < pathA.length && i < pathB.length; i++) { + if (pathA[i] !== pathB[i]) + break; + } + return [(pathA.length - i).toString(), ...pathB.slice(i)].join('/'); +}; +const selectParser = (def, typeName, refs, forceResolution) => { + switch (typeName) { + case zod_1.ZodFirstPartyTypeKind.ZodString: + return (0, string_1.parseStringDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodNumber: + return (0, number_1.parseNumberDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodObject: + return (0, object_1.parseObjectDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodBigInt: + return (0, bigint_1.parseBigintDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodBoolean: + return (0, boolean_1.parseBooleanDef)(); + case zod_1.ZodFirstPartyTypeKind.ZodDate: + return (0, date_1.parseDateDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodUndefined: + return (0, undefined_1.parseUndefinedDef)(); + case zod_1.ZodFirstPartyTypeKind.ZodNull: + return (0, null_1.parseNullDef)(refs); + case zod_1.ZodFirstPartyTypeKind.ZodArray: + return (0, array_1.parseArrayDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodUnion: + case zod_1.ZodFirstPartyTypeKind.ZodDiscriminatedUnion: + return (0, union_1.parseUnionDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodIntersection: + return (0, intersection_1.parseIntersectionDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodTuple: + return (0, tuple_1.parseTupleDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodRecord: + return (0, record_1.parseRecordDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodLiteral: + return (0, literal_1.parseLiteralDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodEnum: + return (0, enum_1.parseEnumDef)(def); + case zod_1.ZodFirstPartyTypeKind.ZodNativeEnum: + return (0, nativeEnum_1.parseNativeEnumDef)(def); + case zod_1.ZodFirstPartyTypeKind.ZodNullable: + return (0, nullable_1.parseNullableDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodOptional: + return (0, optional_1.parseOptionalDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodMap: + return (0, map_1.parseMapDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodSet: + return (0, set_1.parseSetDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodLazy: + return parseDef(def.getter()._def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodPromise: + return (0, promise_1.parsePromiseDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodNaN: + case zod_1.ZodFirstPartyTypeKind.ZodNever: + return (0, never_1.parseNeverDef)(); + case zod_1.ZodFirstPartyTypeKind.ZodEffects: + return (0, effects_1.parseEffectsDef)(def, refs, forceResolution); + case zod_1.ZodFirstPartyTypeKind.ZodAny: + return (0, any_1.parseAnyDef)(); + case zod_1.ZodFirstPartyTypeKind.ZodUnknown: + return (0, unknown_1.parseUnknownDef)(); + case zod_1.ZodFirstPartyTypeKind.ZodDefault: + return (0, default_1.parseDefaultDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodBranded: + return (0, branded_1.parseBrandedDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodReadonly: + return (0, readonly_1.parseReadonlyDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodCatch: + return (0, catch_1.parseCatchDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodPipeline: + return (0, pipeline_1.parsePipelineDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodFunction: + case zod_1.ZodFirstPartyTypeKind.ZodVoid: + case zod_1.ZodFirstPartyTypeKind.ZodSymbol: + return undefined; + default: + return ((_) => undefined)(typeName); + } +}; +const addMeta = (def, refs, jsonSchema) => { + if (def.description) { + jsonSchema.description = def.description; + if (refs.markdownDescription) { + jsonSchema.markdownDescription = def.description; + } + } + return jsonSchema; +}; +//# sourceMappingURL=parseDef.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parseDef.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parseDef.js.map new file mode 100644 index 0000000000000000000000000000000000000000..cf7f9fc1ac8a7e2cdc59c7f071bf565c762ef0df --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parseDef.js.map @@ -0,0 +1 @@ +{"version":3,"file":"parseDef.js","sourceRoot":"","sources":["../../src/_vendor/zod-to-json-schema/parseDef.ts"],"names":[],"mappings":";;AAsEA,4BAwCC;AA9GD,6BAAwD;AACxD,0CAAgE;AAChE,8CAAsE;AACtE,gDAAyE;AACzE,kDAA4E;AAC5E,kDAAoD;AACpD,8CAAgD;AAChD,4CAAmE;AACnE,k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AE,IAAI,CAAC,CAAC;QACpC,KAAK,2BAAqB,CAAC,UAAU;YACnC,OAAO,IAAA,yBAAe,EAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QACpC,KAAK,2BAAqB,CAAC,WAAW;YACpC,OAAO,IAAA,2BAAgB,EAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QACrC,KAAK,2BAAqB,CAAC,QAAQ;YACjC,OAAO,IAAA,qBAAa,EAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QAClC,KAAK,2BAAqB,CAAC,WAAW;YACpC,OAAO,IAAA,2BAAgB,EAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QACrC,KAAK,2BAAqB,CAAC,WAAW,CAAC;QACvC,KAAK,2BAAqB,CAAC,OAAO,CAAC;QACnC,KAAK,2BAAqB,CAAC,SAAS;YAClC,OAAO,SAAS,CAAC;QACnB;YACE,OAAO,CAAC,CAAC,CAAQ,EAAE,EAAE,CAAC,SAAS,CAAC,CAAC,QAAQ,CAAC,CAAC;IAC/C,CAAC;AACH,CAAC,CAAC;AAEF,MAAM,OAAO,GAAG,CAAC,GAAe,EAAE,IAAU,EAAE,UAA2B,EAAmB,EAAE;IAC5F,IAAI,GAAG,CAAC,WAAW,EAAE,CAAC;QACpB,UAAU,CAAC,WAAW,GAAG,GAAG,CAAC,WAAW,CAAC;QAEzC,IAAI,IAAI,CAAC,mBAAmB,EAAE,CAAC;YAC7B,UAAU,CAAC,mBAAmB,GAAG,GAAG,CAAC,WAAW,CAAC;QACnD,CAAC;IACH,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parseDef.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parseDef.mjs new file mode 100644 index 0000000000000000000000000000000000000000..380eaeae18e0c988459c7db39a3f7ca0c4ab0699 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parseDef.mjs @@ -0,0 +1,183 @@ +import { ZodFirstPartyTypeKind } from 'zod'; +import { parseAnyDef } from "./parsers/any.mjs"; +import { parseArrayDef } from "./parsers/array.mjs"; +import { parseBigintDef } from "./parsers/bigint.mjs"; +import { parseBooleanDef } from "./parsers/boolean.mjs"; +import { parseBrandedDef } from "./parsers/branded.mjs"; +import { parseCatchDef } from "./parsers/catch.mjs"; +import { parseDateDef } from "./parsers/date.mjs"; +import { parseDefaultDef } from "./parsers/default.mjs"; +import { parseEffectsDef } from "./parsers/effects.mjs"; +import { parseEnumDef } from "./parsers/enum.mjs"; +import { parseIntersectionDef } from "./parsers/intersection.mjs"; +import { parseLiteralDef } from "./parsers/literal.mjs"; +import { parseMapDef } from "./parsers/map.mjs"; +import { parseNativeEnumDef } from "./parsers/nativeEnum.mjs"; +import { parseNeverDef } from "./parsers/never.mjs"; +import { parseNullDef } from "./parsers/null.mjs"; +import { parseNullableDef } from "./parsers/nullable.mjs"; +import { parseNumberDef } from "./parsers/number.mjs"; +import { parseObjectDef } from "./parsers/object.mjs"; +import { parseOptionalDef } from "./parsers/optional.mjs"; +import { parsePipelineDef } from "./parsers/pipeline.mjs"; +import { parsePromiseDef } from "./parsers/promise.mjs"; +import { parseRecordDef } from "./parsers/record.mjs"; +import { parseSetDef } from "./parsers/set.mjs"; +import { parseStringDef } from "./parsers/string.mjs"; +import { parseTupleDef } from "./parsers/tuple.mjs"; +import { parseUndefinedDef } from "./parsers/undefined.mjs"; +import { parseUnionDef } from "./parsers/union.mjs"; +import { parseUnknownDef } from "./parsers/unknown.mjs"; +import { parseReadonlyDef } from "./parsers/readonly.mjs"; +import { ignoreOverride } from "./Options.mjs"; +export function parseDef(def, refs, forceResolution = false) { + const seenItem = refs.seen.get(def); + if (refs.override) { + const overrideResult = refs.override?.(def, refs, seenItem, forceResolution); + if (overrideResult !== ignoreOverride) { + return overrideResult; + } + } + if (seenItem && !forceResolution) { + const seenSchema = get$ref(seenItem, refs); + if (seenSchema !== undefined) { + if ('$ref' in seenSchema) { + refs.seenRefs.add(seenSchema.$ref); + } + return seenSchema; + } + } + const newItem = { def, path: refs.currentPath, jsonSchema: undefined }; + refs.seen.set(def, newItem); + const jsonSchema = selectParser(def, def.typeName, refs, forceResolution); + if (jsonSchema) { + addMeta(def, refs, jsonSchema); + } + newItem.jsonSchema = jsonSchema; + return jsonSchema; +} +const get$ref = (item, refs) => { + switch (refs.$refStrategy) { + case 'root': + return { $ref: item.path.join('/') }; + // this case is needed as OpenAI strict mode doesn't support top-level `$ref`s, i.e. + // the top-level schema *must* be `{"type": "object", "properties": {...}}` but if we ever + // need to define a `$ref`, relative `$ref`s aren't supported, so we need to extract + // the schema to `#/definitions/` and reference that. + // + // e.g. if we need to reference a schema at + // `["#","definitions","contactPerson","properties","person1","properties","name"]` + // then we'll extract it out to `contactPerson_properties_person1_properties_name` + case 'extract-to-root': + const name = item.path.slice(refs.basePath.length + 1).join('_'); + // we don't need to extract the root schema in this case, as it's already + // been added to the definitions + if (name !== refs.name && refs.nameStrategy === 'duplicate-ref') { + refs.definitions[name] = item.def; + } + return { $ref: [...refs.basePath, refs.definitionPath, name].join('/') }; + case 'relative': + return { $ref: getRelativePath(refs.currentPath, item.path) }; + case 'none': + case 'seen': { + if (item.path.length < refs.currentPath.length && + item.path.every((value, index) => refs.currentPath[index] === value)) { + console.warn(`Recursive reference detected at ${refs.currentPath.join('/')}! Defaulting to any`); + return {}; + } + return refs.$refStrategy === 'seen' ? {} : undefined; + } + } +}; +const getRelativePath = (pathA, pathB) => { + let i = 0; + for (; i < pathA.length && i < pathB.length; i++) { + if (pathA[i] !== pathB[i]) + break; + } + return [(pathA.length - i).toString(), ...pathB.slice(i)].join('/'); +}; +const selectParser = (def, typeName, refs, forceResolution) => { + switch (typeName) { + case ZodFirstPartyTypeKind.ZodString: + return parseStringDef(def, refs); + case ZodFirstPartyTypeKind.ZodNumber: + return parseNumberDef(def, refs); + case ZodFirstPartyTypeKind.ZodObject: + return parseObjectDef(def, refs); + case ZodFirstPartyTypeKind.ZodBigInt: + return parseBigintDef(def, refs); + case ZodFirstPartyTypeKind.ZodBoolean: + return parseBooleanDef(); + case ZodFirstPartyTypeKind.ZodDate: + return parseDateDef(def, refs); + case ZodFirstPartyTypeKind.ZodUndefined: + return parseUndefinedDef(); + case ZodFirstPartyTypeKind.ZodNull: + return parseNullDef(refs); + case ZodFirstPartyTypeKind.ZodArray: + return parseArrayDef(def, refs); + case ZodFirstPartyTypeKind.ZodUnion: + case ZodFirstPartyTypeKind.ZodDiscriminatedUnion: + return parseUnionDef(def, refs); + case ZodFirstPartyTypeKind.ZodIntersection: + return parseIntersectionDef(def, refs); + case ZodFirstPartyTypeKind.ZodTuple: + return parseTupleDef(def, refs); + case ZodFirstPartyTypeKind.ZodRecord: + return parseRecordDef(def, refs); + case ZodFirstPartyTypeKind.ZodLiteral: + return parseLiteralDef(def, refs); + case ZodFirstPartyTypeKind.ZodEnum: + return parseEnumDef(def); + case ZodFirstPartyTypeKind.ZodNativeEnum: + return parseNativeEnumDef(def); + case ZodFirstPartyTypeKind.ZodNullable: + return parseNullableDef(def, refs); + case ZodFirstPartyTypeKind.ZodOptional: + return parseOptionalDef(def, refs); + case ZodFirstPartyTypeKind.ZodMap: + return parseMapDef(def, refs); + case ZodFirstPartyTypeKind.ZodSet: + return parseSetDef(def, refs); + case ZodFirstPartyTypeKind.ZodLazy: + return parseDef(def.getter()._def, refs); + case ZodFirstPartyTypeKind.ZodPromise: + return parsePromiseDef(def, refs); + case ZodFirstPartyTypeKind.ZodNaN: + case ZodFirstPartyTypeKind.ZodNever: + return parseNeverDef(); + case ZodFirstPartyTypeKind.ZodEffects: + return parseEffectsDef(def, refs, forceResolution); + case ZodFirstPartyTypeKind.ZodAny: + return parseAnyDef(); + case ZodFirstPartyTypeKind.ZodUnknown: + return parseUnknownDef(); + case ZodFirstPartyTypeKind.ZodDefault: + return parseDefaultDef(def, refs); + case ZodFirstPartyTypeKind.ZodBranded: + return parseBrandedDef(def, refs); + case ZodFirstPartyTypeKind.ZodReadonly: + return parseReadonlyDef(def, refs); + case ZodFirstPartyTypeKind.ZodCatch: + return parseCatchDef(def, refs); + case ZodFirstPartyTypeKind.ZodPipeline: + return parsePipelineDef(def, refs); + case ZodFirstPartyTypeKind.ZodFunction: + case ZodFirstPartyTypeKind.ZodVoid: + case ZodFirstPartyTypeKind.ZodSymbol: + return undefined; + default: + return ((_) => undefined)(typeName); + } +}; +const addMeta = (def, refs, jsonSchema) => { + if (def.description) { + jsonSchema.description = def.description; + if (refs.markdownDescription) { + jsonSchema.markdownDescription = def.description; + } + } + return jsonSchema; +}; +//# sourceMappingURL=parseDef.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parseDef.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parseDef.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..a06d7cafc801b08b40de35ec0b7bee1ffaffa1fa --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parseDef.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"parseDef.mjs","sourceRoot":"","sources":["../../src/_vendor/zod-to-json-schema/parseDef.ts"],"names":[],"mappings":"OAAO,EAAE,qBAAqB,EAAc,MAAM,KAAK;OAChD,EAAsB,WAAW,EAAE;OACnC,EAAwB,aAAa,EAAE;OACvC,EAAyB,cAAc,EAAE;OACzC,EAA0B,eAAe,EAAE;OAC3C,EAAE,eAAe,EAAE;OACnB,EAAE,aAAa,EAAE;OACjB,EAAuB,YAAY,EAAE;OACrC,EAAE,eAAe,EAAE;OACnB,EAAE,eAAe,EAAE;OACnB,EAAuB,YAAY,EAAE;OACrC,EAAwB,oBAAoB,EAAE;OAC9C,EAA0B,eAAe,EAAE;OAC3C,EAAsB,WAAW,EAAE;OACnC,EAA6B,kBAAkB,EA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GAAG,EAAE,IAAI,CAAC,CAAC;QACpC,KAAK,qBAAqB,CAAC,WAAW;YACpC,OAAO,gBAAgB,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QACrC,KAAK,qBAAqB,CAAC,QAAQ;YACjC,OAAO,aAAa,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QAClC,KAAK,qBAAqB,CAAC,WAAW;YACpC,OAAO,gBAAgB,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QACrC,KAAK,qBAAqB,CAAC,WAAW,CAAC;QACvC,KAAK,qBAAqB,CAAC,OAAO,CAAC;QACnC,KAAK,qBAAqB,CAAC,SAAS;YAClC,OAAO,SAAS,CAAC;QACnB;YACE,OAAO,CAAC,CAAC,CAAQ,EAAE,EAAE,CAAC,SAAS,CAAC,CAAC,QAAQ,CAAC,CAAC;IAC/C,CAAC;AACH,CAAC,CAAC;AAEF,MAAM,OAAO,GAAG,CAAC,GAAe,EAAE,IAAU,EAAE,UAA2B,EAAmB,EAAE;IAC5F,IAAI,GAAG,CAAC,WAAW,EAAE,CAAC;QACpB,UAAU,CAAC,WAAW,GAAG,GAAG,CAAC,WAAW,CAAC;QAEzC,IAAI,IAAI,CAAC,mBAAmB,EAAE,CAAC;YAC7B,UAAU,CAAC,mBAAmB,GAAG,GAAG,CAAC,WAAW,CAAC;QACnD,CAAC;IACH,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/any.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/any.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..f753849f3d7a0bf5531e61260def53c6b3489db5 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/any.d.mts @@ -0,0 +1,3 @@ +export type JsonSchema7AnyType = {}; +export declare function parseAnyDef(): JsonSchema7AnyType; +//# sourceMappingURL=any.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/any.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/any.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..aa68968603485b834fe9a6a98697114c7b7b3ebb --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/any.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"any.d.mts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/any.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAEpC,wBAAgB,WAAW,IAAI,kBAAkB,CAEhD"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/any.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/any.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..587884c2f537f0f2d29072cc01432f82268a4ab8 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/any.d.ts @@ -0,0 +1,3 @@ +export type JsonSchema7AnyType = {}; +export declare function parseAnyDef(): JsonSchema7AnyType; +//# sourceMappingURL=any.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/any.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/any.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..dcd23347c39aaa6fa4c933e48d6aca844b32969c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/any.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"any.d.ts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/any.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAEpC,wBAAgB,WAAW,IAAI,kBAAkB,CAEhD"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/any.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/any.js new file mode 100644 index 0000000000000000000000000000000000000000..b4d78a62363c032d35a7fcad50c1d6bfc4fd7789 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/any.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseAnyDef = parseAnyDef; +function parseAnyDef() { + return {}; +} +//# sourceMappingURL=any.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/any.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/any.js.map new file mode 100644 index 0000000000000000000000000000000000000000..9dbc775ebc547805b72e5dca77ad954a3e1da7ff --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/any.js.map @@ -0,0 +1 @@ +{"version":3,"file":"any.js","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/any.ts"],"names":[],"mappings":";;AAEA,kCAEC;AAFD,SAAgB,WAAW;IACzB,OAAO,EAAE,CAAC;AACZ,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/any.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/any.mjs new file mode 100644 index 0000000000000000000000000000000000000000..082dc766151c6ead291696b645ad283d86c132af --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/any.mjs @@ -0,0 +1,4 @@ +export function parseAnyDef() { + return {}; +} +//# sourceMappingURL=any.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/any.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/any.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..4f0715d32c16129f4f88d97bb7f6cecf275137e8 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/any.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"any.mjs","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/any.ts"],"names":[],"mappings":"AAEA,MAAM,UAAU,WAAW;IACzB,OAAO,EAAE,CAAC;AACZ,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/array.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/array.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..efaaea3c58013b042d28b7ee29d90b47363f92d8 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/array.d.mts @@ -0,0 +1,13 @@ +import { ZodArrayDef } from 'zod'; +import { ErrorMessages } from "../errorMessages.mjs"; +import { JsonSchema7Type } from "../parseDef.mjs"; +import { Refs } from "../Refs.mjs"; +export type JsonSchema7ArrayType = { + type: 'array'; + items?: JsonSchema7Type | undefined; + minItems?: number; + maxItems?: number; + errorMessages?: ErrorMessages; +}; +export declare function parseArrayDef(def: ZodArrayDef, refs: Refs): JsonSchema7ArrayType; +//# sourceMappingURL=array.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/array.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/array.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..7ee980461b695396489e4351ae81fe595fe40be2 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/array.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"array.d.mts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/array.ts"],"names":[],"mappings":"OAAO,EAAE,WAAW,EAAyB,MAAM,KAAK;OACjD,EAAE,aAAa,EAA6B;OAC5C,EAAE,eAAe,EAAY;OAC7B,EAAE,IAAI,EAAE;AAEf,MAAM,MAAM,oBAAoB,GAAG;IACjC,IAAI,EAAE,OAAO,CAAC;IACd,KAAK,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC;IACpC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,aAAa,CAAC,EAAE,aAAa,CAAC,oBAAoB,EAAE,OAAO,CAAC,CAAC;CAC9D,CAAC;AAEF,wBAAgB,aAAa,CAAC,GAAG,EAAE,WAAW,EAAE,IAAI,EAAE,IAAI,wBAsBzD"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/array.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/array.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..af38f20486a58104bdeb54845cbdf5bd972aa83f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/array.d.ts @@ -0,0 +1,13 @@ +import { ZodArrayDef } from 'zod'; +import { ErrorMessages } from "../errorMessages.js"; +import { JsonSchema7Type } from "../parseDef.js"; +import { Refs } from "../Refs.js"; +export type JsonSchema7ArrayType = { + type: 'array'; + items?: JsonSchema7Type | undefined; + minItems?: number; + maxItems?: number; + errorMessages?: ErrorMessages; +}; +export declare function parseArrayDef(def: ZodArrayDef, refs: Refs): JsonSchema7ArrayType; +//# sourceMappingURL=array.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/array.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/array.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..68731b6eabaaf5932401eb09405a51688a3ade3e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/array.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"array.d.ts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/array.ts"],"names":[],"mappings":"OAAO,EAAE,WAAW,EAAyB,MAAM,KAAK;OACjD,EAAE,aAAa,EAA6B;OAC5C,EAAE,eAAe,EAAY;OAC7B,EAAE,IAAI,EAAE;AAEf,MAAM,MAAM,oBAAoB,GAAG;IACjC,IAAI,EAAE,OAAO,CAAC;IACd,KAAK,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC;IACpC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,aAAa,CAAC,EAAE,aAAa,CAAC,oBAAoB,EAAE,OAAO,CAAC,CAAC;CAC9D,CAAC;AAEF,wBAAgB,aAAa,CAAC,GAAG,EAAE,WAAW,EAAE,IAAI,EAAE,IAAI,wBAsBzD"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/array.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/array.js new file mode 100644 index 0000000000000000000000000000000000000000..8d6cd25d04464fa3138b228236b5646b95c8bf2c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/array.js @@ -0,0 +1,29 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseArrayDef = parseArrayDef; +const zod_1 = require("zod"); +const errorMessages_1 = require("../errorMessages.js"); +const parseDef_1 = require("../parseDef.js"); +function parseArrayDef(def, refs) { + const res = { + type: 'array', + }; + if (def.type?._def?.typeName !== zod_1.ZodFirstPartyTypeKind.ZodAny) { + res.items = (0, parseDef_1.parseDef)(def.type._def, { + ...refs, + currentPath: [...refs.currentPath, 'items'], + }); + } + if (def.minLength) { + (0, errorMessages_1.setResponseValueAndErrors)(res, 'minItems', def.minLength.value, def.minLength.message, refs); + } + if (def.maxLength) { + (0, errorMessages_1.setResponseValueAndErrors)(res, 'maxItems', def.maxLength.value, def.maxLength.message, refs); + } + if (def.exactLength) { + (0, errorMessages_1.setResponseValueAndErrors)(res, 'minItems', def.exactLength.value, def.exactLength.message, refs); + (0, errorMessages_1.setResponseValueAndErrors)(res, 'maxItems', def.exactLength.value, def.exactLength.message, refs); + } + return res; +} +//# sourceMappingURL=array.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/array.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/array.js.map new file mode 100644 index 0000000000000000000000000000000000000000..828753c4dcfe9b8801498510e93013e4716be2af --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/array.js.map @@ -0,0 +1 @@ +{"version":3,"file":"array.js","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/array.ts"],"names":[],"mappings":";;AAaA,sCAsBC;AAnCD,6BAAyD;AACzD,uDAA4E;AAC5E,6CAAwD;AAWxD,SAAgB,aAAa,CAAC,GAAgB,EAAE,IAAU;IACxD,MAAM,GAAG,GAAyB;QAChC,IAAI,EAAE,OAAO;KACd,CAAC;IACF,IAAI,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,QAAQ,KAAK,2BAAqB,CAAC,MAAM,EAAE,CAAC;QAC9D,GAAG,CAAC,KAAK,GAAG,IAAA,mBAAQ,EAAC,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE;YAClC,GAAG,IAAI;YACP,WAAW,EAAE,CAAC,GAAG,IAAI,CAAC,WAAW,EAAE,OAAO,CAAC;SAC5C,CAAC,CAAC;IACL,CAAC;IAED,IAAI,GAAG,CAAC,SAAS,EAAE,CAAC;QAClB,IAAA,yCAAyB,EAAC,GAAG,EAAE,UAAU,EAAE,GAAG,CAAC,SAAS,CAAC,KAAK,EAAE,GAAG,CAAC,SAAS,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;IAC/F,CAAC;IACD,IAAI,GAAG,CAAC,SAAS,EAAE,CAAC;QAClB,IAAA,yCAAyB,EAAC,GAAG,EAAE,UAAU,EAAE,GAAG,CAAC,SAAS,CAAC,KAAK,EAAE,GAAG,CAAC,SAAS,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;IAC/F,CAAC;IACD,IAAI,GAAG,CAAC,WAAW,EAAE,CAAC;QACpB,IAAA,yCAAyB,EAAC,GAAG,EAAE,UAAU,EAAE,GAAG,CAAC,WAAW,CAAC,KAAK,EAAE,GAAG,CAAC,WAAW,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;QACjG,IAAA,yCAAyB,EAAC,GAAG,EAAE,UAAU,EAAE,GAAG,CAAC,WAAW,CAAC,KAAK,EAAE,GAAG,CAAC,WAAW,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;IACnG,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/array.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/array.mjs new file mode 100644 index 0000000000000000000000000000000000000000..599a1ab543d0e2768e6e6e08324f746fef37796c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/array.mjs @@ -0,0 +1,26 @@ +import { ZodFirstPartyTypeKind } from 'zod'; +import { setResponseValueAndErrors } from "../errorMessages.mjs"; +import { parseDef } from "../parseDef.mjs"; +export function parseArrayDef(def, refs) { + const res = { + type: 'array', + }; + if (def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) { + res.items = parseDef(def.type._def, { + ...refs, + currentPath: [...refs.currentPath, 'items'], + }); + } + if (def.minLength) { + setResponseValueAndErrors(res, 'minItems', def.minLength.value, def.minLength.message, refs); + } + if (def.maxLength) { + setResponseValueAndErrors(res, 'maxItems', def.maxLength.value, def.maxLength.message, refs); + } + if (def.exactLength) { + setResponseValueAndErrors(res, 'minItems', def.exactLength.value, def.exactLength.message, refs); + setResponseValueAndErrors(res, 'maxItems', def.exactLength.value, def.exactLength.message, refs); + } + return res; +} +//# sourceMappingURL=array.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/array.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/array.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..c112d0bf2a6c579d2ccdec619e697b9a4284c60d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/array.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"array.mjs","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/array.ts"],"names":[],"mappings":"OAAO,EAAe,qBAAqB,EAAE,MAAM,KAAK;OACjD,EAAiB,yBAAyB,EAAE;OAC5C,EAAmB,QAAQ,EAAE;AAWpC,MAAM,UAAU,aAAa,CAAC,GAAgB,EAAE,IAAU;IACxD,MAAM,GAAG,GAAyB;QAChC,IAAI,EAAE,OAAO;KACd,CAAC;IACF,IAAI,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,QAAQ,KAAK,qBAAqB,CAAC,MAAM,EAAE,CAAC;QAC9D,GAAG,CAAC,KAAK,GAAG,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE;YAClC,GAAG,IAAI;YACP,WAAW,EAAE,CAAC,GAAG,IAAI,CAAC,WAAW,EAAE,OAAO,CAAC;SAC5C,CAAC,CAAC;IACL,CAAC;IAED,IAAI,GAAG,CAAC,SAAS,EAAE,CAAC;QAClB,yBAAyB,CAAC,GAAG,EAAE,UAAU,EAAE,GAAG,CAAC,SAAS,CAAC,KAAK,EAAE,GAAG,CAAC,SAAS,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;IAC/F,CAAC;IACD,IAAI,GAAG,CAAC,SAAS,EAAE,CAAC;QAClB,yBAAyB,CAAC,GAAG,EAAE,UAAU,EAAE,GAAG,CAAC,SAAS,CAAC,KAAK,EAAE,GAAG,CAAC,SAAS,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;IAC/F,CAAC;IACD,IAAI,GAAG,CAAC,WAAW,EAAE,CAAC;QACpB,yBAAyB,CAAC,GAAG,EAAE,UAAU,EAAE,GAAG,CAAC,WAAW,CAAC,KAAK,EAAE,GAAG,CAAC,WAAW,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;QACjG,yBAAyB,CAAC,GAAG,EAAE,UAAU,EAAE,GAAG,CAAC,WAAW,CAAC,KAAK,EAAE,GAAG,CAAC,WAAW,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;IACnG,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/bigint.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/bigint.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..17cd0fe5104115bf7815941c87dc3e31fd72eb8a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/bigint.d.mts @@ -0,0 +1,15 @@ +import { ZodBigIntDef } from 'zod'; +import { Refs } from "../Refs.mjs"; +import { ErrorMessages } from "../errorMessages.mjs"; +export type JsonSchema7BigintType = { + type: 'integer'; + format: 'int64'; + minimum?: BigInt; + exclusiveMinimum?: BigInt; + maximum?: BigInt; + exclusiveMaximum?: BigInt; + multipleOf?: BigInt; + errorMessage?: ErrorMessages; +}; +export declare function parseBigintDef(def: ZodBigIntDef, refs: Refs): JsonSchema7BigintType; +//# sourceMappingURL=bigint.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/bigint.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/bigint.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..9bf3424ff01a7e929ead6dd4aa0ad8d477334f83 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/bigint.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"bigint.d.mts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/bigint.ts"],"names":[],"mappings":"OAAO,EAAE,YAAY,EAAE,MAAM,KAAK;OAC3B,EAAE,IAAI,EAAE;OACR,EAAE,aAAa,EAA6B;AAEnD,MAAM,MAAM,qBAAqB,GAAG;IAClC,IAAI,EAAE,SAAS,CAAC;IAChB,MAAM,EAAE,OAAO,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,YAAY,CAAC,EAAE,aAAa,CAAC,qBAAqB,CAAC,CAAC;CACrD,CAAC;AAEF,wBAAgB,cAAc,CAAC,GAAG,EAAE,YAAY,EAAE,IAAI,EAAE,IAAI,GAAG,qBAAqB,CA4CnF"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/bigint.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/bigint.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a029808e6516ff4332859d811ffbf3a9e916b0b7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/bigint.d.ts @@ -0,0 +1,15 @@ +import { ZodBigIntDef } from 'zod'; +import { Refs } from "../Refs.js"; +import { ErrorMessages } from "../errorMessages.js"; +export type JsonSchema7BigintType = { + type: 'integer'; + format: 'int64'; + minimum?: BigInt; + exclusiveMinimum?: BigInt; + maximum?: BigInt; + exclusiveMaximum?: BigInt; + multipleOf?: BigInt; + errorMessage?: ErrorMessages; +}; +export declare function parseBigintDef(def: ZodBigIntDef, refs: Refs): JsonSchema7BigintType; +//# sourceMappingURL=bigint.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/bigint.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/bigint.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..007b306ecbd9760aac505f48221481efea2966e3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/bigint.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"bigint.d.ts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/bigint.ts"],"names":[],"mappings":"OAAO,EAAE,YAAY,EAAE,MAAM,KAAK;OAC3B,EAAE,IAAI,EAAE;OACR,EAAE,aAAa,EAA6B;AAEnD,MAAM,MAAM,qBAAqB,GAAG;IAClC,IAAI,EAAE,SAAS,CAAC;IAChB,MAAM,EAAE,OAAO,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,YAAY,CAAC,EAAE,aAAa,CAAC,qBAAqB,CAAC,CAAC;CACrD,CAAC;AAEF,wBAAgB,cAAc,CAAC,GAAG,EAAE,YAAY,EAAE,IAAI,EAAE,IAAI,GAAG,qBAAqB,CA4CnF"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/bigint.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/bigint.js new file mode 100644 index 0000000000000000000000000000000000000000..ce53d22bb1d5e0f73b7ec98088d5c05665da327c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/bigint.js @@ -0,0 +1,53 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseBigintDef = parseBigintDef; +const errorMessages_1 = require("../errorMessages.js"); +function parseBigintDef(def, refs) { + const res = { + type: 'integer', + format: 'int64', + }; + if (!def.checks) + return res; + for (const check of def.checks) { + switch (check.kind) { + case 'min': + if (refs.target === 'jsonSchema7') { + if (check.inclusive) { + (0, errorMessages_1.setResponseValueAndErrors)(res, 'minimum', check.value, check.message, refs); + } + else { + (0, errorMessages_1.setResponseValueAndErrors)(res, 'exclusiveMinimum', check.value, check.message, refs); + } + } + else { + if (!check.inclusive) { + res.exclusiveMinimum = true; + } + (0, errorMessages_1.setResponseValueAndErrors)(res, 'minimum', check.value, check.message, refs); + } + break; + case 'max': + if (refs.target === 'jsonSchema7') { + if (check.inclusive) { + (0, errorMessages_1.setResponseValueAndErrors)(res, 'maximum', check.value, check.message, refs); + } + else { + (0, errorMessages_1.setResponseValueAndErrors)(res, 'exclusiveMaximum', check.value, check.message, refs); + } + } + else { + if (!check.inclusive) { + res.exclusiveMaximum = true; + } + (0, errorMessages_1.setResponseValueAndErrors)(res, 'maximum', check.value, check.message, refs); + } + break; + case 'multipleOf': + (0, errorMessages_1.setResponseValueAndErrors)(res, 'multipleOf', check.value, check.message, refs); + break; + } + } + return res; +} +//# sourceMappingURL=bigint.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/bigint.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/bigint.js.map new file mode 100644 index 0000000000000000000000000000000000000000..cf1fabedefc4292382d5c9567695516cd7b40c4e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/bigint.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bigint.js","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/bigint.ts"],"names":[],"mappings":";;AAeA,wCA4CC;AAzDD,uDAA4E;AAa5E,SAAgB,cAAc,CAAC,GAAiB,EAAE,IAAU;IAC1D,MAAM,GAAG,GAA0B;QACjC,IAAI,EAAE,SAAS;QACf,MAAM,EAAE,OAAO;KAChB,CAAC;IAEF,IAAI,CAAC,GAAG,CAAC,MAAM;QAAE,OAAO,GAAG,CAAC;IAE5B,KAAK,MAAM,KAAK,IAAI,GAAG,CAAC,MAAM,EAAE,CAAC;QAC/B,QAAQ,KAAK,CAAC,IAAI,EAAE,CAAC;YACnB,KAAK,KAAK;gBACR,IAAI,IAAI,CAAC,MAAM,KAAK,aAAa,EAAE,CAAC;oBAClC,IAAI,KAAK,CAAC,SAAS,EAAE,CAAC;wBACpB,IAAA,yCAAyB,EAAC,GAAG,EAAE,SAAS,EAAE,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;oBAC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gBAC/E,MAAM;QACV,CAAC;IACH,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/bigint.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/bigint.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1275b3dc1c29c280d2203e64f21adb19b53cc8ec --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/bigint.mjs @@ -0,0 +1,50 @@ +import { setResponseValueAndErrors } from "../errorMessages.mjs"; +export function parseBigintDef(def, refs) { + const res = { + type: 'integer', + format: 'int64', + }; + if (!def.checks) + return res; + for (const check of def.checks) { + switch (check.kind) { + case 'min': + if (refs.target === 'jsonSchema7') { + if (check.inclusive) { + setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs); + } + else { + setResponseValueAndErrors(res, 'exclusiveMinimum', check.value, check.message, refs); + } + } + else { + if (!check.inclusive) { + res.exclusiveMinimum = true; + } + setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs); + } + break; + case 'max': + if (refs.target === 'jsonSchema7') { + if (check.inclusive) { + setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs); + } + else { + setResponseValueAndErrors(res, 'exclusiveMaximum', check.value, check.message, refs); + } + } + else { + if (!check.inclusive) { + res.exclusiveMaximum = true; + } + setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs); + } + break; + case 'multipleOf': + setResponseValueAndErrors(res, 'multipleOf', check.value, check.message, refs); + break; + } + } + return res; +} +//# sourceMappingURL=bigint.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/bigint.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/bigint.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..0e5cbfdaf737fca9e30dd3ebdbadfd5539ff36aa --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/bigint.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"bigint.mjs","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/bigint.ts"],"names":[],"mappings":"OAEO,EAAiB,yBAAyB,EAAE;AAanD,MAAM,UAAU,cAAc,CAAC,GAAiB,EAAE,IAAU;IAC1D,MAAM,GAAG,GAA0B;QACjC,IAAI,EAAE,SAAS;QACf,MAAM,EAAE,OAAO;KAChB,CAAC;IAEF,IAAI,CAAC,GAAG,CAAC,MAAM;QAAE,OAAO,GAAG,CAAC;IAE5B,KAAK,MAAM,KAAK,IAAI,GAAG,CAAC,MAAM,EAAE,CAAC;QAC/B,QAAQ,KAAK,CAAC,IAAI,EAAE,CAAC;YACnB,KAAK,KAAK;gBACR,IAAI,IAAI,CAAC,MAAM,KAAK,aAAa,EAAE,CAAC;oBAClC,IAAI,KAAK,CAAC,SAAS,EAAE,CAAC;wBACpB,yBAAyB,CAAC,GAAG,EAAE,SAAS,EAAE,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;oBAC9E,CAAC;yBAAM,CAAC;wBACN,yBAAyB,CAAC,GAAG,EAAE,kBAAkB,EAAE,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;oBACvF,CAAC;gBACH,CAAC;qBAAM,CAAC;oBACN,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,CAAC;wBACrB,GAAG,CAAC,gBAAgB,GAAG,IAAW,CAAC;oBACrC,CAAC;oBACD,yBAAyB,CAAC,GAAG,EAAE,SAAS,EAAE,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;gBAC9E,CAAC;gBACD,MAAM;YACR,KAAK,KAAK;gBACR,IAAI,IAAI,CAAC,MAAM,KAAK,aAAa,EAAE,CAAC;oBAClC,IAAI,KAAK,CAAC,SAAS,EAAE,CAAC;wBACpB,yBAAyB,CAAC,GAAG,EAAE,SAAS,EAAE,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;oBAC9E,CAAC;yBAAM,CAAC;wBACN,yBAAyB,CAAC,GAAG,EAAE,kBAAkB,EAAE,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;oBACvF,CAAC;gBACH,CAAC;qBAAM,CAAC;oBACN,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,CAAC;wBACrB,GAAG,CAAC,gBAAgB,GAAG,IAAW,CAAC;oBACrC,CAAC;oBACD,yBAAyB,CAAC,GAAG,EAAE,SAAS,EAAE,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;gBAC9E,CAAC;gBACD,MAAM;YACR,KAAK,YAAY;gBACf,yBAAyB,CAAC,GAAG,EAAE,YAAY,EAAE,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;gBAC/E,MAAM;QACV,CAAC;IACH,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/boolean.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/boolean.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..76c60658a50dcf4164ed95dfd70ba13af0d7dd85 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/boolean.d.mts @@ -0,0 +1,5 @@ +export type JsonSchema7BooleanType = { + type: 'boolean'; +}; +export declare function parseBooleanDef(): JsonSchema7BooleanType; +//# sourceMappingURL=boolean.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/boolean.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/boolean.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..0ed153fc48156ac9cb7f884a13ca635834f51eef --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/boolean.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"boolean.d.mts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/boolean.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,sBAAsB,GAAG;IACnC,IAAI,EAAE,SAAS,CAAC;CACjB,CAAC;AAEF,wBAAgB,eAAe,IAAI,sBAAsB,CAIxD"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/boolean.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/boolean.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7de6510ebb0b6252df42d932a1a9c4ac77d39aad --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/boolean.d.ts @@ -0,0 +1,5 @@ +export type JsonSchema7BooleanType = { + type: 'boolean'; +}; +export declare function parseBooleanDef(): JsonSchema7BooleanType; +//# sourceMappingURL=boolean.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/boolean.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/boolean.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..ac0a8f2d9bcc3c684280dec67144ba888590b473 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/boolean.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"boolean.d.ts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/boolean.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,sBAAsB,GAAG;IACnC,IAAI,EAAE,SAAS,CAAC;CACjB,CAAC;AAEF,wBAAgB,eAAe,IAAI,sBAAsB,CAIxD"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/boolean.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/boolean.js new file mode 100644 index 0000000000000000000000000000000000000000..a00ee7988e7e79bd324d187e8226516a87cd7c6c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/boolean.js @@ -0,0 +1,9 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseBooleanDef = parseBooleanDef; +function parseBooleanDef() { + return { + type: 'boolean', + }; +} +//# sourceMappingURL=boolean.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/boolean.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/boolean.js.map new file mode 100644 index 0000000000000000000000000000000000000000..0966bc61862b37447401b317514b6e4a5b4453c7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/boolean.js.map @@ -0,0 +1 @@ +{"version":3,"file":"boolean.js","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/boolean.ts"],"names":[],"mappings":";;AAIA,0CAIC;AAJD,SAAgB,eAAe;IAC7B,OAAO;QACL,IAAI,EAAE,SAAS;KAChB,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/boolean.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/boolean.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3f3ee5a039ee06e2554e0ce488da17009ba543ee --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/boolean.mjs @@ -0,0 +1,6 @@ +export function parseBooleanDef() { + return { + type: 'boolean', + }; +} +//# sourceMappingURL=boolean.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/boolean.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/boolean.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..574a99afde81ff05316694a6824fb30e0c9e6773 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/boolean.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"boolean.mjs","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/boolean.ts"],"names":[],"mappings":"AAIA,MAAM,UAAU,eAAe;IAC7B,OAAO;QACL,IAAI,EAAE,SAAS;KAChB,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/branded.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/branded.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..d4c68de9927a5e72ce5aa285e9e17f585a4068bd --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/branded.d.mts @@ -0,0 +1,4 @@ +import { ZodBrandedDef } from 'zod'; +import { Refs } from "../Refs.mjs"; +export declare function parseBrandedDef(_def: ZodBrandedDef, refs: Refs): import("../parseDef").JsonSchema7Type | undefined; +//# sourceMappingURL=branded.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/branded.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/branded.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..85b570f758c5941dea0b15efc5647601bfc6883d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/branded.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"branded.d.mts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/branded.ts"],"names":[],"mappings":"OAAO,EAAE,aAAa,EAAE,MAAM,KAAK;OAE5B,EAAE,IAAI,EAAE;AAEf,wBAAgB,eAAe,CAAC,IAAI,EAAE,aAAa,CAAC,GAAG,CAAC,EAAE,IAAI,EAAE,IAAI,qDAEnE"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/branded.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/branded.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..298ebc5778b8a322982445bd8ac1a8028a27285c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/branded.d.ts @@ -0,0 +1,4 @@ +import { ZodBrandedDef } from 'zod'; +import { Refs } from "../Refs.js"; +export declare function parseBrandedDef(_def: ZodBrandedDef, refs: Refs): import("../parseDef").JsonSchema7Type | undefined; +//# sourceMappingURL=branded.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/branded.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/branded.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..f10f3f1d13e49ac072673015d0f3c8ab8eeb2cb0 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/branded.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"branded.d.ts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/branded.ts"],"names":[],"mappings":"OAAO,EAAE,aAAa,EAAE,MAAM,KAAK;OAE5B,EAAE,IAAI,EAAE;AAEf,wBAAgB,eAAe,CAAC,IAAI,EAAE,aAAa,CAAC,GAAG,CAAC,EAAE,IAAI,EAAE,IAAI,qDAEnE"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/branded.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/branded.js new file mode 100644 index 0000000000000000000000000000000000000000..915aed64521fec051ac1ab91c55ffd87179c18e7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/branded.js @@ -0,0 +1,8 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseBrandedDef = parseBrandedDef; +const parseDef_1 = require("../parseDef.js"); +function parseBrandedDef(_def, refs) { + return (0, parseDef_1.parseDef)(_def.type._def, refs); +} +//# sourceMappingURL=branded.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/branded.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/branded.js.map new file mode 100644 index 0000000000000000000000000000000000000000..6de373d1ca4511558b72a83f038193ca86c5fb9f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/branded.js.map @@ -0,0 +1 @@ +{"version":3,"file":"branded.js","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/branded.ts"],"names":[],"mappings":";;AAIA,0CAEC;AALD,6CAAuC;AAGvC,SAAgB,eAAe,CAAC,IAAwB,EAAE,IAAU;IAClE,OAAO,IAAA,mBAAQ,EAAC,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;AACxC,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/branded.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/branded.mjs new file mode 100644 index 0000000000000000000000000000000000000000..fcd6d3e2f5631c09544f27cdaf36816e94ba0c78 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/branded.mjs @@ -0,0 +1,5 @@ +import { parseDef } from "../parseDef.mjs"; +export function parseBrandedDef(_def, refs) { + return parseDef(_def.type._def, refs); +} +//# sourceMappingURL=branded.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/branded.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/branded.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..4520f5f5fbc4ef0c43de7c3c85e3e0d1840cfd1d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/branded.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"branded.mjs","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/branded.ts"],"names":[],"mappings":"OACO,EAAE,QAAQ,EAAE;AAGnB,MAAM,UAAU,eAAe,CAAC,IAAwB,EAAE,IAAU;IAClE,OAAO,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;AACxC,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/catch.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/catch.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..d2e3169ff6fa310a508b6910b03393f3042424a5 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/catch.d.mts @@ -0,0 +1,4 @@ +import { ZodCatchDef } from 'zod'; +import { Refs } from "../Refs.mjs"; +export declare const parseCatchDef: (def: ZodCatchDef, refs: Refs) => import("../parseDef").JsonSchema7Type | undefined; +//# sourceMappingURL=catch.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/catch.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/catch.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..2a429a5e38e3c6245e05fd58da0e3159fd4800cd --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/catch.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"catch.d.mts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/catch.ts"],"names":[],"mappings":"OAAO,EAAE,WAAW,EAAE,MAAM,KAAK;OAE1B,EAAE,IAAI,EAAE;AAEf,eAAO,MAAM,aAAa,GAAI,KAAK,WAAW,CAAC,GAAG,CAAC,EAAE,MAAM,IAAI,sDAE9D,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/catch.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/catch.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..055b593e188b23376453456a2f35c657325d300d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/catch.d.ts @@ -0,0 +1,4 @@ +import { ZodCatchDef } from 'zod'; +import { Refs } from "../Refs.js"; +export declare const parseCatchDef: (def: ZodCatchDef, refs: Refs) => import("../parseDef").JsonSchema7Type | undefined; +//# sourceMappingURL=catch.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/catch.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/catch.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..8dec830b376d800e0758fee4617314c9c2abd1ce --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/catch.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"catch.d.ts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/catch.ts"],"names":[],"mappings":"OAAO,EAAE,WAAW,EAAE,MAAM,KAAK;OAE1B,EAAE,IAAI,EAAE;AAEf,eAAO,MAAM,aAAa,GAAI,KAAK,WAAW,CAAC,GAAG,CAAC,EAAE,MAAM,IAAI,sDAE9D,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/catch.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/catch.js new file mode 100644 index 0000000000000000000000000000000000000000..79aa9baa2c03106e49775709512622b60402079d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/catch.js @@ -0,0 +1,9 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseCatchDef = void 0; +const parseDef_1 = require("../parseDef.js"); +const parseCatchDef = (def, refs) => { + return (0, parseDef_1.parseDef)(def.innerType._def, refs); +}; +exports.parseCatchDef = parseCatchDef; +//# sourceMappingURL=catch.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/catch.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/catch.js.map new file mode 100644 index 0000000000000000000000000000000000000000..680a799cf1ea5b376578b6600893bc7b64a067c1 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/catch.js.map @@ -0,0 +1 @@ +{"version":3,"file":"catch.js","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/catch.ts"],"names":[],"mappings":";;;AACA,6CAAuC;AAGhC,MAAM,aAAa,GAAG,CAAC,GAAqB,EAAE,IAAU,EAAE,EAAE;IACjE,OAAO,IAAA,mBAAQ,EAAC,GAAG,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;AAC5C,CAAC,CAAC;AAFW,QAAA,aAAa,iBAExB"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/catch.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/catch.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ac7abd582a9fb30c4d619beaa48da94ac70a795c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/catch.mjs @@ -0,0 +1,5 @@ +import { parseDef } from "../parseDef.mjs"; +export const parseCatchDef = (def, refs) => { + return parseDef(def.innerType._def, refs); +}; +//# sourceMappingURL=catch.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/catch.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/catch.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..381272034e32d60e126c87601432f8a67616c00d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/catch.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"catch.mjs","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/catch.ts"],"names":[],"mappings":"OACO,EAAE,QAAQ,EAAE;AAGnB,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,GAAqB,EAAE,IAAU,EAAE,EAAE;IACjE,OAAO,QAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;AAC5C,CAAC,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/date.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/date.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..a63bd055e35146cf24296ffcbe2af535c4378681 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/date.d.mts @@ -0,0 +1,16 @@ +import { ZodDateDef } from 'zod'; +import { Refs } from "../Refs.mjs"; +import { ErrorMessages } from "../errorMessages.mjs"; +import { JsonSchema7NumberType } from "./number.mjs"; +import { DateStrategy } from "../Options.mjs"; +export type JsonSchema7DateType = { + type: 'integer' | 'string'; + format: 'unix-time' | 'date-time' | 'date'; + minimum?: number; + maximum?: number; + errorMessage?: ErrorMessages; +} | { + anyOf: JsonSchema7DateType[]; +}; +export declare function parseDateDef(def: ZodDateDef, refs: Refs, overrideDateStrategy?: DateStrategy): JsonSchema7DateType; +//# sourceMappingURL=date.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/date.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/date.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..2091248f17313b1a9e9ee7196d64b96d5a8da58d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/date.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"date.d.mts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/date.ts"],"names":[],"mappings":"OAAO,EAAE,UAAU,EAAE,MAAM,KAAK;OACzB,EAAE,IAAI,EAAE;OACR,EAAE,aAAa,EAA6B;OAC5C,EAAE,qBAAqB,EAAE;OACzB,EAAE,YAAY,EAAE;AAEvB,MAAM,MAAM,mBAAmB,GAC3B;IACE,IAAI,EAAE,SAAS,GAAG,QAAQ,CAAC;IAC3B,MAAM,EAAE,WAAW,GAAG,WAAW,GAAG,MAAM,CAAC;IAC3C,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,YAAY,CAAC,EAAE,aAAa,CAAC,qBAAqB,CAAC,CAAC;CACrD,GACD;IACE,KAAK,EAAE,mBAAmB,EAAE,CAAC;CAC9B,CAAC;AAEN,wBAAgB,YAAY,CAC1B,GAAG,EAAE,UAAU,EACf,IAAI,EAAE,IAAI,EACV,oBAAoB,CAAC,EAAE,YAAY,GAClC,mBAAmB,CAwBrB"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/date.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/date.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1361f22148cc8766d68558c77ebe74608b8d9db5 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/date.d.ts @@ -0,0 +1,16 @@ +import { ZodDateDef } from 'zod'; +import { Refs } from "../Refs.js"; +import { ErrorMessages } from "../errorMessages.js"; +import { JsonSchema7NumberType } from "./number.js"; +import { DateStrategy } from "../Options.js"; +export type JsonSchema7DateType = { + type: 'integer' | 'string'; + format: 'unix-time' | 'date-time' | 'date'; + minimum?: number; + maximum?: number; + errorMessage?: ErrorMessages; +} | { + anyOf: JsonSchema7DateType[]; +}; +export declare function parseDateDef(def: ZodDateDef, refs: Refs, overrideDateStrategy?: DateStrategy): JsonSchema7DateType; +//# sourceMappingURL=date.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/date.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/date.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..13622f96ebe82850de26dc6cd74322ce7896f487 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/date.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"date.d.ts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/date.ts"],"names":[],"mappings":"OAAO,EAAE,UAAU,EAAE,MAAM,KAAK;OACzB,EAAE,IAAI,EAAE;OACR,EAAE,aAAa,EAA6B;OAC5C,EAAE,qBAAqB,EAAE;OACzB,EAAE,YAAY,EAAE;AAEvB,MAAM,MAAM,mBAAmB,GAC3B;IACE,IAAI,EAAE,SAAS,GAAG,QAAQ,CAAC;IAC3B,MAAM,EAAE,WAAW,GAAG,WAAW,GAAG,MAAM,CAAC;IAC3C,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,YAAY,CAAC,EAAE,aAAa,CAAC,qBAAqB,CAAC,CAAC;CACrD,GACD;IACE,KAAK,EAAE,mBAAmB,EAAE,CAAC;CAC9B,CAAC;AAEN,wBAAgB,YAAY,CAC1B,GAAG,EAAE,UAAU,EACf,IAAI,EAAE,IAAI,EACV,oBAAoB,CAAC,EAAE,YAAY,GAClC,mBAAmB,CAwBrB"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/date.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/date.js new file mode 100644 index 0000000000000000000000000000000000000000..dbd21c29b0ec7e9cf2bcccfb07de5e2e52fedbdb --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/date.js @@ -0,0 +1,50 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseDateDef = parseDateDef; +const errorMessages_1 = require("../errorMessages.js"); +function parseDateDef(def, refs, overrideDateStrategy) { + const strategy = overrideDateStrategy ?? refs.dateStrategy; + if (Array.isArray(strategy)) { + return { + anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)), + }; + } + switch (strategy) { + case 'string': + case 'format:date-time': + return { + type: 'string', + format: 'date-time', + }; + case 'format:date': + return { + type: 'string', + format: 'date', + }; + case 'integer': + return integerDateParser(def, refs); + } +} +const integerDateParser = (def, refs) => { + const res = { + type: 'integer', + format: 'unix-time', + }; + if (refs.target === 'openApi3') { + return res; + } + for (const check of def.checks) { + switch (check.kind) { + case 'min': + (0, errorMessages_1.setResponseValueAndErrors)(res, 'minimum', check.value, // This is in milliseconds + check.message, refs); + break; + case 'max': + (0, errorMessages_1.setResponseValueAndErrors)(res, 'maximum', check.value, // This is in milliseconds + check.message, refs); + break; + } + } + return res; +}; +//# sourceMappingURL=date.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/date.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/date.js.map new file mode 100644 index 0000000000000000000000000000000000000000..3b7d22c2a39d3b1ba2967c6d6e7642fd2f39e9f8 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/date.js.map @@ -0,0 +1 @@ +{"version":3,"file":"date.js","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/date.ts"],"names":[],"mappings":";;AAkBA,oCA4BC;AA5CD,uDAA4E;AAgB5E,SAAgB,YAAY,CAC1B,GAAe,EACf,IAAU,EACV,oBAAmC;IAEnC,MAAM,QAAQ,GAAG,oBAAoB,IAAI,IAAI,CAAC,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ACF,MAAM;QACV,CAAC;IACH,CAAC;IAED,OAAO,GAAG,CAAC;AACb,CAAC,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/date.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/date.mjs new file mode 100644 index 0000000000000000000000000000000000000000..640bb004873d9b75c7909b45a8e186755ea13416 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/date.mjs @@ -0,0 +1,47 @@ +import { setResponseValueAndErrors } from "../errorMessages.mjs"; +export function parseDateDef(def, refs, overrideDateStrategy) { + const strategy = overrideDateStrategy ?? refs.dateStrategy; + if (Array.isArray(strategy)) { + return { + anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)), + }; + } + switch (strategy) { + case 'string': + case 'format:date-time': + return { + type: 'string', + format: 'date-time', + }; + case 'format:date': + return { + type: 'string', + format: 'date', + }; + case 'integer': + return integerDateParser(def, refs); + } +} +const integerDateParser = (def, refs) => { + const res = { + type: 'integer', + format: 'unix-time', + }; + if (refs.target === 'openApi3') { + return res; + } + for (const check of def.checks) { + switch (check.kind) { + case 'min': + setResponseValueAndErrors(res, 'minimum', check.value, // This is in milliseconds + check.message, refs); + break; + case 'max': + setResponseValueAndErrors(res, 'maximum', check.value, // This is in milliseconds + check.message, refs); + break; + } + } + return res; +}; +//# sourceMappingURL=date.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/date.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/date.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..3e9eec4b82714ba99049e27ad6bc03435c9bed73 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/date.mjs.map @@ -0,0 +1 @@ +{"version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AAE,0BAA0B;gBACvC,KAAK,CAAC,OAAO,EACb,IAAI,CACL,CAAC;gBACF,MAAM;YACR,KAAK,KAAK;gBACR,yBAAyB,CACvB,GAAG,EACH,SAAS,EACT,KAAK,CAAC,KAAK,EAAE,0BAA0B;gBACvC,KAAK,CAAC,OAAO,EACb,IAAI,CACL,CAAC;gBACF,MAAM;QACV,CAAC;IACH,CAAC;IAED,OAAO,GAAG,CAAC;AACb,CAAC,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/default.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/default.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..e31d86917ffa7ccf2eeb985795bdc8760afe0e4d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/default.d.mts @@ -0,0 +1,7 @@ +import { ZodDefaultDef } from 'zod'; +import { JsonSchema7Type } from "../parseDef.mjs"; +import { Refs } from "../Refs.mjs"; +export declare function parseDefaultDef(_def: ZodDefaultDef, refs: Refs): JsonSchema7Type & { + default: any; +}; +//# sourceMappingURL=default.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/default.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/default.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..c0ce84c33fa4a581824b1ef7c915e44fa69f0c9c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/default.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"default.d.mts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/default.ts"],"names":[],"mappings":"OAAO,EAAE,aAAa,EAAE,MAAM,KAAK;OAC5B,EAAE,eAAe,EAAY;OAC7B,EAAE,IAAI,EAAE;AAEf,wBAAgB,eAAe,CAAC,IAAI,EAAE,aAAa,EAAE,IAAI,EAAE,IAAI,GAAG,eAAe,GAAG;IAAE,OAAO,EAAE,GAAG,CAAA;CAAE,CAKnG"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/default.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/default.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b572a7b961de2442ffd0129a91082ffdae1ed45f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/default.d.ts @@ -0,0 +1,7 @@ +import { ZodDefaultDef } from 'zod'; +import { JsonSchema7Type } from "../parseDef.js"; +import { Refs } from "../Refs.js"; +export declare function parseDefaultDef(_def: ZodDefaultDef, refs: Refs): JsonSchema7Type & { + default: any; +}; +//# sourceMappingURL=default.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/default.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/default.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..3615815f51d5dba1d00611901caf35b80752a16b --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/default.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"default.d.ts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/default.ts"],"names":[],"mappings":"OAAO,EAAE,aAAa,EAAE,MAAM,KAAK;OAC5B,EAAE,eAAe,EAAY;OAC7B,EAAE,IAAI,EAAE;AAEf,wBAAgB,eAAe,CAAC,IAAI,EAAE,aAAa,EAAE,IAAI,EAAE,IAAI,GAAG,eAAe,GAAG;IAAE,OAAO,EAAE,GAAG,CAAA;CAAE,CAKnG"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/default.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/default.js new file mode 100644 index 0000000000000000000000000000000000000000..f03447e35ae100e0fcc1c1017aaedce154fa670f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/default.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseDefaultDef = parseDefaultDef; +const parseDef_1 = require("../parseDef.js"); +function parseDefaultDef(_def, refs) { + return { + ...(0, parseDef_1.parseDef)(_def.innerType._def, refs), + default: _def.defaultValue(), + }; +} +//# sourceMappingURL=default.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/default.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/default.js.map new file mode 100644 index 0000000000000000000000000000000000000000..57c54b3ddad04ba87cfa53aae0a33a21c4333136 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/default.js.map @@ -0,0 +1 @@ +{"version":3,"file":"default.js","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/default.ts"],"names":[],"mappings":";;AAIA,0CAKC;AARD,6CAAwD;AAGxD,SAAgB,eAAe,CAAC,IAAmB,EAAE,IAAU;IAC7D,OAAO;QACL,GAAG,IAAA,mBAAQ,EAAC,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC;QACtC,OAAO,EAAE,IAAI,CAAC,YAAY,EAAE;KAC7B,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/default.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/default.mjs new file mode 100644 index 0000000000000000000000000000000000000000..446639deb5757e71811678f1862033fba4b27c60 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/default.mjs @@ -0,0 +1,8 @@ +import { parseDef } from "../parseDef.mjs"; +export function parseDefaultDef(_def, refs) { + return { + ...parseDef(_def.innerType._def, refs), + default: _def.defaultValue(), + }; +} +//# sourceMappingURL=default.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/default.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/default.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..6b0a172b70fba58e06cb4ee7695f3f320eadee56 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/default.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"default.mjs","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/default.ts"],"names":[],"mappings":"OACO,EAAmB,QAAQ,EAAE;AAGpC,MAAM,UAAU,eAAe,CAAC,IAAmB,EAAE,IAAU;IAC7D,OAAO;QACL,GAAG,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC;QACtC,OAAO,EAAE,IAAI,CAAC,YAAY,EAAE;KAC7B,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/effects.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/effects.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..4b4c0b2c97769567b4ddb5eb496b64f28a9f4249 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/effects.d.mts @@ -0,0 +1,5 @@ +import { ZodEffectsDef } from 'zod'; +import { JsonSchema7Type } from "../parseDef.mjs"; +import { Refs } from "../Refs.mjs"; +export declare function parseEffectsDef(_def: ZodEffectsDef, refs: Refs, forceResolution: boolean): JsonSchema7Type | undefined; +//# sourceMappingURL=effects.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/effects.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/effects.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..85e43b292319f93bc44613013632545175e9b3d3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/effects.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"effects.d.mts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/effects.ts"],"names":[],"mappings":"OAAO,EAAE,aAAa,EAAE,MAAM,KAAK;OAC5B,EAAE,eAAe,EAAY;OAC7B,EAAE,IAAI,EAAE;AAEf,wBAAgB,eAAe,CAC7B,IAAI,EAAE,aAAa,EACnB,IAAI,EAAE,IAAI,EACV,eAAe,EAAE,OAAO,GACvB,eAAe,GAAG,SAAS,CAE7B"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/effects.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/effects.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7b319703a032cf1cef0356bedce95af767536eb0 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/effects.d.ts @@ -0,0 +1,5 @@ +import { ZodEffectsDef } from 'zod'; +import { JsonSchema7Type } from "../parseDef.js"; +import { Refs } from "../Refs.js"; +export declare function parseEffectsDef(_def: ZodEffectsDef, refs: Refs, forceResolution: boolean): JsonSchema7Type | undefined; +//# sourceMappingURL=effects.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/effects.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/effects.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..6e18ab185ad778319a7da1f97da9785db195214a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/effects.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"effects.d.ts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/effects.ts"],"names":[],"mappings":"OAAO,EAAE,aAAa,EAAE,MAAM,KAAK;OAC5B,EAAE,eAAe,EAAY;OAC7B,EAAE,IAAI,EAAE;AAEf,wBAAgB,eAAe,CAC7B,IAAI,EAAE,aAAa,EACnB,IAAI,EAAE,IAAI,EACV,eAAe,EAAE,OAAO,GACvB,eAAe,GAAG,SAAS,CAE7B"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/effects.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/effects.js new file mode 100644 index 0000000000000000000000000000000000000000..14687e886c35065bbc36973d5a8fe7f60e8d068a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/effects.js @@ -0,0 +1,8 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseEffectsDef = parseEffectsDef; +const parseDef_1 = require("../parseDef.js"); +function parseEffectsDef(_def, refs, forceResolution) { + return refs.effectStrategy === 'input' ? (0, parseDef_1.parseDef)(_def.schema._def, refs, forceResolution) : {}; +} +//# sourceMappingURL=effects.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/effects.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/effects.js.map new file mode 100644 index 0000000000000000000000000000000000000000..e6629e82d368d1477ac7e7cfa7b523b8bf0ca80d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/effects.js.map @@ -0,0 +1 @@ +{"version":3,"file":"effects.js","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/effects.ts"],"names":[],"mappings":";;AAIA,0CAMC;AATD,6CAAwD;AAGxD,SAAgB,eAAe,CAC7B,IAAmB,EACnB,IAAU,EACV,eAAwB;IAExB,OAAO,IAAI,CAAC,cAAc,KAAK,OAAO,CAAC,CAAC,CAAC,IAAA,mBAAQ,EAAC,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE,IAAI,EAAE,eAAe,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AAClG,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/effects.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/effects.mjs new file mode 100644 index 0000000000000000000000000000000000000000..fdff42c0df7c460c677ae406a7d848fe0c47c05b --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/effects.mjs @@ -0,0 +1,5 @@ +import { parseDef } from "../parseDef.mjs"; +export function parseEffectsDef(_def, refs, forceResolution) { + return refs.effectStrategy === 'input' ? parseDef(_def.schema._def, refs, forceResolution) : {}; +} +//# sourceMappingURL=effects.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/effects.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/effects.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..56fa6bbd711dfd2d164309aee6a04bc1747bf180 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/effects.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"effects.mjs","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/effects.ts"],"names":[],"mappings":"OACO,EAAmB,QAAQ,EAAE;AAGpC,MAAM,UAAU,eAAe,CAC7B,IAAmB,EACnB,IAAU,EACV,eAAwB;IAExB,OAAO,IAAI,CAAC,cAAc,KAAK,OAAO,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE,IAAI,EAAE,eAAe,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AAClG,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/enum.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/enum.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..e67e6149ef7c5295267cb4ac25fed882a960b97e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/enum.d.mts @@ -0,0 +1,7 @@ +import { ZodEnumDef } from 'zod'; +export type JsonSchema7EnumType = { + type: 'string'; + enum: string[]; +}; +export declare function parseEnumDef(def: ZodEnumDef): JsonSchema7EnumType; +//# sourceMappingURL=enum.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/enum.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/enum.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..26c3120e51717190059b541a309e1ba34c482f00 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/enum.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"enum.d.mts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/enum.ts"],"names":[],"mappings":"OAAO,EAAE,UAAU,EAAE,MAAM,KAAK;AAEhC,MAAM,MAAM,mBAAmB,GAAG;IAChC,IAAI,EAAE,QAAQ,CAAC;IACf,IAAI,EAAE,MAAM,EAAE,CAAC;CAChB,CAAC;AAEF,wBAAgB,YAAY,CAAC,GAAG,EAAE,UAAU,GAAG,mBAAmB,CAKjE"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/enum.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/enum.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2a9f4f8bd459ba828139c440b22149eb604603cb --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/enum.d.ts @@ -0,0 +1,7 @@ +import { ZodEnumDef } from 'zod'; +export type JsonSchema7EnumType = { + type: 'string'; + enum: string[]; +}; +export declare function parseEnumDef(def: ZodEnumDef): JsonSchema7EnumType; +//# sourceMappingURL=enum.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/enum.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/enum.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..aabfb27158ad618759d6bde2f047436bf8c0a97b --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/enum.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"enum.d.ts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/enum.ts"],"names":[],"mappings":"OAAO,EAAE,UAAU,EAAE,MAAM,KAAK;AAEhC,MAAM,MAAM,mBAAmB,GAAG;IAChC,IAAI,EAAE,QAAQ,CAAC;IACf,IAAI,EAAE,MAAM,EAAE,CAAC;CAChB,CAAC;AAEF,wBAAgB,YAAY,CAAC,GAAG,EAAE,UAAU,GAAG,mBAAmB,CAKjE"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/enum.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/enum.js new file mode 100644 index 0000000000000000000000000000000000000000..45050bfa3fa00756733115c3b2d6bf925f6da132 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/enum.js @@ -0,0 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseEnumDef = parseEnumDef; +function parseEnumDef(def) { + return { + type: 'string', + enum: [...def.values], + }; +} +//# sourceMappingURL=enum.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/enum.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/enum.js.map new file mode 100644 index 0000000000000000000000000000000000000000..76ea8963d72488fa3fc9e755ffe513f8e6a1346c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/enum.js.map @@ -0,0 +1 @@ +{"version":3,"file":"enum.js","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/enum.ts"],"names":[],"mappings":";;AAOA,oCAKC;AALD,SAAgB,YAAY,CAAC,GAAe;IAC1C,OAAO;QACL,IAAI,EAAE,QAAQ;QACd,IAAI,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,CAAC;KACtB,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/enum.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/enum.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7c4dd29c50b4258b24d85abe3966b19688abb33e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/enum.mjs @@ -0,0 +1,7 @@ +export function parseEnumDef(def) { + return { + type: 'string', + enum: [...def.values], + }; +} +//# sourceMappingURL=enum.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/enum.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/enum.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..c0387056f891bde984b3ffd58a1b4cdc8cc1a898 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/enum.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"enum.mjs","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/enum.ts"],"names":[],"mappings":"AAOA,MAAM,UAAU,YAAY,CAAC,GAAe;IAC1C,OAAO;QACL,IAAI,EAAE,QAAQ;QACd,IAAI,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,CAAC;KACtB,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/intersection.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/intersection.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..0fd3a84c489f03121349b946cd37826f02021631 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/intersection.d.mts @@ -0,0 +1,9 @@ +import { ZodIntersectionDef } from 'zod'; +import { JsonSchema7Type } from "../parseDef.mjs"; +import { Refs } from "../Refs.mjs"; +export type JsonSchema7AllOfType = { + allOf: JsonSchema7Type[]; + unevaluatedProperties?: boolean; +}; +export declare function parseIntersectionDef(def: ZodIntersectionDef, refs: Refs): JsonSchema7AllOfType | JsonSchema7Type | undefined; +//# sourceMappingURL=intersection.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/intersection.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/intersection.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..8e2042d461d97f99c67850c7a692168933e9cd7c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/intersection.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"intersection.d.mts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/intersection.ts"],"names":[],"mappings":"OAAO,EAAE,kBAAkB,EAAE,MAAM,KAAK;OACjC,EAAE,eAAe,EAAY;OAC7B,EAAE,IAAI,EAAE;AAGf,MAAM,MAAM,oBAAoB,GAAG;IACjC,KAAK,EAAE,eAAe,EAAE,CAAC;IACzB,qBAAqB,CAAC,EAAE,OAAO,CAAC;CACjC,CAAC;AASF,wBAAgB,oBAAoB,CAClC,GAAG,EAAE,kBAAkB,EACvB,IAAI,EAAE,IAAI,GACT,oBAAoB,GAAG,eAAe,GAAG,SAAS,CA2CpD"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/intersection.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/intersection.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b7be6199c0fc8e5dd6f1c71e946f2d33ab3624ff --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/intersection.d.ts @@ -0,0 +1,9 @@ +import { ZodIntersectionDef } from 'zod'; +import { JsonSchema7Type } from "../parseDef.js"; +import { Refs } from "../Refs.js"; +export type JsonSchema7AllOfType = { + allOf: JsonSchema7Type[]; + unevaluatedProperties?: boolean; +}; +export declare function parseIntersectionDef(def: ZodIntersectionDef, refs: Refs): JsonSchema7AllOfType | JsonSchema7Type | undefined; +//# sourceMappingURL=intersection.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/intersection.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/intersection.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..d05ae0f1dcadb165a13ad22e90d8ef5b4c8b69f4 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/intersection.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"intersection.d.ts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/intersection.ts"],"names":[],"mappings":"OAAO,EAAE,kBAAkB,EAAE,MAAM,KAAK;OACjC,EAAE,eAAe,EAAY;OAC7B,EAAE,IAAI,EAAE;AAGf,MAAM,MAAM,oBAAoB,GAAG;IACjC,KAAK,EAAE,eAAe,EAAE,CAAC;IACzB,qBAAqB,CAAC,EAAE,OAAO,CAAC;CACjC,CAAC;AASF,wBAAgB,oBAAoB,CAClC,GAAG,EAAE,kBAAkB,EACvB,IAAI,EAAE,IAAI,GACT,oBAAoB,GAAG,eAAe,GAAG,SAAS,CA2CpD"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/intersection.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/intersection.js new file mode 100644 index 0000000000000000000000000000000000000000..7bfa6792f92b7343bf78d9d375bd80ce22037693 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/intersection.js @@ -0,0 +1,53 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseIntersectionDef = parseIntersectionDef; +const parseDef_1 = require("../parseDef.js"); +const isJsonSchema7AllOfType = (type) => { + if ('type' in type && type.type === 'string') + return false; + return 'allOf' in type; +}; +function parseIntersectionDef(def, refs) { + const allOf = [ + (0, parseDef_1.parseDef)(def.left._def, { + ...refs, + currentPath: [...refs.currentPath, 'allOf', '0'], + }), + (0, parseDef_1.parseDef)(def.right._def, { + ...refs, + currentPath: [...refs.currentPath, 'allOf', '1'], + }), + ].filter((x) => !!x); + let unevaluatedProperties = refs.target === 'jsonSchema2019-09' ? { unevaluatedProperties: false } : undefined; + const mergedAllOf = []; + // If either of the schemas is an allOf, merge them into a single allOf + allOf.forEach((schema) => { + if (isJsonSchema7AllOfType(schema)) { + mergedAllOf.push(...schema.allOf); + if (schema.unevaluatedProperties === undefined) { + // If one of the schemas has no unevaluatedProperties set, + // the merged schema should also have no unevaluatedProperties set + unevaluatedProperties = undefined; + } + } + else { + let nestedSchema = schema; + if ('additionalProperties' in schema && schema.additionalProperties === false) { + const { additionalProperties, ...rest } = schema; + nestedSchema = rest; + } + else { + // As soon as one of the schemas has additionalProperties set not to false, we allow unevaluatedProperties + unevaluatedProperties = undefined; + } + mergedAllOf.push(nestedSchema); + } + }); + return mergedAllOf.length ? + { + allOf: mergedAllOf, + ...unevaluatedProperties, + } + : undefined; +} +//# sourceMappingURL=intersection.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/intersection.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/intersection.js.map new file mode 100644 index 0000000000000000000000000000000000000000..40b04eeb152b3a2fe962bc67f4dd100c1b5c81c4 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/intersection.js.map @@ -0,0 +1 @@ +{"version":3,"file":"intersection.js","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/intersection.ts"],"names":[],"mappings":";;AAiBA,oDA8CC;AA9DD,6CAAwD;AASxD,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,MAAM,CAAC;YAC3C,IAAI,sBAAsB,IAAI,MAAM,IAAI,MAAM,CAAC,oBAAoB,KAAK,KAAK,EAAE,CAAC;gBAC9E,MAAM,EAAE,oBAAoB,EAAE,GAAG,IAAI,EAAE,GAAG,MAAM,CAAC;gBACjD,YAAY,GAAG,IAAI,CAAC;YACtB,CAAC;iBAAM,CAAC;gBACN,0GAA0G;gBAC1G,qBAAqB,GAAG,SAAS,CAAC;YACpC,CAAC;YACD,WAAW,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;QACjC,CAAC;IACH,CAAC,CAAC,CAAC;IACH,OAAO,WAAW,CAAC,MAAM,CAAC,CAAC;QACvB;YACE,KAAK,EAAE,WAAW;YAClB,GAAG,qBAAqB;SACzB;QACH,CAAC,CAAC,SAAS,CAAC;AAChB,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/intersection.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/intersection.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c11f8390327067d312510e4f2c6652fb57556b0c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/intersection.mjs @@ -0,0 +1,50 @@ +import { parseDef } from "../parseDef.mjs"; +const isJsonSchema7AllOfType = (type) => { + if ('type' in type && type.type === 'string') + return false; + return 'allOf' in type; +}; +export function parseIntersectionDef(def, refs) { + const allOf = [ + parseDef(def.left._def, { + ...refs, + currentPath: [...refs.currentPath, 'allOf', '0'], + }), + parseDef(def.right._def, { + ...refs, + currentPath: [...refs.currentPath, 'allOf', '1'], + }), + ].filter((x) => !!x); + let unevaluatedProperties = refs.target === 'jsonSchema2019-09' ? { unevaluatedProperties: false } : undefined; + const mergedAllOf = []; + // If either of the schemas is an allOf, merge them into a single allOf + allOf.forEach((schema) => { + if (isJsonSchema7AllOfType(schema)) { + mergedAllOf.push(...schema.allOf); + if (schema.unevaluatedProperties === undefined) { + // If one of the schemas has no unevaluatedProperties set, + // the merged schema should also have no unevaluatedProperties set + unevaluatedProperties = undefined; + } + } + else { + let nestedSchema = schema; + if ('additionalProperties' in schema && schema.additionalProperties === false) { + const { additionalProperties, ...rest } = schema; + nestedSchema = rest; + } + else { + // As soon as one of the schemas has additionalProperties set not to false, we allow unevaluatedProperties + unevaluatedProperties = undefined; + } + mergedAllOf.push(nestedSchema); + } + }); + return mergedAllOf.length ? + { + allOf: mergedAllOf, + ...unevaluatedProperties, + } + : undefined; +} +//# sourceMappingURL=intersection.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/intersection.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/intersection.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..b2586b1ce616bf9285d2c18cf33bd6cffba87573 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/intersection.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"intersection.mjs","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/intersection.ts"],"names":[],"mappings":"OACO,EAAmB,QAAQ,EAAE;AASpC,MAAM,sBAAsB,GAAG,CAC7B,IAA6C,EACf,EAAE;IAChC,IAAI,MAAM,IAAI,IAAI,IAAI,IAAI,CAAC,IAAI,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IAC3D,OAAO,OAAO,IAAI,IAAI,CAAC;AACzB,CAAC,CAAC;AAEF,MAAM,UAAU,oBAAoB,CAClC,GAAuB,EACvB,IAAU;IAEV,MAAM,KAAK,GAAG;QACZ,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE;YACtB,GAAG,IAAI;YACP,WAAW,EAAE,CAAC,GAAG,IAAI,CAAC,WAAW,EAAE,OAAO,EAAE,GAAG,CAAC;S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E,WAAW;YAClB,GAAG,qBAAqB;SACzB;QACH,CAAC,CAAC,SAAS,CAAC;AAChB,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/literal.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/literal.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..70ee430a6c93641e7ec095795bb2bdbfaaff1cff --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/literal.d.mts @@ -0,0 +1,10 @@ +import { ZodLiteralDef } from 'zod'; +import { Refs } from "../Refs.mjs"; +export type JsonSchema7LiteralType = { + type: 'string' | 'number' | 'integer' | 'boolean'; + const: string | number | boolean; +} | { + type: 'object' | 'array'; +}; +export declare function parseLiteralDef(def: ZodLiteralDef, refs: Refs): JsonSchema7LiteralType; +//# sourceMappingURL=literal.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/literal.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/literal.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..793c0f544544943dc497633824253a8a1c174ddd --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/literal.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"literal.d.mts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/literal.ts"],"names":[],"mappings":"OAAO,EAAE,aAAa,EAAE,MAAM,KAAK;OAC5B,EAAE,IAAI,EAAE;AAEf,MAAM,MAAM,sBAAsB,GAC9B;IACE,IAAI,EAAE,QAAQ,GAAG,QAAQ,GAAG,SAAS,GAAG,SAAS,CAAC;IAClD,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC;CAClC,GACD;IACE,IAAI,EAAE,QAAQ,GAAG,OAAO,CAAC;CAC1B,CAAC;AAEN,wBAAgB,eAAe,CAAC,GAAG,EAAE,aAAa,EAAE,IAAI,EAAE,IAAI,GAAG,sBAAsB,CAwBtF"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/literal.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/literal.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..36b539e5bb9caf466aef3623ec57eec4f2f86a13 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/literal.d.ts @@ -0,0 +1,10 @@ +import { ZodLiteralDef } from 'zod'; +import { Refs } from "../Refs.js"; +export type JsonSchema7LiteralType = { + type: 'string' | 'number' | 'integer' | 'boolean'; + const: string | number | boolean; +} | { + type: 'object' | 'array'; +}; +export declare function parseLiteralDef(def: ZodLiteralDef, refs: Refs): JsonSchema7LiteralType; +//# sourceMappingURL=literal.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/literal.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/literal.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..6a2ada4116b884daa393b7ad4dcccb71447b1d92 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/literal.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"literal.d.ts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/literal.ts"],"names":[],"mappings":"OAAO,EAAE,aAAa,EAAE,MAAM,KAAK;OAC5B,EAAE,IAAI,EAAE;AAEf,MAAM,MAAM,sBAAsB,GAC9B;IACE,IAAI,EAAE,QAAQ,GAAG,QAAQ,GAAG,SAAS,GAAG,SAAS,CAAC;IAClD,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC;CAClC,GACD;IACE,IAAI,EAAE,QAAQ,GAAG,OAAO,CAAC;CAC1B,CAAC;AAEN,wBAAgB,eAAe,CAAC,GAAG,EAAE,aAAa,EAAE,IAAI,EAAE,IAAI,GAAG,sBAAsB,CAwBtF"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/literal.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/literal.js new file mode 100644 index 0000000000000000000000000000000000000000..4c9139d5dc849485959c9b130a833477bbbf9a58 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/literal.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseLiteralDef = parseLiteralDef; +function parseLiteralDef(def, refs) { + const parsedType = typeof def.value; + if (parsedType !== 'bigint' && + parsedType !== 'number' && + parsedType !== 'boolean' && + parsedType !== 'string') { + return { + type: Array.isArray(def.value) ? 'array' : 'object', + }; + } + if (refs.target === 'openApi3') { + return { + type: parsedType === 'bigint' ? 'integer' : parsedType, + enum: [def.value], + }; + } + return { + type: parsedType === 'bigint' ? 'integer' : parsedType, + const: def.value, + }; +} +//# sourceMappingURL=literal.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/literal.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/literal.js.map new file mode 100644 index 0000000000000000000000000000000000000000..4e2ed712a7cd8f22c6fd024aa9df3ccaeb523e2d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/literal.js.map @@ -0,0 +1 @@ +{"version":3,"file":"literal.js","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/literal.ts"],"names":[],"mappings":";;AAYA,0CAwBC;AAxBD,SAAgB,eAAe,CAAC,GAAkB,EAAE,IAAU;IAC5D,MAAM,UAAU,GAAG,OAAO,GAAG,CAAC,KAAK,CAAC;IACpC,IACE,UAAU,KAAK,QAAQ;QACvB,UAAU,KAAK,QAAQ;QACvB,UAAU,KAAK,SAAS;QACxB,UAAU,KAAK,QAAQ,EACvB,CAAC;QACD,OAAO;YACL,IAAI,EAAE,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,QAAQ;SACpD,CAAC;IACJ,CAAC;IAED,IAAI,IAAI,CAAC,MAAM,KAAK,UAAU,EAAE,CAAC;QAC/B,OAAO;YACL,IAAI,EAAE,UAAU,KAAK,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,UAAU;YACtD,IAAI,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC;SACX,CAAC;IACX,CAAC;IAED,OAAO;QACL,IAAI,EAAE,UAAU,KAAK,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,UAAU;QACtD,KAAK,EAAE,GAAG,CAAC,KAAK;KACjB,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/literal.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/literal.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a8519728b35a07c8cdaf9cb46ddc1ae300c2f1f0 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/literal.mjs @@ -0,0 +1,22 @@ +export function parseLiteralDef(def, refs) { + const parsedType = typeof def.value; + if (parsedType !== 'bigint' && + parsedType !== 'number' && + parsedType !== 'boolean' && + parsedType !== 'string') { + return { + type: Array.isArray(def.value) ? 'array' : 'object', + }; + } + if (refs.target === 'openApi3') { + return { + type: parsedType === 'bigint' ? 'integer' : parsedType, + enum: [def.value], + }; + } + return { + type: parsedType === 'bigint' ? 'integer' : parsedType, + const: def.value, + }; +} +//# sourceMappingURL=literal.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/literal.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/literal.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..7d4f4f5266701fe3ad3ef0f84f98c0c3bf995347 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/literal.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"literal.mjs","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/literal.ts"],"names":[],"mappings":"AAYA,MAAM,UAAU,eAAe,CAAC,GAAkB,EAAE,IAAU;IAC5D,MAAM,UAAU,GAAG,OAAO,GAAG,CAAC,KAAK,CAAC;IACpC,IACE,UAAU,KAAK,QAAQ;QACvB,UAAU,KAAK,QAAQ;QACvB,UAAU,KAAK,SAAS;QACxB,UAAU,KAAK,QAAQ,EACvB,CAAC;QACD,OAAO;YACL,IAAI,EAAE,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,QAAQ;SACpD,CAAC;IACJ,CAAC;IAED,IAAI,IAAI,CAAC,MAAM,KAAK,UAAU,EAAE,CAAC;QAC/B,OAAO;YACL,IAAI,EAAE,UAAU,KAAK,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,UAAU;YACtD,IAAI,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC;SACX,CAAC;IACX,CAAC;IAED,OAAO;QACL,IAAI,EAAE,UAAU,KAAK,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,UAAU;QACtD,KAAK,EAAE,GAAG,CAAC,KAAK;KACjB,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/map.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/map.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..272f293e548ccc546b2a8ac8b049f998a19bc939 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/map.d.mts @@ -0,0 +1,16 @@ +import { ZodMapDef } from 'zod'; +import { JsonSchema7Type } from "../parseDef.mjs"; +import { Refs } from "../Refs.mjs"; +import { JsonSchema7RecordType } from "./record.mjs"; +export type JsonSchema7MapType = { + type: 'array'; + maxItems: 125; + items: { + type: 'array'; + items: [JsonSchema7Type, JsonSchema7Type]; + minItems: 2; + maxItems: 2; + }; +}; +export declare function parseMapDef(def: ZodMapDef, refs: Refs): JsonSchema7MapType | JsonSchema7RecordType; +//# sourceMappingURL=map.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/map.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/map.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..3176b4762db939eaafec9ad70521a9dceca1c428 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/map.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"map.d.mts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/map.ts"],"names":[],"mappings":"OAAO,EAAE,SAAS,EAAE,MAAM,KAAK;OACxB,EAAE,eAAe,EAAY;OAC7B,EAAE,IAAI,EAAE;OACR,EAAE,qBAAqB,EAAkB;AAEhD,MAAM,MAAM,kBAAkB,GAAG;IAC/B,IAAI,EAAE,OAAO,CAAC;IACd,QAAQ,EAAE,GAAG,CAAC;IACd,KAAK,EAAE;QACL,IAAI,EAAE,OAAO,CAAC;QACd,KAAK,EAAE,CAAC,eAAe,EAAE,eAAe,CAAC,CAAC;QAC1C,QAAQ,EAAE,CAAC,CAAC;QACZ,QAAQ,EAAE,CAAC,CAAC;KACb,CAAC;CACH,CAAC;AAEF,wBAAgB,WAAW,CAAC,GAAG,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,GAAG,kBAAkB,GAAG,qBAAqB,CAyBlG"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/map.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/map.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3016f892d1b76edc40347824097d81f98704f9a4 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/map.d.ts @@ -0,0 +1,16 @@ +import { ZodMapDef } from 'zod'; +import { JsonSchema7Type } from "../parseDef.js"; +import { Refs } from "../Refs.js"; +import { JsonSchema7RecordType } from "./record.js"; +export type JsonSchema7MapType = { + type: 'array'; + maxItems: 125; + items: { + type: 'array'; + items: [JsonSchema7Type, JsonSchema7Type]; + minItems: 2; + maxItems: 2; + }; +}; +export declare function parseMapDef(def: ZodMapDef, refs: Refs): JsonSchema7MapType | JsonSchema7RecordType; +//# sourceMappingURL=map.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/map.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/map.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..1bf2b0b70e7704be03cc04ef32c6187e70915104 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/map.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"map.d.ts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/map.ts"],"names":[],"mappings":"OAAO,EAAE,SAAS,EAAE,MAAM,KAAK;OACxB,EAAE,eAAe,EAAY;OAC7B,EAAE,IAAI,EAAE;OACR,EAAE,qBAAqB,EAAkB;AAEhD,MAAM,MAAM,kBAAkB,GAAG;IAC/B,IAAI,EAAE,OAAO,CAAC;IACd,QAAQ,EAAE,GAAG,CAAC;IACd,KAAK,EAAE;QACL,IAAI,EAAE,OAAO,CAAC;QACd,KAAK,EAAE,CAAC,eAAe,EAAE,eAAe,CAAC,CAAC;QAC1C,QAAQ,EAAE,CAAC,CAAC;QACZ,QAAQ,EAAE,CAAC,CAAC;KACb,CAAC;CACH,CAAC;AAEF,wBAAgB,WAAW,CAAC,GAAG,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,GAAG,kBAAkB,GAAG,qBAAqB,CAyBlG"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/map.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/map.js new file mode 100644 index 0000000000000000000000000000000000000000..9e29637fe2a68690c1ce4cf046cbc9c3c5686eec --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/map.js @@ -0,0 +1,29 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseMapDef = parseMapDef; +const parseDef_1 = require("../parseDef.js"); +const record_1 = require("./record.js"); +function parseMapDef(def, refs) { + if (refs.mapStrategy === 'record') { + return (0, record_1.parseRecordDef)(def, refs); + } + const keys = (0, parseDef_1.parseDef)(def.keyType._def, { + ...refs, + currentPath: [...refs.currentPath, 'items', 'items', '0'], + }) || {}; + const values = (0, parseDef_1.parseDef)(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, 'items', 'items', '1'], + }) || {}; + return { + type: 'array', + maxItems: 125, + items: { + type: 'array', + items: [keys, values], + minItems: 2, + maxItems: 2, + }, + }; +} +//# sourceMappingURL=map.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/map.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/map.js.map new file mode 100644 index 0000000000000000000000000000000000000000..6dbba062fbce6211a441208c83846ab445f6f514 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/map.js.map @@ -0,0 +1 @@ +{"version":3,"file":"map.js","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/map.ts"],"names":[],"mappings":";;AAgBA,kCAyBC;AAxCD,6CAAwD;AAExD,wCAAiE;AAajE,SAAgB,WAAW,CAAC,GAAc,EAAE,IAAU;IACpD,IAAI,IAAI,CAAC,WAAW,KAAK,QAAQ,EAAE,CAAC;QAClC,OAAO,IAAA,uBAAc,EAAC,GAAG,EAAE,IAAI,CAAC,CAAC;IACnC,CAAC;IAED,MAAM,IAAI,GACR,IAAA,mBAAQ,EAAC,GAAG,CAAC,OAAO,CAAC,IAAI,EAAE;QACzB,GAAG,IAAI;QACP,WAAW,EAAE,CAAC,GAAG,IAAI,CAAC,WAAW,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,CAAC;KAC1D,CAAC,IAAI,EAAE,CAAC;IACX,MAAM,MAAM,GACV,IAAA,mBAAQ,EAAC,GAAG,CAAC,SAAS,CAAC,IAAI,EAAE;QAC3B,GAAG,IAAI;QACP,WAAW,EAAE,CAAC,GAAG,IAAI,CAAC,WAAW,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,CAAC;KAC1D,CAAC,IAAI,EAAE,CAAC;IACX,OAAO;QACL,IAAI,EAAE,OAAO;QACb,QAAQ,EAAE,GAAG;QACb,KAAK,EAAE;YACL,IAAI,EAAE,OAAO;YACb,KAAK,EAAE,CAAC,IAAI,EAAE,MAAM,CAAC;YACrB,QAAQ,EAAE,CAAC;YACX,QAAQ,EAAE,CAAC;SACZ;KACF,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/map.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/map.mjs new file mode 100644 index 0000000000000000000000000000000000000000..428849e5849079bbd4355fd754d9aa613fe30670 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/map.mjs @@ -0,0 +1,26 @@ +import { parseDef } from "../parseDef.mjs"; +import { parseRecordDef } from "./record.mjs"; +export function parseMapDef(def, refs) { + if (refs.mapStrategy === 'record') { + return parseRecordDef(def, refs); + } + const keys = parseDef(def.keyType._def, { + ...refs, + currentPath: [...refs.currentPath, 'items', 'items', '0'], + }) || {}; + const values = parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, 'items', 'items', '1'], + }) || {}; + return { + type: 'array', + maxItems: 125, + items: { + type: 'array', + items: [keys, values], + minItems: 2, + maxItems: 2, + }, + }; +} +//# sourceMappingURL=map.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/map.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/map.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..a613e7d76bde51ae9904fdb4c2768d1b23d86b77 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/map.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"map.mjs","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/map.ts"],"names":[],"mappings":"OACO,EAAmB,QAAQ,EAAE;OAE7B,EAAyB,cAAc,EAAE;AAahD,MAAM,UAAU,WAAW,CAAC,GAAc,EAAE,IAAU;IACpD,IAAI,IAAI,CAAC,WAAW,KAAK,QAAQ,EAAE,CAAC;QAClC,OAAO,cAAc,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;IACnC,CAAC;IAED,MAAM,IAAI,GACR,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,IAAI,EAAE;QACzB,GAAG,IAAI;QACP,WAAW,EAAE,CAAC,GAAG,IAAI,CAAC,WAAW,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,CAAC;KAC1D,CAAC,IAAI,EAAE,CAAC;IACX,MAAM,MAAM,GACV,QAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,EAAE;QAC3B,GAAG,IAAI;QACP,WAAW,EAAE,CAAC,GAAG,IAAI,CAAC,WAAW,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,CAAC;KAC1D,CAAC,IAAI,EAAE,CAAC;IACX,OAAO;QACL,IAAI,EAAE,OAAO;QACb,QAAQ,EAAE,GAAG;QACb,KAAK,EAAE;YACL,IAAI,EAAE,OAAO;YACb,KAAK,EAAE,CAAC,IAAI,EAAE,MAAM,CAAC;YACrB,QAAQ,EAAE,CAAC;YACX,QAAQ,EAAE,CAAC;SACZ;KACF,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nativeEnum.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nativeEnum.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..5c83d3c442ddb6c1e179a29464cb49c53f18ebdf --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nativeEnum.d.mts @@ -0,0 +1,7 @@ +import { ZodNativeEnumDef } from 'zod'; +export type JsonSchema7NativeEnumType = { + type: 'string' | 'number' | ['string', 'number']; + enum: (string | number)[]; +}; +export declare function parseNativeEnumDef(def: ZodNativeEnumDef): JsonSchema7NativeEnumType; +//# sourceMappingURL=nativeEnum.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nativeEnum.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nativeEnum.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..6d04fb0b343441c88946ae23afcb3158e50d80b7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nativeEnum.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"nativeEnum.d.mts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/nativeEnum.ts"],"names":[],"mappings":"OAAO,EAAE,gBAAgB,EAAE,MAAM,KAAK;AAEtC,MAAM,MAAM,yBAAyB,GAAG;IACtC,IAAI,EAAE,QAAQ,GAAG,QAAQ,GAAG,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;IACjD,IAAI,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,CAAC;CAC3B,CAAC;AAEF,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,gBAAgB,GAAG,yBAAyB,CAmBnF"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nativeEnum.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nativeEnum.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..43cf2e2f32f6137dff6990dc73f6678701537061 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nativeEnum.d.ts @@ -0,0 +1,7 @@ +import { ZodNativeEnumDef } from 'zod'; +export type JsonSchema7NativeEnumType = { + type: 'string' | 'number' | ['string', 'number']; + enum: (string | number)[]; +}; +export declare function parseNativeEnumDef(def: ZodNativeEnumDef): JsonSchema7NativeEnumType; +//# sourceMappingURL=nativeEnum.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nativeEnum.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nativeEnum.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..48dd6585bd81f4d8a784a50af64105615a51359e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nativeEnum.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"nativeEnum.d.ts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/nativeEnum.ts"],"names":[],"mappings":"OAAO,EAAE,gBAAgB,EAAE,MAAM,KAAK;AAEtC,MAAM,MAAM,yBAAyB,GAAG;IACtC,IAAI,EAAE,QAAQ,GAAG,QAAQ,GAAG,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;IACjD,IAAI,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,CAAC;CAC3B,CAAC;AAEF,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,gBAAgB,GAAG,yBAAyB,CAmBnF"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nativeEnum.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nativeEnum.js new file mode 100644 index 0000000000000000000000000000000000000000..b9041708bf22260433a654254485d3c9a968546c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nativeEnum.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseNativeEnumDef = parseNativeEnumDef; +function parseNativeEnumDef(def) { + const object = def.values; + const actualKeys = Object.keys(def.values).filter((key) => { + return typeof object[object[key]] !== 'number'; + }); + const actualValues = actualKeys.map((key) => object[key]); + const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values))); + return { + type: parsedTypes.length === 1 ? + parsedTypes[0] === 'string' ? + 'string' + : 'number' + : ['string', 'number'], + enum: actualValues, + }; +} +//# sourceMappingURL=nativeEnum.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nativeEnum.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nativeEnum.js.map new file mode 100644 index 0000000000000000000000000000000000000000..069631d58fe4f3053da3ebfcfbccbc0dc0429df7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nativeEnum.js.map @@ -0,0 +1 @@ +{"version":3,"file":"nativeEnum.js","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/nativeEnum.ts"],"names":[],"mappings":";;AAOA,gDAmBC;AAnBD,SAAgB,kBAAkB,CAAC,GAAqB;IACtD,MAAM,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC;IAC1B,MAAM,UAAU,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,CAAC,GAAW,EAAE,EAAE;QAChE,OAAO,OAAO,MAAM,CAAC,MAAM,CAAC,GAAG,CAAE,CAAC,KAAK,QAAQ,CAAC;IAClD,CAAC,CAAC,CAAC;IAEH,MAAM,YAAY,GAAG,UAAU,CAAC,GAAG,CAAC,CAAC,GAAW,EAAE,EAAE,CAAC,MAAM,CAAC,GAAG,CAAE,CAAC,CAAC;IAEnE,MAAM,WAAW,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC,MAAuB,EAAE,EAAE,CAAC,OAAO,MAAM,CAAC,CAAC,CAAC,CAAC;IAEtG,OAAO;QACL,IAAI,EACF,WAAW,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC;YACxB,WAAW,CAAC,CAAC,CAAC,KAAK,QAAQ,CAAC,CAAC;gBAC3B,QAAQ;gBACV,CAAC,CAAC,QAAQ;YACZ,CAAC,CAAC,CAAC,QAAQ,EAAE,QAAQ,CAAC;QACxB,IAAI,EAAE,YAAY;KACnB,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nativeEnum.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nativeEnum.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6e1a0acb01197fa90cbbc711806ab320070502ec --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nativeEnum.mjs @@ -0,0 +1,17 @@ +export function parseNativeEnumDef(def) { + const object = def.values; + const actualKeys = Object.keys(def.values).filter((key) => { + return typeof object[object[key]] !== 'number'; + }); + const actualValues = actualKeys.map((key) => object[key]); + const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values))); + return { + type: parsedTypes.length === 1 ? + parsedTypes[0] === 'string' ? + 'string' + : 'number' + : ['string', 'number'], + enum: actualValues, + }; +} +//# sourceMappingURL=nativeEnum.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nativeEnum.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nativeEnum.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..34d5262d00c701281c05984ac9d8c85164cb5835 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nativeEnum.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"nativeEnum.mjs","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/nativeEnum.ts"],"names":[],"mappings":"AAOA,MAAM,UAAU,kBAAkB,CAAC,GAAqB;IACtD,MAAM,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC;IAC1B,MAAM,UAAU,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,CAAC,GAAW,EAAE,EAAE;QAChE,OAAO,OAAO,MAAM,CAAC,MAAM,CAAC,GAAG,CAAE,CAAC,KAAK,QAAQ,CAAC;IAClD,CAAC,CAAC,CAAC;IAEH,MAAM,YAAY,GAAG,UAAU,CAAC,GAAG,CAAC,CAAC,GAAW,EAAE,EAAE,CAAC,MAAM,CAAC,GAAG,CAAE,CAAC,CAAC;IAEnE,MAAM,WAAW,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC,MAAuB,EAAE,EAAE,CAAC,OAAO,MAAM,CAAC,CAAC,CAAC,CAAC;IAEtG,OAAO;QACL,IAAI,EACF,WAAW,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC;YACxB,WAAW,CAAC,CAAC,CAAC,KAAK,QAAQ,CAAC,CAAC;gBAC3B,QAAQ;gBACV,CAAC,CAAC,QAAQ;YACZ,CAAC,CAAC,CAAC,QAAQ,EAAE,QAAQ,CAAC;QACxB,IAAI,EAAE,YAAY;KACnB,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/never.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/never.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..215eebf5b0a899205e26be1f5a13474166f69aa8 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/never.d.mts @@ -0,0 +1,5 @@ +export type JsonSchema7NeverType = { + not: {}; +}; +export declare function parseNeverDef(): JsonSchema7NeverType; +//# sourceMappingURL=never.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/never.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/never.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..98671e8fc860b6f61683004303f837a4d1218988 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/never.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"never.d.mts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/never.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,oBAAoB,GAAG;IACjC,GAAG,EAAE,EAAE,CAAC;CACT,CAAC;AAEF,wBAAgB,aAAa,IAAI,oBAAoB,CAIpD"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/never.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/never.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d56edd087a97e7ba8b8c442c2fde8129b6c07d40 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/never.d.ts @@ -0,0 +1,5 @@ +export type JsonSchema7NeverType = { + not: {}; +}; +export declare function parseNeverDef(): JsonSchema7NeverType; +//# sourceMappingURL=never.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/never.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/never.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..0bc5ba2d7321ec5d1ae8d2b846f82b328341aac7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/never.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"never.d.ts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/never.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,oBAAoB,GAAG;IACjC,GAAG,EAAE,EAAE,CAAC;CACT,CAAC;AAEF,wBAAgB,aAAa,IAAI,oBAAoB,CAIpD"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/never.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/never.js new file mode 100644 index 0000000000000000000000000000000000000000..5c95153bce6607eabcad89606ea04491396e6813 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/never.js @@ -0,0 +1,9 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseNeverDef = parseNeverDef; +function parseNeverDef() { + return { + not: {}, + }; +} +//# sourceMappingURL=never.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/never.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/never.js.map new file mode 100644 index 0000000000000000000000000000000000000000..84488c9e7bac1f91fbf8d549aa7ba54610806173 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/never.js.map @@ -0,0 +1 @@ +{"version":3,"file":"never.js","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/never.ts"],"names":[],"mappings":";;AAIA,sCAIC;AAJD,SAAgB,aAAa;IAC3B,OAAO;QACL,GAAG,EAAE,EAAE;KACR,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/never.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/never.mjs new file mode 100644 index 0000000000000000000000000000000000000000..dd877d7f7c447e9f312423ddb6244bb7c0257ad1 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/never.mjs @@ -0,0 +1,6 @@ +export function parseNeverDef() { + return { + not: {}, + }; +} +//# sourceMappingURL=never.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/never.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/never.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..2a7ca45740575823876e2c2bdfcf8be7c9ff9dd7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/never.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"never.mjs","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/never.ts"],"names":[],"mappings":"AAIA,MAAM,UAAU,aAAa;IAC3B,OAAO;QACL,GAAG,EAAE,EAAE;KACR,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/null.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/null.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..9a84b681a3edc749ede5671b475c2cc5aeea3899 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/null.d.mts @@ -0,0 +1,6 @@ +import { Refs } from "../Refs.mjs"; +export type JsonSchema7NullType = { + type: 'null'; +}; +export declare function parseNullDef(refs: Refs): JsonSchema7NullType; +//# sourceMappingURL=null.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/null.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/null.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..b35b37ff96647f43e8cbf65dda3ba1bd52781b7d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/null.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"null.d.mts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/null.ts"],"names":[],"mappings":"OAAO,EAAE,IAAI,EAAE;AAEf,MAAM,MAAM,mBAAmB,GAAG;IAChC,IAAI,EAAE,MAAM,CAAC;CACd,CAAC;AAEF,wBAAgB,YAAY,CAAC,IAAI,EAAE,IAAI,GAAG,mBAAmB,CAS5D"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/null.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/null.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b2b993deacb54db898eb465bef711786861c8753 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/null.d.ts @@ -0,0 +1,6 @@ +import { Refs } from "../Refs.js"; +export type JsonSchema7NullType = { + type: 'null'; +}; +export declare function parseNullDef(refs: Refs): JsonSchema7NullType; +//# sourceMappingURL=null.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/null.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/null.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..849537ec9e35bcceba3078cd50d389a8e6100380 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/null.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"null.d.ts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/null.ts"],"names":[],"mappings":"OAAO,EAAE,IAAI,EAAE;AAEf,MAAM,MAAM,mBAAmB,GAAG;IAChC,IAAI,EAAE,MAAM,CAAC;CACd,CAAC;AAEF,wBAAgB,YAAY,CAAC,IAAI,EAAE,IAAI,GAAG,mBAAmB,CAS5D"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/null.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/null.js new file mode 100644 index 0000000000000000000000000000000000000000..156354fce32c5cab501c4acb82b2c8bbc8674be8 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/null.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseNullDef = parseNullDef; +function parseNullDef(refs) { + return refs.target === 'openApi3' ? + { + enum: ['null'], + nullable: true, + } + : { + type: 'null', + }; +} +//# sourceMappingURL=null.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/null.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/null.js.map new file mode 100644 index 0000000000000000000000000000000000000000..96e1ebb3b56ed8b9c12b36a96c60b0528b343217 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/null.js.map @@ -0,0 +1 @@ +{"version":3,"file":"null.js","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/null.ts"],"names":[],"mappings":";;AAMA,oCASC;AATD,SAAgB,YAAY,CAAC,IAAU;IACrC,OAAO,IAAI,CAAC,MAAM,KAAK,UAAU,CAAC,CAAC;QAC9B;YACC,IAAI,EAAE,CAAC,MAAM,CAAC;YACd,QAAQ,EAAE,IAAI;SACP;QACX,CAAC,CAAC;YACE,IAAI,EAAE,MAAM;SACb,CAAC;AACR,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/null.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/null.mjs new file mode 100644 index 0000000000000000000000000000000000000000..cd8ce3b91abdeb50ba3d7a6461ebbd0404d14205 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/null.mjs @@ -0,0 +1,11 @@ +export function parseNullDef(refs) { + return refs.target === 'openApi3' ? + { + enum: ['null'], + nullable: true, + } + : { + type: 'null', + }; +} +//# sourceMappingURL=null.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/null.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/null.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..d67be9c9f0ec355b885ac8a39e7ba1d846ca934d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/null.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"null.mjs","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/null.ts"],"names":[],"mappings":"AAMA,MAAM,UAAU,YAAY,CAAC,IAAU;IACrC,OAAO,IAAI,CAAC,MAAM,KAAK,UAAU,CAAC,CAAC;QAC9B;YACC,IAAI,EAAE,CAAC,MAAM,CAAC;YACd,QAAQ,EAAE,IAAI;SACP;QACX,CAAC,CAAC;YACE,IAAI,EAAE,MAAM;SACb,CAAC;AACR,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nullable.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nullable.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..1bc1b939a0666773418aff8a250848fc022cd242 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nullable.d.mts @@ -0,0 +1,11 @@ +import { ZodNullableDef } from 'zod'; +import { JsonSchema7Type } from "../parseDef.mjs"; +import { Refs } from "../Refs.mjs"; +import { JsonSchema7NullType } from "./null.mjs"; +export type JsonSchema7NullableType = { + anyOf: [JsonSchema7Type, JsonSchema7NullType]; +} | { + type: [string, 'null']; +}; +export declare function parseNullableDef(def: ZodNullableDef, refs: Refs): JsonSchema7NullableType | undefined; +//# sourceMappingURL=nullable.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nullable.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nullable.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..085cd2b85b4a630e08c1248a42cb5e44eed46fb9 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nullable.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"nullable.d.mts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/nullable.ts"],"names":[],"mappings":"OAAO,EAAE,cAAc,EAAE,MAAM,KAAK;OAC7B,EAAE,eAAe,EAAY;OAC7B,EAAE,IAAI,EAAE;OACR,EAAE,mBAAmB,EAAE;AAG9B,MAAM,MAAM,uBAAuB,GAC/B;IACE,KAAK,EAAE,CAAC,eAAe,EAAE,mBAAmB,CAAC,CAAC;CAC/C,GACD;IACE,IAAI,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACxB,CAAC;AAEN,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,cAAc,EAAE,IAAI,EAAE,IAAI,GAAG,uBAAuB,GAAG,SAAS,CAkCrG"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nullable.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nullable.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..40292b852347a96df7e8da28c303500032f98558 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nullable.d.ts @@ -0,0 +1,11 @@ +import { ZodNullableDef } from 'zod'; +import { JsonSchema7Type } from "../parseDef.js"; +import { Refs } from "../Refs.js"; +import { JsonSchema7NullType } from "./null.js"; +export type JsonSchema7NullableType = { + anyOf: [JsonSchema7Type, JsonSchema7NullType]; +} | { + type: [string, 'null']; +}; +export declare function parseNullableDef(def: ZodNullableDef, refs: Refs): JsonSchema7NullableType | undefined; +//# sourceMappingURL=nullable.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nullable.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nullable.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..338eb493aeb79e7c4333b89bfe921cdc5365f8f2 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nullable.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"nullable.d.ts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/nullable.ts"],"names":[],"mappings":"OAAO,EAAE,cAAc,EAAE,MAAM,KAAK;OAC7B,EAAE,eAAe,EAAY;OAC7B,EAAE,IAAI,EAAE;OACR,EAAE,mBAAmB,EAAE;AAG9B,MAAM,MAAM,uBAAuB,GAC/B;IACE,KAAK,EAAE,CAAC,eAAe,EAAE,mBAAmB,CAAC,CAAC;CAC/C,GACD;IACE,IAAI,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACxB,CAAC;AAEN,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,cAAc,EAAE,IAAI,EAAE,IAAI,GAAG,uBAAuB,GAAG,SAAS,CAkCrG"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nullable.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nullable.js new file mode 100644 index 0000000000000000000000000000000000000000..d84f6f6d6e264dcf87ffd1a4f14c6f88f5d7c2ff --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nullable.js @@ -0,0 +1,34 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseNullableDef = parseNullableDef; +const parseDef_1 = require("../parseDef.js"); +const union_1 = require("./union.js"); +function parseNullableDef(def, refs) { + if (['ZodString', 'ZodNumber', 'ZodBigInt', 'ZodBoolean', 'ZodNull'].includes(def.innerType._def.typeName) && + (!def.innerType._def.checks || !def.innerType._def.checks.length)) { + if (refs.target === 'openApi3' || refs.nullableStrategy === 'property') { + return { + type: union_1.primitiveMappings[def.innerType._def.typeName], + nullable: true, + }; + } + return { + type: [union_1.primitiveMappings[def.innerType._def.typeName], 'null'], + }; + } + if (refs.target === 'openApi3') { + const base = (0, parseDef_1.parseDef)(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath], + }); + if (base && '$ref' in base) + return { allOf: [base], nullable: true }; + return base && { ...base, nullable: true }; + } + const base = (0, parseDef_1.parseDef)(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath, 'anyOf', '0'], + }); + return base && { anyOf: [base, { type: 'null' }] }; +} +//# sourceMappingURL=nullable.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nullable.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nullable.js.map new file mode 100644 index 0000000000000000000000000000000000000000..bd855d3e187a126f53ee78a032fc89972f216c20 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nullable.js.map @@ -0,0 +1 @@ +{"version":3,"file":"nullable.js","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/nullable.ts"],"names":[],"mappings":";;AAcA,4CAkCC;AA/CD,6CAAwD;AAGxD,sCAA4C;AAU5C,SAAgB,gBAAgB,CAAC,GAAmB,EAAE,IAAU;IAC9D,IACE,CAAC,WAAW,EAAE,WAAW,EAAE,WAAW,EAAE,YAAY,EAAE,SAAS,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,CAAC,QAAQ,CAAC;QACtG,CAAC,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,CAAC,MAAM,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,EACjE,CAAC;QACD,IAAI,IAAI,CAAC,MAAM,KAAK,UAAU,IAAI,IAAI,CAAC,gBAAgB,KAAK,UAAU,EAAE,CAAC;YACvE,OAAO;gBACL,IAAI,EAAE,yBAAiB,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,CAAC,QAA0C,CAAC;gBACtF,QAAQ,EAAE,IAAI;aACR,CAAC;QACX,CAAC;QAED,OAAO;YACL,IAAI,EAAE,CAAC,yBAAiB,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,CAAC,QAA0C,CAAC,EAAE,MAAM,CAAC;SACjG,CAAC;IACJ,CAAC;IAED,IAAI,IAAI,CAAC,MAAM,KAAK,UAAU,EAAE,CAAC;QAC/B,MAAM,IAAI,GAAG,IAAA,mBAAQ,EAAC,GAAG,CAAC,SAAS,CAAC,IAAI,EAAE;YACxC,GAAG,IAAI;YACP,WAAW,EAAE,CAAC,GAAG,IAAI,CAAC,WAAW,CAAC;SACnC,CAAC,CAAC;QAEH,IAAI,IAAI,IAAI,MAAM,IAAI,IAAI;YAAE,OAAO,EAAE,KAAK,EAAE,CAAC,IAAI,CAAC,EAAE,QAAQ,EAAE,IAAI,EAAS,CAAC;QAE5E,OAAO,IAAI,IAAK,EAAE,GAAG,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAU,CAAC;IACtD,CAAC;IAED,MAAM,IAAI,GAAG,IAAA,mBAAQ,EAAC,GAAG,CAAC,SAAS,CAAC,IAAI,EAAE;QACxC,GAAG,IAAI;QACP,WAAW,EAAE,CAAC,GAAG,IAAI,CAAC,WAAW,EAAE,OAAO,EAAE,GAAG,CAAC;KACjD,CAAC,CAAC;IAEH,OAAO,IAAI,IAAI,EAAE,KAAK,EAAE,CAAC,IAAI,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC,EAAE,CAAC;AACrD,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nullable.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nullable.mjs new file mode 100644 index 0000000000000000000000000000000000000000..057ad3376cbb97d3c114c1ee903f152f80a0e296 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nullable.mjs @@ -0,0 +1,31 @@ +import { parseDef } from "../parseDef.mjs"; +import { primitiveMappings } from "./union.mjs"; +export function parseNullableDef(def, refs) { + if (['ZodString', 'ZodNumber', 'ZodBigInt', 'ZodBoolean', 'ZodNull'].includes(def.innerType._def.typeName) && + (!def.innerType._def.checks || !def.innerType._def.checks.length)) { + if (refs.target === 'openApi3' || refs.nullableStrategy === 'property') { + return { + type: primitiveMappings[def.innerType._def.typeName], + nullable: true, + }; + } + return { + type: [primitiveMappings[def.innerType._def.typeName], 'null'], + }; + } + if (refs.target === 'openApi3') { + const base = parseDef(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath], + }); + if (base && '$ref' in base) + return { allOf: [base], nullable: true }; + return base && { ...base, nullable: true }; + } + const base = parseDef(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath, 'anyOf', '0'], + }); + return base && { anyOf: [base, { type: 'null' }] }; +} +//# sourceMappingURL=nullable.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nullable.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nullable.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..14ac37faac35ebbf63800aa3911106e1a800d957 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/nullable.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"nullable.mjs","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/nullable.ts"],"names":[],"mappings":"OACO,EAAmB,QAAQ,EAAE;OAG7B,EAAE,iBAAiB,EAAE;AAU5B,MAAM,UAAU,gBAAgB,CAAC,GAAmB,EAAE,IAAU;IAC9D,IACE,CAAC,WAAW,EAAE,WAAW,EAAE,WAAW,EAAE,YAAY,EAAE,SAAS,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,CAAC,QAAQ,CAAC;QACtG,CAAC,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,CAAC,MAAM,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,EACjE,CAAC;QACD,IAAI,IAAI,CAAC,MAAM,KAAK,UAAU,IAAI,IAAI,CAAC,gBAAgB,KAAK,UAAU,EAAE,CAAC;YACvE,OAAO;gBACL,IAAI,EAAE,iBAAiB,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,CAAC,QAA0C,CAAC;gBACtF,QAAQ,EAAE,IAAI;aACR,CAAC;QACX,CAAC;QAED,OAAO;YACL,IAAI,EAAE,CAAC,iBAAiB,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,CAAC,QAA0C,CAAC,EAAE,MAAM,CAAC;SACjG,CAAC;IACJ,CAAC;IAED,IAAI,IAAI,CAAC,MAAM,KAAK,UAAU,EAAE,CAAC;QAC/B,MAAM,IAAI,GAAG,QAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,EAAE;YACxC,GAAG,IAAI;YACP,WAAW,EAAE,CAAC,GAAG,IAAI,CAAC,WAAW,CAAC;SACnC,CAAC,CAAC;QAEH,IAAI,IAAI,IAAI,MAAM,IAAI,IAAI;YAAE,OAAO,EAAE,KAAK,EAAE,CAAC,IAAI,CAAC,EAAE,QAAQ,EAAE,IAAI,EAAS,CAAC;QAE5E,OAAO,IAAI,IAAK,EAAE,GAAG,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAU,CAAC;IACtD,CAAC;IAED,MAAM,IAAI,GAAG,QAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,EAAE;QACxC,GAAG,IAAI;QACP,WAAW,EAAE,CAAC,GAAG,IAAI,CAAC,WAAW,EAAE,OAAO,EAAE,GAAG,CAAC;KACjD,CAAC,CAAC;IAEH,OAAO,IAAI,IAAI,EAAE,KAAK,EAAE,CAAC,IAAI,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC,EAAE,CAAC;AACrD,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/number.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/number.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..e06b80e2cbe4970e7dcd31acc5cd0c304729fd69 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/number.d.mts @@ -0,0 +1,14 @@ +import { ZodNumberDef } from 'zod'; +import { ErrorMessages } from "../errorMessages.mjs"; +import { Refs } from "../Refs.mjs"; +export type JsonSchema7NumberType = { + type: 'number' | 'integer'; + minimum?: number; + exclusiveMinimum?: number; + maximum?: number; + exclusiveMaximum?: number; + multipleOf?: number; + errorMessage?: ErrorMessages; +}; +export declare function parseNumberDef(def: ZodNumberDef, refs: Refs): JsonSchema7NumberType; +//# sourceMappingURL=number.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/number.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/number.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..8577d5f5605616e4d70f997b40c4895dc3e62d0a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/number.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"number.d.mts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/number.ts"],"names":[],"mappings":"OAAO,EAAE,YAAY,EAAE,MAAM,KAAK;OAC3B,EAAmB,aAAa,EAA6B;OAC7D,EAAE,IAAI,EAAE;AAEf,MAAM,MAAM,qBAAqB,GAAG;IAClC,IAAI,EAAE,QAAQ,GAAG,SAAS,CAAC;IAC3B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,YAAY,CAAC,EAAE,aAAa,CAAC,qBAAqB,CAAC,CAAC;CACrD,CAAC;AAEF,wBAAgB,cAAc,CAAC,GAAG,EAAE,YAAY,EAAE,IAAI,EAAE,IAAI,GAAG,qBAAqB,CA+CnF"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/number.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/number.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..364b0ed1bb3dafc59c4a5399951add04090d1fdc --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/number.d.ts @@ -0,0 +1,14 @@ +import { ZodNumberDef } from 'zod'; +import { ErrorMessages } from "../errorMessages.js"; +import { Refs } from "../Refs.js"; +export type JsonSchema7NumberType = { + type: 'number' | 'integer'; + minimum?: number; + exclusiveMinimum?: number; + maximum?: number; + exclusiveMaximum?: number; + multipleOf?: number; + errorMessage?: ErrorMessages; +}; +export declare function parseNumberDef(def: ZodNumberDef, refs: Refs): JsonSchema7NumberType; +//# sourceMappingURL=number.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/number.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/number.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..b2bc56e48047d6209501d5e1410f0b62fffd8534 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/number.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"number.d.ts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/number.ts"],"names":[],"mappings":"OAAO,EAAE,YAAY,EAAE,MAAM,KAAK;OAC3B,EAAmB,aAAa,EAA6B;OAC7D,EAAE,IAAI,EAAE;AAEf,MAAM,MAAM,qBAAqB,GAAG;IAClC,IAAI,EAAE,QAAQ,GAAG,SAAS,CAAC;IAC3B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,YAAY,CAAC,EAAE,aAAa,CAAC,qBAAqB,CAAC,CAAC;CACrD,CAAC;AAEF,wBAAgB,cAAc,CAAC,GAAG,EAAE,YAAY,EAAE,IAAI,EAAE,IAAI,GAAG,qBAAqB,CA+CnF"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/number.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/number.js new file mode 100644 index 0000000000000000000000000000000000000000..bb2ab643c3e7d1e587026db487fc5a8044858273 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/number.js @@ -0,0 +1,56 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseNumberDef = parseNumberDef; +const errorMessages_1 = require("../errorMessages.js"); +function parseNumberDef(def, refs) { + const res = { + type: 'number', + }; + if (!def.checks) + return res; + for (const check of def.checks) { + switch (check.kind) { + case 'int': + res.type = 'integer'; + (0, errorMessages_1.addErrorMessage)(res, 'type', check.message, refs); + break; + case 'min': + if (refs.target === 'jsonSchema7') { + if (check.inclusive) { + (0, errorMessages_1.setResponseValueAndErrors)(res, 'minimum', check.value, check.message, refs); + } + else { + (0, errorMessages_1.setResponseValueAndErrors)(res, 'exclusiveMinimum', check.value, check.message, refs); + } + } + else { + if (!check.inclusive) { + res.exclusiveMinimum = true; + } + (0, errorMessages_1.setResponseValueAndErrors)(res, 'minimum', check.value, check.message, refs); + } + break; + case 'max': + if (refs.target === 'jsonSchema7') { + if (check.inclusive) { + (0, errorMessages_1.setResponseValueAndErrors)(res, 'maximum', check.value, check.message, refs); + } + else { + (0, errorMessages_1.setResponseValueAndErrors)(res, 'exclusiveMaximum', check.value, check.message, refs); + } + } + else { + if (!check.inclusive) { + res.exclusiveMaximum = true; + } + (0, errorMessages_1.setResponseValueAndErrors)(res, 'maximum', check.value, check.message, refs); + } + break; + case 'multipleOf': + (0, errorMessages_1.setResponseValueAndErrors)(res, 'multipleOf', check.value, check.message, refs); + break; + } + } + return res; +} +//# sourceMappingURL=number.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/number.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/number.js.map new file mode 100644 index 0000000000000000000000000000000000000000..7014714147f4ce9e83998d96f4d65c5d9063307e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/number.js.map @@ -0,0 +1 @@ +{"version":3,"file":"number.js","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/number.ts"],"names":[],"mappings":";;AAcA,wCA+CC;AA5DD,uDAA6F;AAa7F,SAAgB,cAAc,CAAC,GAAiB,EAAE,IAAU;IAC1D,MAAM,GAAG,GAA0B;QACjC,IAAI,EAAE,QAAQ;KACf,CAAC;IAEF,IAAI,CAAC,GAAG,CAAC,MAAM;QAAE,OAAO,GAAG,CAAC;IAE5B,KAAK,MAAM,KAAK,IAAI,GAAG,CAAC,MAAM,EAAE,CAAC;QAC/B,QAAQ,KAAK,CAAC,IAAI,EAAE,CAAC;YACnB,KAAK,KAAK;gBACR,GAAG,CAAC,IAAI,GAAG,SAAS,CAAC;gBACrB,IAAA,+BAAe,EAAC,GAAG,EAAE,MAAM,EAAE,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;gBAClD,MAAM;YACR,KAAK,KAAK;gBACR,IAAI,IAAI,CAAC,MAAM,KAAK,aAAa,EAAE,CAAC;oBAClC,IAAI,KAAK,CAAC,SAAS,EAAE,CAAC;wBACpB,IAAA,yCAAyB,EAAC,GAAG,EAAE,SAAS,EAAE,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;oBAC9E,CAAC;yBAAM,CAAC;wBACN,IAAA,yCAAyB,EAAC,GAAG,EAAE,kBAAkB,EAAE,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;oBACvF,CAAC;gBACH,CAAC;qBAAM,CAAC;oBACN,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,CAAC;wBACrB,GAAG,CAAC,gBAAgB,GAAG,IAAW,CAAC;oBACrC,CAAC;oBACD,IAAA,yCAAyB,EAAC,GAAG,EAAE,SAAS,EAAE,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;gBAC9E,CAAC;gBACD,MAAM;YACR,KAAK,KAAK;gBACR,IAAI,IAAI,CAAC,MAAM,KAAK,aAAa,EAAE,CAAC;oBAClC,IAAI,KAAK,CAAC,SAAS,EAAE,CAAC;wBACpB,IAAA,yCAAyB,EAAC,GAAG,EAAE,SAAS,EAAE,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;oBAC9E,CAAC;yBAAM,CAAC;wBACN,IAAA,yCAAyB,EAAC,GAAG,EAAE,kBAAkB,EAAE,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;oBACvF,CAAC;gBACH,CAAC;qBAAM,CAAC;oBACN,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,CAAC;wBACrB,GAAG,CAAC,gBAAgB,GAAG,IAAW,CAAC;oBACrC,CAAC;oBACD,IAAA,yCAAyB,EAAC,GAAG,EAAE,SAAS,EAAE,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;gBAC9E,CAAC;gBACD,MAAM;YACR,KAAK,YAAY;gBACf,IAAA,yCAAyB,EAAC,GAAG,EAAE,YAAY,EAAE,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;gBAC/E,MAAM;QACV,CAAC;IACH,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/number.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/number.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1560b0021534eafa68a8c554e9fa9553e1ddbacc --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/number.mjs @@ -0,0 +1,53 @@ +import { addErrorMessage, setResponseValueAndErrors } from "../errorMessages.mjs"; +export function parseNumberDef(def, refs) { + const res = { + type: 'number', + }; + if (!def.checks) + return res; + for (const check of def.checks) { + switch (check.kind) { + case 'int': + res.type = 'integer'; + addErrorMessage(res, 'type', check.message, refs); + break; + case 'min': + if (refs.target === 'jsonSchema7') { + if (check.inclusive) { + setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs); + } + else { + setResponseValueAndErrors(res, 'exclusiveMinimum', check.value, check.message, refs); + } + } + else { + if (!check.inclusive) { + res.exclusiveMinimum = true; + } + setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs); + } + break; + case 'max': + if (refs.target === 'jsonSchema7') { + if (check.inclusive) { + setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs); + } + else { + setResponseValueAndErrors(res, 'exclusiveMaximum', check.value, check.message, refs); + } + } + else { + if (!check.inclusive) { + res.exclusiveMaximum = true; + } + setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs); + } + break; + case 'multipleOf': + setResponseValueAndErrors(res, 'multipleOf', check.value, check.message, refs); + break; + } + } + return res; +} +//# sourceMappingURL=number.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/number.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/number.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..65d1d8908f412ad4d8101fbbd41f97840251f769 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/number.mjs.map @@ -0,0 +1 @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ACR,IAAI,IAAI,CAAC,MAAM,KAAK,aAAa,EAAE,CAAC;oBAClC,IAAI,KAAK,CAAC,SAAS,EAAE,CAAC;wBACpB,yBAAyB,CAAC,GAAG,EAAE,SAAS,EAAE,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;oBAC9E,CAAC;yBAAM,CAAC;wBACN,yBAAyB,CAAC,GAAG,EAAE,kBAAkB,EAAE,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;oBACvF,CAAC;gBACH,CAAC;qBAAM,CAAC;oBACN,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,CAAC;wBACrB,GAAG,CAAC,gBAAgB,GAAG,IAAW,CAAC;oBACrC,CAAC;oBACD,yBAAyB,CAAC,GAAG,EAAE,SAAS,EAAE,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;gBAC9E,CAAC;gBACD,MAAM;YACR,KAAK,YAAY;gBACf,yBAAyB,CAAC,GAAG,EAAE,YAAY,EAAE,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;gBAC/E,MAAM;QACV,CAAC;IACH,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/object.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/object.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..6bf575449c6eee12eb99a328307c4a7fb2c4577c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/object.d.mts @@ -0,0 +1,11 @@ +import { ZodObjectDef } from 'zod'; +import { JsonSchema7Type } from "../parseDef.mjs"; +import { Refs } from "../Refs.mjs"; +export type JsonSchema7ObjectType = { + type: 'object'; + properties: Record; + additionalProperties: boolean | JsonSchema7Type; + required?: string[]; +}; +export declare function parseObjectDef(def: ZodObjectDef, refs: Refs): JsonSchema7ObjectType; +//# sourceMappingURL=object.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/object.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/object.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..6e44b76001ce4ba03509e51f509e914999d5d8dd --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/object.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"object.d.mts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/object.ts"],"names":[],"mappings":"OAAO,EAAE,YAAY,EAAE,MAAM,KAAK;OAC3B,EAAE,eAAe,EAAY;OAC7B,EAAE,IAAI,EAAE;AAoBf,MAAM,MAAM,qBAAqB,GAAG;IAClC,IAAI,EAAE,QAAQ,CAAC;IACf,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;IAC5C,oBAAoB,EAAE,OAAO,GAAG,eAAe,CAAC;IAChD,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;CACrB,CAAC;AAEF,wBAAgB,cAAc,CAAC,GAAG,EAAE,YAAY,EAAE,IAAI,EAAE,IAAI,yBA8C3D"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/object.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/object.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9dc95e1b280a1e2984f46ee353d02b95e59a5255 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/object.d.ts @@ -0,0 +1,11 @@ +import { ZodObjectDef } from 'zod'; +import { JsonSchema7Type } from "../parseDef.js"; +import { Refs } from "../Refs.js"; +export type JsonSchema7ObjectType = { + type: 'object'; + properties: Record; + additionalProperties: boolean | JsonSchema7Type; + required?: string[]; +}; +export declare function parseObjectDef(def: ZodObjectDef, refs: Refs): JsonSchema7ObjectType; +//# sourceMappingURL=object.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/object.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/object.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..f3dcf61ed86e42b850c52af81a47b43d12745afa --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/object.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"object.d.ts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/object.ts"],"names":[],"mappings":"OAAO,EAAE,YAAY,EAAE,MAAM,KAAK;OAC3B,EAAE,eAAe,EAAY;OAC7B,EAAE,IAAI,EAAE;AAoBf,MAAM,MAAM,qBAAqB,GAAG;IAClC,IAAI,EAAE,QAAQ,CAAC;IACf,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;IAC5C,oBAAoB,EAAE,OAAO,GAAG,eAAe,CAAC;IAChD,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;CACrB,CAAC;AAEF,wBAAgB,cAAc,CAAC,GAAG,EAAE,YAAY,EAAE,IAAI,EAAE,IAAI,yBA8C3D"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/object.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/object.js new file mode 100644 index 0000000000000000000000000000000000000000..be930c28f1c4bde0ef6a25b3914955cd94c37cd2 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/object.js @@ -0,0 +1,57 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseObjectDef = parseObjectDef; +const parseDef_1 = require("../parseDef.js"); +function decideAdditionalProperties(def, refs) { + if (refs.removeAdditionalStrategy === 'strict') { + return def.catchall._def.typeName === 'ZodNever' ? + def.unknownKeys !== 'strict' + : (0, parseDef_1.parseDef)(def.catchall._def, { + ...refs, + currentPath: [...refs.currentPath, 'additionalProperties'], + }) ?? true; + } + else { + return def.catchall._def.typeName === 'ZodNever' ? + def.unknownKeys === 'passthrough' + : (0, parseDef_1.parseDef)(def.catchall._def, { + ...refs, + currentPath: [...refs.currentPath, 'additionalProperties'], + }) ?? true; + } +} +function parseObjectDef(def, refs) { + const result = { + type: 'object', + ...Object.entries(def.shape()).reduce((acc, [propName, propDef]) => { + if (propDef === undefined || propDef._def === undefined) + return acc; + const propertyPath = [...refs.currentPath, 'properties', propName]; + const parsedDef = (0, parseDef_1.parseDef)(propDef._def, { + ...refs, + currentPath: propertyPath, + propertyPath, + }); + if (parsedDef === undefined) + return acc; + if (refs.openaiStrictMode && + propDef.isOptional() && + !propDef.isNullable() && + typeof propDef._def?.defaultValue === 'undefined') { + throw new Error(`Zod field at \`${propertyPath.join('/')}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`); + } + return { + properties: { + ...acc.properties, + [propName]: parsedDef, + }, + required: propDef.isOptional() && !refs.openaiStrictMode ? acc.required : [...acc.required, propName], + }; + }, { properties: {}, required: [] }), + additionalProperties: decideAdditionalProperties(def, refs), + }; + if (!result.required.length) + delete result.required; + return result; +} +//# sourceMappingURL=object.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/object.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/object.js.map new file mode 100644 index 0000000000000000000000000000000000000000..febff2b9d28d98d49aa8e9c4a61452e5b4d66e32 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/object.js.map @@ -0,0 +1 @@ +{"version":3,"file":"object.js","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/object.ts"],"names":[],"mappings":";;AA6BA,wCA8CC;AA1ED,6CAAwD;AAGxD,SAAS,0BAA0B,CAAC,GAAiB,EAAE,IAAU;IAC/D,IAAI,IAAI,CAAC,wBAAwB,KAAK,QAAQ,EAAE,CAAC;QAC/C,OAAO,GAAG,CAAC,QAAQ,CAAC,IAAI,CAAC,QAAQ,KAAK,UAAU,CAAC,CAAC;YAC9C,GAAG,CAAC,WAAW,KAAK,QAAQ;YAC9B,CAAC,CAAC,IAAA,mBAAQ,EAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,EAAE;gBAC1B,GAAG,IAAI;gBACP,WAAW,EAAE,CAAC,GAAG,IAAI,CAAC,WAAW,EAAE,sBAAsB,CAAC;aAC3D,CAAC,IAAI,IAAI,CAAC;IACjB,CAAC;SAAM,CAAC;QACN,OAAO,GAAG,CAAC,QAAQ,CAAC,IAAI,CAAC,QAAQ,KAAK,UAAU,CAAC,CAAC;YAC9C,GAAG,CAAC,WAAW,KAAK,aAAa;YACnC,CAAC,CAAC,IAAA,mBAAQ,EAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,EAAE;gBAC1B,GAAG,IAAI;gBACP,WAAW,EAAE,CAAC,GAAG,IAAI,CAAC,WAAW,EAAE,sBAAsB,CAAC;aAC3D,CAAC,IAAI,IAAI,CAAC;IACjB,CAAC;AACH,CAAC;AASD,SAAgB,cAAc,CAAC,GAAiB,EAAE,IAAU;IAC1D,MAAM,MAAM,GAA0B;QACpC,IAAI,EAAE,QAAQ;QACd,GAAG,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,C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,MAAM,CAAC,QAAQ,CAAC;IACrD,OAAO,MAAM,CAAC;AAChB,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/object.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/object.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a13d0938f5c63bcf91fa984894186b3141f1a10e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/object.mjs @@ -0,0 +1,54 @@ +import { parseDef } from "../parseDef.mjs"; +function decideAdditionalProperties(def, refs) { + if (refs.removeAdditionalStrategy === 'strict') { + return def.catchall._def.typeName === 'ZodNever' ? + def.unknownKeys !== 'strict' + : parseDef(def.catchall._def, { + ...refs, + currentPath: [...refs.currentPath, 'additionalProperties'], + }) ?? true; + } + else { + return def.catchall._def.typeName === 'ZodNever' ? + def.unknownKeys === 'passthrough' + : parseDef(def.catchall._def, { + ...refs, + currentPath: [...refs.currentPath, 'additionalProperties'], + }) ?? true; + } +} +export function parseObjectDef(def, refs) { + const result = { + type: 'object', + ...Object.entries(def.shape()).reduce((acc, [propName, propDef]) => { + if (propDef === undefined || propDef._def === undefined) + return acc; + const propertyPath = [...refs.currentPath, 'properties', propName]; + const parsedDef = parseDef(propDef._def, { + ...refs, + currentPath: propertyPath, + propertyPath, + }); + if (parsedDef === undefined) + return acc; + if (refs.openaiStrictMode && + propDef.isOptional() && + !propDef.isNullable() && + typeof propDef._def?.defaultValue === 'undefined') { + throw new Error(`Zod field at \`${propertyPath.join('/')}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`); + } + return { + properties: { + ...acc.properties, + [propName]: parsedDef, + }, + required: propDef.isOptional() && !refs.openaiStrictMode ? acc.required : [...acc.required, propName], + }; + }, { properties: {}, required: [] }), + additionalProperties: decideAdditionalProperties(def, refs), + }; + if (!result.required.length) + delete result.required; + return result; +} +//# sourceMappingURL=object.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/object.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/object.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..4508e8cd900532e8f9f282c39330da39ea5e4cc6 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/object.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"object.mjs","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/object.ts"],"names":[],"mappings":"OACO,EAAmB,QAAQ,EAAE;AAGpC,SAAS,0BAA0B,CAAC,GAAiB,EAAE,IAAU;IAC/D,IAAI,IAAI,CAAC,wBAAwB,KAAK,QAAQ,EAAE,CAAC;QAC/C,OAAO,GAAG,CAAC,QAAQ,CAAC,IAAI,CAAC,QAAQ,KAAK,UAAU,CAAC,CAAC;YAC9C,GAAG,CAAC,WAAW,KAAK,QAAQ;YAC9B,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,EAAE;gBAC1B,GAAG,IAAI;gBACP,WAAW,EAAE,CAAC,GAAG,IAAI,CAAC,WAAW,EAAE,sBAAsB,CAAC;aAC3D,CAAC,IAAI,IAAI,CAAC;IACjB,CAAC;SAAM,CAAC;QACN,OAAO,GAAG,CAAC,QAAQ,CAAC,IAAI,CAAC,QAAQ,KAAK,UAAU,CAAC,CAAC;YAC9C,GAAG,CAAC,WAAW,KAAK,aAAa;YACnC,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,EAAE;gBAC1B,GAAG,IAAI;gBACP,WAAW,EAAE,CAAC,GAAG,IAAI,CAAC,WAAW,EAAE,sBAAsB,CAAC;aAC3D,CAAC,IAAI,IAAI,CAAC;IACj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EAAE,EAAE,EAAE,QAAQ,EAAE,EAAE,EAAE,CACjC;QACD,oBAAoB,EAAE,0BAA0B,CAAC,GAAG,EAAE,IAAI,CAAC;KAC5D,CAAC;IACF,IAAI,CAAC,MAAM,CAAC,QAAS,CAAC,MAAM;QAAE,OAAO,MAAM,CAAC,QAAQ,CAAC;IACrD,OAAO,MAAM,CAAC;AAChB,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/optional.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/optional.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..9d19a3fd7f3cd158e291f6f1ca6bde092503d17d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/optional.d.mts @@ -0,0 +1,5 @@ +import { ZodOptionalDef } from 'zod'; +import { JsonSchema7Type } from "../parseDef.mjs"; +import { Refs } from "../Refs.mjs"; +export declare const parseOptionalDef: (def: ZodOptionalDef, refs: Refs) => JsonSchema7Type | undefined; +//# sourceMappingURL=optional.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/optional.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/optional.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..2d7bd3c7c17ae16cafe0f665dc93af5367c293c8 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/optional.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"optional.d.mts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/optional.ts"],"names":[],"mappings":"OAAO,EAAE,cAAc,EAAE,MAAM,KAAK;OAC7B,EAAE,eAAe,EAAY;OAC7B,EAAE,IAAI,EAAE;AAEf,eAAO,MAAM,gBAAgB,GAAI,KAAK,cAAc,EAAE,MAAM,IAAI,KAAG,eAAe,GAAG,SAuBpF,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/optional.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/optional.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6160c994ec5abbc2618c3ec9dfa2dd086787f093 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/optional.d.ts @@ -0,0 +1,5 @@ +import { ZodOptionalDef } from 'zod'; +import { JsonSchema7Type } from "../parseDef.js"; +import { Refs } from "../Refs.js"; +export declare const parseOptionalDef: (def: ZodOptionalDef, refs: Refs) => JsonSchema7Type | undefined; +//# sourceMappingURL=optional.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/optional.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/optional.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..2a2531884adad16796df69f2b64062608580f9b3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/optional.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"optional.d.ts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/optional.ts"],"names":[],"mappings":"OAAO,EAAE,cAAc,EAAE,MAAM,KAAK;OAC7B,EAAE,eAAe,EAAY;OAC7B,EAAE,IAAI,EAAE;AAEf,eAAO,MAAM,gBAAgB,GAAI,KAAK,cAAc,EAAE,MAAM,IAAI,KAAG,eAAe,GAAG,SAuBpF,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/optional.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/optional.js new file mode 100644 index 0000000000000000000000000000000000000000..a2cae117be5212e8079ac05c5b0e33029da281ea --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/optional.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseOptionalDef = void 0; +const parseDef_1 = require("../parseDef.js"); +const parseOptionalDef = (def, refs) => { + if (refs.propertyPath && + refs.currentPath.slice(0, refs.propertyPath.length).toString() === refs.propertyPath.toString()) { + return (0, parseDef_1.parseDef)(def.innerType._def, { ...refs, currentPath: refs.currentPath }); + } + const innerSchema = (0, parseDef_1.parseDef)(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath, 'anyOf', '1'], + }); + return innerSchema ? + { + anyOf: [ + { + not: {}, + }, + innerSchema, + ], + } + : {}; +}; +exports.parseOptionalDef = parseOptionalDef; +//# sourceMappingURL=optional.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/optional.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/optional.js.map new file mode 100644 index 0000000000000000000000000000000000000000..7edda9292ada7046384d44b268e9bf74dc2d9e6e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/optional.js.map @@ -0,0 +1 @@ +{"version":3,"file":"optional.js","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/optional.ts"],"names":[],"mappings":";;;AACA,6CAAwD;AAGjD,MAAM,gBAAgB,GAAG,CAAC,GAAmB,EAAE,IAAU,EAA+B,EAAE;IAC/F,IACE,IAAI,CAAC,YAAY;QACjB,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE,KAAK,IAAI,CAAC,YAAY,CAAC,QAAQ,EAAE,EAC/F,CAAC;QACD,OAAO,IAAA,mBAAQ,EAAC,GAAG,CAAC,SAAS,CAAC,IAAI,EAAE,EAAE,GAAG,IAAI,EAAE,WAAW,EAAE,IAAI,CAAC,WAAW,EAAE,CAAC,CAAC;IAClF,CAAC;IAED,MAAM,WAAW,GAAG,IAAA,mBAAQ,EAAC,GAAG,CAAC,SAAS,CAAC,IAAI,EAAE;QAC/C,GAAG,IAAI;QACP,WAAW,EAAE,CAAC,GAAG,IAAI,CAAC,WAAW,EAAE,OAAO,EAAE,GAAG,CAAC;KACjD,CAAC,CAAC;IAEH,OAAO,WAAW,CAAC,CAAC;QAChB;YACE,KAAK,EAAE;gBACL;oBACE,GAAG,EAAE,EAAE;iBACR;gBACD,WAAW;aACZ;SACF;QACH,CAAC,CAAC,EAAE,CAAC;AACT,CAAC,CAAC;AAvBW,QAAA,gBAAgB,oBAuB3B"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/optional.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/optional.mjs new file mode 100644 index 0000000000000000000000000000000000000000..98d86b4d608d3a8638eecad2cf5b03c169bd17da --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/optional.mjs @@ -0,0 +1,22 @@ +import { parseDef } from "../parseDef.mjs"; +export const parseOptionalDef = (def, refs) => { + if (refs.propertyPath && + refs.currentPath.slice(0, refs.propertyPath.length).toString() === refs.propertyPath.toString()) { + return parseDef(def.innerType._def, { ...refs, currentPath: refs.currentPath }); + } + const innerSchema = parseDef(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath, 'anyOf', '1'], + }); + return innerSchema ? + { + anyOf: [ + { + not: {}, + }, + innerSchema, + ], + } + : {}; +}; +//# sourceMappingURL=optional.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/optional.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/optional.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..3c3e0e5bbb1e4a40083cb1e83d629e15d1698f9e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/optional.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"optional.mjs","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/optional.ts"],"names":[],"mappings":"OACO,EAAmB,QAAQ,EAAE;AAGpC,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,GAAmB,EAAE,IAAU,EAA+B,EAAE;IAC/F,IACE,IAAI,CAAC,YAAY;QACjB,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE,KAAK,IAAI,CAAC,YAAY,CAAC,QAAQ,EAAE,EAC/F,CAAC;QACD,OAAO,QAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,EAAE,EAAE,GAAG,IAAI,EAAE,WAAW,EAAE,IAAI,CAAC,WAAW,EAAE,CAAC,CAAC;IAClF,CAAC;IAED,MAAM,WAAW,GAAG,QAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,EAAE;QAC/C,GAAG,IAAI;QACP,WAAW,EAAE,CAAC,GAAG,IAAI,CAAC,WAAW,EAAE,OAAO,EAAE,GAAG,CAAC;KACjD,CAAC,CAAC;IAEH,OAAO,WAAW,CAAC,CAAC;QAChB;YACE,KAAK,EAAE;gBACL;oBACE,GAAG,EAAE,EAAE;iBACR;gBACD,WAAW;aACZ;SACF;QACH,CAAC,CAAC,EAAE,CAAC;AACT,CAAC,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/pipeline.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/pipeline.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..80e22d5375e2ea4eed21ea65c7d0e27965225b55 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/pipeline.d.mts @@ -0,0 +1,6 @@ +import { ZodPipelineDef } from 'zod'; +import { JsonSchema7Type } from "../parseDef.mjs"; +import { Refs } from "../Refs.mjs"; +import { JsonSchema7AllOfType } from "./intersection.mjs"; +export declare const parsePipelineDef: (def: ZodPipelineDef, refs: Refs) => JsonSchema7AllOfType | JsonSchema7Type | undefined; +//# sourceMappingURL=pipeline.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/pipeline.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/pipeline.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..c22f8254a567314010863ac5a1b1beaa96685e15 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/pipeline.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"pipeline.d.mts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/pipeline.ts"],"names":[],"mappings":"OAAO,EAAE,cAAc,EAAE,MAAM,KAAK;OAC7B,EAAE,eAAe,EAAY;OAC7B,EAAE,IAAI,EAAE;OACR,EAAE,oBAAoB,EAAE;AAE/B,eAAO,MAAM,gBAAgB,GAC3B,KAAK,cAAc,CAAC,GAAG,EAAE,GAAG,CAAC,EAC7B,MAAM,IAAI,KACT,oBAAoB,GAAG,eAAe,GAAG,SAmB3C,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/pipeline.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/pipeline.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4fe9b1ba5e989a707293360a40fba1cc0fcebadc --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/pipeline.d.ts @@ -0,0 +1,6 @@ +import { ZodPipelineDef } from 'zod'; +import { JsonSchema7Type } from "../parseDef.js"; +import { Refs } from "../Refs.js"; +import { JsonSchema7AllOfType } from "./intersection.js"; +export declare const parsePipelineDef: (def: ZodPipelineDef, refs: Refs) => JsonSchema7AllOfType | JsonSchema7Type | undefined; +//# sourceMappingURL=pipeline.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/pipeline.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/pipeline.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..528f825b8c3fdfcfbad0950348554f9fbb58d13c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/pipeline.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"pipeline.d.ts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/pipeline.ts"],"names":[],"mappings":"OAAO,EAAE,cAAc,EAAE,MAAM,KAAK;OAC7B,EAAE,eAAe,EAAY;OAC7B,EAAE,IAAI,EAAE;OACR,EAAE,oBAAoB,EAAE;AAE/B,eAAO,MAAM,gBAAgB,GAC3B,KAAK,cAAc,CAAC,GAAG,EAAE,GAAG,CAAC,EAC7B,MAAM,IAAI,KACT,oBAAoB,GAAG,eAAe,GAAG,SAmB3C,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/pipeline.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/pipeline.js new file mode 100644 index 0000000000000000000000000000000000000000..34a23372751536fb5d3aa174a0e3516360cff8fe --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/pipeline.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parsePipelineDef = void 0; +const parseDef_1 = require("../parseDef.js"); +const parsePipelineDef = (def, refs) => { + if (refs.pipeStrategy === 'input') { + return (0, parseDef_1.parseDef)(def.in._def, refs); + } + else if (refs.pipeStrategy === 'output') { + return (0, parseDef_1.parseDef)(def.out._def, refs); + } + const a = (0, parseDef_1.parseDef)(def.in._def, { + ...refs, + currentPath: [...refs.currentPath, 'allOf', '0'], + }); + const b = (0, parseDef_1.parseDef)(def.out._def, { + ...refs, + currentPath: [...refs.currentPath, 'allOf', a ? '1' : '0'], + }); + return { + allOf: [a, b].filter((x) => x !== undefined), + }; +}; +exports.parsePipelineDef = parsePipelineDef; +//# sourceMappingURL=pipeline.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/pipeline.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/pipeline.js.map new file mode 100644 index 0000000000000000000000000000000000000000..7cee2ac0fbe814cb019250f668aada363b01c3e3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/pipeline.js.map @@ -0,0 +1 @@ +{"version":3,"file":"pipeline.js","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/pipeline.ts"],"names":[],"mappings":";;;AACA,6CAAwD;AAIjD,MAAM,gBAAgB,GAAG,CAC9B,GAA6B,EAC7B,IAAU,EAC0C,EAAE;IACtD,IAAI,IAAI,CAAC,YAAY,KAAK,OAAO,EAAE,CAAC;QAClC,OAAO,IAAA,mBAAQ,EAAC,GAAG,CAAC,EAAE,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IACrC,CAAC;SAAM,IAAI,IAAI,CAAC,YAAY,KAAK,QAAQ,EAAE,CAAC;QAC1C,OAAO,IAAA,mBAAQ,EAAC,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IACtC,CAAC;IAED,MAAM,CAAC,GAAG,IAAA,mBAAQ,EAAC,GAAG,CAAC,EAAE,CAAC,IAAI,EAAE;QAC9B,GAAG,IAAI;QACP,WAAW,EAAE,CAAC,GAAG,IAAI,CAAC,WAAW,EAAE,OAAO,EAAE,GAAG,CAAC;KACjD,CAAC,CAAC;IACH,MAAM,CAAC,GAAG,IAAA,mBAAQ,EAAC,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE;QAC/B,GAAG,IAAI;QACP,WAAW,EAAE,CAAC,GAAG,IAAI,CAAC,WAAW,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC;KAC3D,CAAC,CAAC;IAEH,OAAO;QACL,KAAK,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAwB,EAAE,CAAC,CAAC,KAAK,SAAS,CAAC;KACnE,CAAC;AACJ,CAAC,CAAC;AAtBW,QAAA,gBAAgB,oBAsB3B"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/pipeline.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/pipeline.mjs new file mode 100644 index 0000000000000000000000000000000000000000..540d15a754d457ae53fbdb11bef3fe9bdc6cb4ff --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/pipeline.mjs @@ -0,0 +1,21 @@ +import { parseDef } from "../parseDef.mjs"; +export const parsePipelineDef = (def, refs) => { + if (refs.pipeStrategy === 'input') { + return parseDef(def.in._def, refs); + } + else if (refs.pipeStrategy === 'output') { + return parseDef(def.out._def, refs); + } + const a = parseDef(def.in._def, { + ...refs, + currentPath: [...refs.currentPath, 'allOf', '0'], + }); + const b = parseDef(def.out._def, { + ...refs, + currentPath: [...refs.currentPath, 'allOf', a ? '1' : '0'], + }); + return { + allOf: [a, b].filter((x) => x !== undefined), + }; +}; +//# sourceMappingURL=pipeline.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/pipeline.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/pipeline.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..16008d72c5c1ba0ef61dd5d965474e697f3cc5a3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/pipeline.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"pipeline.mjs","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/pipeline.ts"],"names":[],"mappings":"OACO,EAAmB,QAAQ,EAAE;AAIpC,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAC9B,GAA6B,EAC7B,IAAU,EAC0C,EAAE;IACtD,IAAI,IAAI,CAAC,YAAY,KAAK,OAAO,EAAE,CAAC;QAClC,OAAO,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IACrC,CAAC;SAAM,IAAI,IAAI,CAAC,YAAY,KAAK,QAAQ,EAAE,CAAC;QAC1C,OAAO,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IACtC,CAAC;IAED,MAAM,CAAC,GAAG,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,EAAE;QAC9B,GAAG,IAAI;QACP,WAAW,EAAE,CAAC,GAAG,IAAI,CAAC,WAAW,EAAE,OAAO,EAAE,GAAG,CAAC;KACjD,CAAC,CAAC;IACH,MAAM,CAAC,GAAG,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE;QAC/B,GAAG,IAAI;QACP,WAAW,EAAE,CAAC,GAAG,IAAI,CAAC,WAAW,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC;KAC3D,CAAC,CAAC;IAEH,OAAO;QACL,KAAK,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAwB,EAAE,CAAC,CAAC,KAAK,SAAS,CAAC;KACnE,CAAC;AACJ,CAAC,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/promise.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/promise.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..3b5e5ff88f3bbf777c1248d3fbd9b68156caf3a2 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/promise.d.mts @@ -0,0 +1,5 @@ +import { ZodPromiseDef } from 'zod'; +import { JsonSchema7Type } from "../parseDef.mjs"; +import { Refs } from "../Refs.mjs"; +export declare function parsePromiseDef(def: ZodPromiseDef, refs: Refs): JsonSchema7Type | undefined; +//# sourceMappingURL=promise.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/promise.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/promise.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..37ab3f68659686f8f3c94664bfdbcd9d7b9c64d7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/promise.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"promise.d.mts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/promise.ts"],"names":[],"mappings":"OAAO,EAAE,aAAa,EAAE,MAAM,KAAK;OAC5B,EAAE,eAAe,EAAY;OAC7B,EAAE,IAAI,EAAE;AAEf,wBAAgB,eAAe,CAAC,GAAG,EAAE,aAAa,EAAE,IAAI,EAAE,IAAI,GAAG,eAAe,GAAG,SAAS,CAE3F"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/promise.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/promise.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5182c7a0cdb83ea18b92219bd3c8e4b890d24f2b --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/promise.d.ts @@ -0,0 +1,5 @@ +import { ZodPromiseDef } from 'zod'; +import { JsonSchema7Type } from "../parseDef.js"; +import { Refs } from "../Refs.js"; +export declare function parsePromiseDef(def: ZodPromiseDef, refs: Refs): JsonSchema7Type | undefined; +//# sourceMappingURL=promise.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/promise.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/promise.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..a765e144e21cac0a857dcd60af22e80e1868ebbd --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/promise.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"promise.d.ts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/promise.ts"],"names":[],"mappings":"OAAO,EAAE,aAAa,EAAE,MAAM,KAAK;OAC5B,EAAE,eAAe,EAAY;OAC7B,EAAE,IAAI,EAAE;AAEf,wBAAgB,eAAe,CAAC,GAAG,EAAE,aAAa,EAAE,IAAI,EAAE,IAAI,GAAG,eAAe,GAAG,SAAS,CAE3F"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/promise.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/promise.js new file mode 100644 index 0000000000000000000000000000000000000000..a073bbcdfe21e9804cce3a46d2a89db63ae5d298 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/promise.js @@ -0,0 +1,8 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parsePromiseDef = parsePromiseDef; +const parseDef_1 = require("../parseDef.js"); +function parsePromiseDef(def, refs) { + return (0, parseDef_1.parseDef)(def.type._def, refs); +} +//# sourceMappingURL=promise.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/promise.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/promise.js.map new file mode 100644 index 0000000000000000000000000000000000000000..60d386c394f11da90ce4dcdc2f21bdb370dd9d5e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/promise.js.map @@ -0,0 +1 @@ +{"version":3,"file":"promise.js","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/promise.ts"],"names":[],"mappings":";;AAIA,0CAEC;AALD,6CAAwD;AAGxD,SAAgB,eAAe,CAAC,GAAkB,EAAE,IAAU;IAC5D,OAAO,IAAA,mBAAQ,EAAC,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;AACvC,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/promise.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/promise.mjs new file mode 100644 index 0000000000000000000000000000000000000000..cfe6b738a4ab570490e547ce7402089c63808364 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/promise.mjs @@ -0,0 +1,5 @@ +import { parseDef } from "../parseDef.mjs"; +export function parsePromiseDef(def, refs) { + return parseDef(def.type._def, refs); +} +//# sourceMappingURL=promise.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/promise.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/promise.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..2cee9b05ef1e64850fdb0cf56f7decfd4abf741f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/promise.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"promise.mjs","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/promise.ts"],"names":[],"mappings":"OACO,EAAmB,QAAQ,EAAE;AAGpC,MAAM,UAAU,eAAe,CAAC,GAAkB,EAAE,IAAU;IAC5D,OAAO,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;AACvC,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/readonly.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/readonly.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..77bdac1a8d0481abc38f354f995d65d96783cbae --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/readonly.d.mts @@ -0,0 +1,4 @@ +import { ZodReadonlyDef } from 'zod'; +import { Refs } from "../Refs.mjs"; +export declare const parseReadonlyDef: (def: ZodReadonlyDef, refs: Refs) => import("../parseDef").JsonSchema7Type | undefined; +//# sourceMappingURL=readonly.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/readonly.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/readonly.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..9c3bb9de99c30f029c57883bead4b3db247fc648 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/readonly.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"readonly.d.mts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/readonly.ts"],"names":[],"mappings":"OAAO,EAAE,cAAc,EAAE,MAAM,KAAK;OAE7B,EAAE,IAAI,EAAE;AAEf,eAAO,MAAM,gBAAgB,GAAI,KAAK,cAAc,CAAC,GAAG,CAAC,EAAE,MAAM,IAAI,sDAEpE,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/readonly.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/readonly.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..abcd39cac8121dc0dab1bdd26f82e9f66850fa9c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/readonly.d.ts @@ -0,0 +1,4 @@ +import { ZodReadonlyDef } from 'zod'; +import { Refs } from "../Refs.js"; +export declare const parseReadonlyDef: (def: ZodReadonlyDef, refs: Refs) => import("../parseDef").JsonSchema7Type | undefined; +//# sourceMappingURL=readonly.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/readonly.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/readonly.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..36541599c29dfcc994aa0a5e72e2937159f109ad --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/readonly.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"readonly.d.ts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/readonly.ts"],"names":[],"mappings":"OAAO,EAAE,cAAc,EAAE,MAAM,KAAK;OAE7B,EAAE,IAAI,EAAE;AAEf,eAAO,MAAM,gBAAgB,GAAI,KAAK,cAAc,CAAC,GAAG,CAAC,EAAE,MAAM,IAAI,sDAEpE,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/readonly.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/readonly.js new file mode 100644 index 0000000000000000000000000000000000000000..e3f91c462b6c8f7d3c2e36950efa1f97d9ee22ad --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/readonly.js @@ -0,0 +1,9 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseReadonlyDef = void 0; +const parseDef_1 = require("../parseDef.js"); +const parseReadonlyDef = (def, refs) => { + return (0, parseDef_1.parseDef)(def.innerType._def, refs); +}; +exports.parseReadonlyDef = parseReadonlyDef; +//# sourceMappingURL=readonly.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/readonly.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/readonly.js.map new file mode 100644 index 0000000000000000000000000000000000000000..0d4d60dc22532b9bf9d33bdb617376691a76ca12 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/readonly.js.map @@ -0,0 +1 @@ +{"version":3,"file":"readonly.js","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/readonly.ts"],"names":[],"mappings":";;;AACA,6CAAuC;AAGhC,MAAM,gBAAgB,GAAG,CAAC,GAAwB,EAAE,IAAU,EAAE,EAAE;IACvE,OAAO,IAAA,mBAAQ,EAAC,GAAG,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;AAC5C,CAAC,CAAC;AAFW,QAAA,gBAAgB,oBAE3B"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/readonly.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/readonly.mjs new file mode 100644 index 0000000000000000000000000000000000000000..852288ab545c88ceb4762d1416c0409ed06a838d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/readonly.mjs @@ -0,0 +1,5 @@ +import { parseDef } from "../parseDef.mjs"; +export const parseReadonlyDef = (def, refs) => { + return parseDef(def.innerType._def, refs); +}; +//# sourceMappingURL=readonly.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/readonly.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/readonly.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..64dfbc707d2e795d25aea11fef492541f33f67fc --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/readonly.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"readonly.mjs","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/readonly.ts"],"names":[],"mappings":"OACO,EAAE,QAAQ,EAAE;AAGnB,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,GAAwB,EAAE,IAAU,EAAE,EAAE;IACvE,OAAO,QAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;AAC5C,CAAC,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/record.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/record.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..90477d105ef9382d06452b2aa3136a12a5b1efe1 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/record.d.mts @@ -0,0 +1,14 @@ +import { ZodMapDef, ZodRecordDef, ZodTypeAny } from 'zod'; +import { JsonSchema7Type } from "../parseDef.mjs"; +import { Refs } from "../Refs.mjs"; +import { JsonSchema7EnumType } from "./enum.mjs"; +import { JsonSchema7StringType } from "./string.mjs"; +type JsonSchema7RecordPropertyNamesType = Omit | Omit; +export type JsonSchema7RecordType = { + type: 'object'; + additionalProperties: JsonSchema7Type; + propertyNames?: JsonSchema7RecordPropertyNamesType; +}; +export declare function parseRecordDef(def: ZodRecordDef | ZodMapDef, refs: Refs): JsonSchema7RecordType; +export {}; +//# sourceMappingURL=record.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/record.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/record.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..8f062b2d0a5019c16cbf9ac14571aa9d9d3ad204 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/record.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"record.d.mts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/record.ts"],"names":[],"mappings":"OAAO,EAAyB,SAAS,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,KAAK;OACzE,EAAE,eAAe,EAAY;OAC7B,EAAE,IAAI,EAAE;OACR,EAAE,mBAAmB,EAAE;OAEvB,EAAE,qBAAqB,EAAkB;AAEhD,KAAK,kCAAkC,GACnC,IAAI,CAAC,qBAAqB,EAAE,MAAM,CAAC,GACnC,IAAI,CAAC,mBAAmB,EAAE,MAAM,CAAC,CAAC;AAEtC,MAAM,MAAM,qBAAqB,GAAG;IAClC,IAAI,EAAE,QAAQ,CAAC;IACf,oBAAoB,EAAE,eAAe,CAAC;IACtC,aAAa,CAAC,EAAE,kCAAkC,CAAC;CACpD,CAAC;AAEF,wBAAgB,cAAc,CAC5B,GAAG,EAAE,YAAY,CAAC,UAAU,EAAE,UAAU,CAAC,GAAG,SAAS,EACrD,IAAI,EAAE,IAAI,GACT,qBAAqB,CAoDvB"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/record.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/record.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7a5d5b66b1eeb6db7d7207c81cdcd9fab5891c67 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/record.d.ts @@ -0,0 +1,14 @@ +import { ZodMapDef, ZodRecordDef, ZodTypeAny } from 'zod'; +import { JsonSchema7Type } from "../parseDef.js"; +import { Refs } from "../Refs.js"; +import { JsonSchema7EnumType } from "./enum.js"; +import { JsonSchema7StringType } from "./string.js"; +type JsonSchema7RecordPropertyNamesType = Omit | Omit; +export type JsonSchema7RecordType = { + type: 'object'; + additionalProperties: JsonSchema7Type; + propertyNames?: JsonSchema7RecordPropertyNamesType; +}; +export declare function parseRecordDef(def: ZodRecordDef | ZodMapDef, refs: Refs): JsonSchema7RecordType; +export {}; +//# sourceMappingURL=record.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/record.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/record.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..e2c0b964e9f1a1cf6e70e6da317479ba85d994a2 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/record.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"record.d.ts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/record.ts"],"names":[],"mappings":"OAAO,EAAyB,SAAS,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,KAAK;OACzE,EAAE,eAAe,EAAY;OAC7B,EAAE,IAAI,EAAE;OACR,EAAE,mBAAmB,EAAE;OAEvB,EAAE,qBAAqB,EAAkB;AAEhD,KAAK,kCAAkC,GACnC,IAAI,CAAC,qBAAqB,EAAE,MAAM,CAAC,GACnC,IAAI,CAAC,mBAAmB,EAAE,MAAM,CAAC,CAAC;AAEtC,MAAM,MAAM,qBAAqB,GAAG;IAClC,IAAI,EAAE,QAAQ,CAAC;IACf,oBAAoB,EAAE,eAAe,CAAC;IACtC,aAAa,CAAC,EAAE,kCAAkC,CAAC;CACpD,CAAC;AAEF,wBAAgB,cAAc,CAC5B,GAAG,EAAE,YAAY,CAAC,UAAU,EAAE,UAAU,CAAC,GAAG,SAAS,EACrD,IAAI,EAAE,IAAI,GACT,qBAAqB,CAoDvB"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/record.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/record.js new file mode 100644 index 0000000000000000000000000000000000000000..3ee48e052a916c31f436399bdb16bd4c11d9f379 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/record.js @@ -0,0 +1,49 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseRecordDef = parseRecordDef; +const zod_1 = require("zod"); +const parseDef_1 = require("../parseDef.js"); +const string_1 = require("./string.js"); +function parseRecordDef(def, refs) { + if (refs.target === 'openApi3' && def.keyType?._def.typeName === zod_1.ZodFirstPartyTypeKind.ZodEnum) { + return { + type: 'object', + required: def.keyType._def.values, + properties: def.keyType._def.values.reduce((acc, key) => ({ + ...acc, + [key]: (0, parseDef_1.parseDef)(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, 'properties', key], + }) ?? {}, + }), {}), + additionalProperties: false, + }; + } + const schema = { + type: 'object', + additionalProperties: (0, parseDef_1.parseDef)(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, 'additionalProperties'], + }) ?? {}, + }; + if (refs.target === 'openApi3') { + return schema; + } + if (def.keyType?._def.typeName === zod_1.ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) { + const keyType = Object.entries((0, string_1.parseStringDef)(def.keyType._def, refs)).reduce((acc, [key, value]) => (key === 'type' ? acc : { ...acc, [key]: value }), {}); + return { + ...schema, + propertyNames: keyType, + }; + } + else if (def.keyType?._def.typeName === zod_1.ZodFirstPartyTypeKind.ZodEnum) { + return { + ...schema, + propertyNames: { + enum: def.keyType._def.values, + }, + }; + } + return schema; +} +//# sourceMappingURL=record.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/record.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/record.js.map new file mode 100644 index 0000000000000000000000000000000000000000..f014fe5d749aec6df5cba62a4824d64dd7e5b652 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/record.js.map @@ -0,0 +1 @@ +{"version":3,"file":"record.js","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/record.ts"],"names":[],"mappings":";;AAiBA,wCAuDC;AAxED,6BAAiF;AACjF,6CAAwD;AAIxD,wCAAiE;AAYjE,SAAgB,cAAc,CAC5B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c,EAAC,GAAG,CAAC,OAAO,CAAC,IAAI,EAAE,IAAI,CAAC,CACvC,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC,GAAG,KAAK,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,EAAE,CAAC,GAAG,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC;QAEvF,OAAO;YACL,GAAG,MAAM;YACT,aAAa,EAAE,OAAO;SACvB,CAAC;IACJ,CAAC;SAAM,IAAI,GAAG,CAAC,OAAO,EAAE,IAAI,CAAC,QAAQ,KAAK,2BAAqB,CAAC,OAAO,EAAE,CAAC;QACxE,OAAO;YACL,GAAG,MAAM;YACT,aAAa,EAAE;gBACb,IAAI,EAAE,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM;aAC9B;SACF,CAAC;IACJ,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/record.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/record.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5ac62ea02ed38c5fa14721c006df7a4623eee8e9 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/record.mjs @@ -0,0 +1,46 @@ +import { ZodFirstPartyTypeKind } from 'zod'; +import { parseDef } from "../parseDef.mjs"; +import { parseStringDef } from "./string.mjs"; +export function parseRecordDef(def, refs) { + if (refs.target === 'openApi3' && def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) { + return { + type: 'object', + required: def.keyType._def.values, + properties: def.keyType._def.values.reduce((acc, key) => ({ + ...acc, + [key]: parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, 'properties', key], + }) ?? {}, + }), {}), + additionalProperties: false, + }; + } + const schema = { + type: 'object', + additionalProperties: parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, 'additionalProperties'], + }) ?? {}, + }; + if (refs.target === 'openApi3') { + return schema; + } + if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) { + const keyType = Object.entries(parseStringDef(def.keyType._def, refs)).reduce((acc, [key, value]) => (key === 'type' ? acc : { ...acc, [key]: value }), {}); + return { + ...schema, + propertyNames: keyType, + }; + } + else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) { + return { + ...schema, + propertyNames: { + enum: def.keyType._def.values, + }, + }; + } + return schema; +} +//# sourceMappingURL=record.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/record.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/record.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..652162764e406959176b8628c407576b40654cd7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/record.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"record.mjs","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/record.ts"],"names":[],"mappings":"OAAO,EAAE,qBAAqB,EAAuC,MAAM,KAAK;OACzE,EAAmB,QAAQ,EAAE;OAI7B,EAAyB,cAAc,EAAE;AAYhD,MAAM,UAAU,cAAc,CAC5B,GAAqD,EACrD,IAAU;IAEV,IAAI,IAAI,CAAC,MAAM,KAAK,UAAU,IAAI,GAAG,CAAC,OAAO,EAAE,IAAI,CAAC,QAAQ,KAAK,qBAAqB,CAAC,OAAO,EAAE,CAAC;QAC/F,OAAO;YACL,IAAI,EAAE,QAAQ;YACd,QAAQ,EAAE,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM;YACjC,UA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,EAAE,EAAE,CAAC,CAAC;QAEvF,OAAO;YACL,GAAG,MAAM;YACT,aAAa,EAAE,OAAO;SACvB,CAAC;IACJ,CAAC;SAAM,IAAI,GAAG,CAAC,OAAO,EAAE,IAAI,CAAC,QAAQ,KAAK,qBAAqB,CAAC,OAAO,EAAE,CAAC;QACxE,OAAO;YACL,GAAG,MAAM;YACT,aAAa,EAAE;gBACb,IAAI,EAAE,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM;aAC9B;SACF,CAAC;IACJ,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/set.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/set.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..3416269d17bc1141f1b96a2fbb7790d94118cafc --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/set.d.mts @@ -0,0 +1,14 @@ +import { ZodSetDef } from 'zod'; +import { ErrorMessages } from "../errorMessages.mjs"; +import { JsonSchema7Type } from "../parseDef.mjs"; +import { Refs } from "../Refs.mjs"; +export type JsonSchema7SetType = { + type: 'array'; + uniqueItems: true; + items?: JsonSchema7Type | undefined; + minItems?: number; + maxItems?: number; + errorMessage?: ErrorMessages; +}; +export declare function parseSetDef(def: ZodSetDef, refs: Refs): JsonSchema7SetType; +//# sourceMappingURL=set.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/set.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/set.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..741031e09beeb8f18d0f91997ad1f2fd206b3d09 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/set.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"set.d.mts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/set.ts"],"names":[],"mappings":"OAAO,EAAE,SAAS,EAAE,MAAM,KAAK;OACxB,EAAE,aAAa,EAA6B;OAC5C,EAAE,eAAe,EAAY;OAC7B,EAAE,IAAI,EAAE;AAEf,MAAM,MAAM,kBAAkB,GAAG;IAC/B,IAAI,EAAE,OAAO,CAAC;IACd,WAAW,EAAE,IAAI,CAAC;IAClB,KAAK,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC;IACpC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,YAAY,CAAC,EAAE,aAAa,CAAC,kBAAkB,CAAC,CAAC;CAClD,CAAC;AAEF,wBAAgB,WAAW,CAAC,GAAG,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,GAAG,kBAAkB,CAqB1E"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/set.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/set.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b0dbb90d7cdc8281a23b8a2e567619e7fd5eda84 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/set.d.ts @@ -0,0 +1,14 @@ +import { ZodSetDef } from 'zod'; +import { ErrorMessages } from "../errorMessages.js"; +import { JsonSchema7Type } from "../parseDef.js"; +import { Refs } from "../Refs.js"; +export type JsonSchema7SetType = { + type: 'array'; + uniqueItems: true; + items?: JsonSchema7Type | undefined; + minItems?: number; + maxItems?: number; + errorMessage?: ErrorMessages; +}; +export declare function parseSetDef(def: ZodSetDef, refs: Refs): JsonSchema7SetType; +//# sourceMappingURL=set.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/set.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/set.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..3537978950218dca732bf62cae0f298509f8d5c8 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/set.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"set.d.ts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/set.ts"],"names":[],"mappings":"OAAO,EAAE,SAAS,EAAE,MAAM,KAAK;OACxB,EAAE,aAAa,EAA6B;OAC5C,EAAE,eAAe,EAAY;OAC7B,EAAE,IAAI,EAAE;AAEf,MAAM,MAAM,kBAAkB,GAAG;IAC/B,IAAI,EAAE,OAAO,CAAC;IACd,WAAW,EAAE,IAAI,CAAC;IAClB,KAAK,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC;IACpC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,YAAY,CAAC,EAAE,aAAa,CAAC,kBAAkB,CAAC,CAAC;CAClD,CAAC;AAEF,wBAAgB,WAAW,CAAC,GAAG,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,GAAG,kBAAkB,CAqB1E"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/set.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/set.js new file mode 100644 index 0000000000000000000000000000000000000000..a3e8545276b553a3169abd0c4dfa232bab0e5e75 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/set.js @@ -0,0 +1,24 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseSetDef = parseSetDef; +const errorMessages_1 = require("../errorMessages.js"); +const parseDef_1 = require("../parseDef.js"); +function parseSetDef(def, refs) { + const items = (0, parseDef_1.parseDef)(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, 'items'], + }); + const schema = { + type: 'array', + uniqueItems: true, + items, + }; + if (def.minSize) { + (0, errorMessages_1.setResponseValueAndErrors)(schema, 'minItems', def.minSize.value, def.minSize.message, refs); + } + if (def.maxSize) { + (0, errorMessages_1.setResponseValueAndErrors)(schema, 'maxItems', def.maxSize.value, def.maxSize.message, refs); + } + return schema; +} +//# sourceMappingURL=set.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/set.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/set.js.map new file mode 100644 index 0000000000000000000000000000000000000000..8bbd1f7e526bfaddc629bdcd8fb3b61fbca469ee --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/set.js.map @@ -0,0 +1 @@ +{"version":3,"file":"set.js","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/set.ts"],"names":[],"mappings":";;AAcA,kCAqBC;AAlCD,uDAA4E;AAC5E,6CAAwD;AAYxD,SAAgB,WAAW,CAAC,GAAc,EAAE,IAAU;IACpD,MAAM,KAAK,GAAG,IAAA,mBAAQ,EAAC,GAAG,CAAC,SAAS,CAAC,IAAI,EAAE;QACzC,GAAG,IAAI;QACP,WAAW,EAAE,CAAC,GAAG,IAAI,CAAC,WAAW,EAAE,OAAO,CAAC;KAC5C,CAAC,CAAC;IAEH,MAAM,MAAM,GAAuB;QACjC,IAAI,EAAE,OAAO;QACb,WAAW,EAAE,IAAI;QACjB,KAAK;KACN,CAAC;IAEF,IAAI,GAAG,CAAC,OAAO,EAAE,CAAC;QAChB,IAAA,yCAAyB,EAAC,MAAM,EAAE,UAAU,EAAE,GAAG,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,OAAO,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;IAC9F,CAAC;IAED,IAAI,GAAG,CAAC,OAAO,EAAE,CAAC;QAChB,IAAA,yCAAyB,EAAC,MAAM,EAAE,UAAU,EAAE,GAAG,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,OAAO,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;IAC9F,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/set.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/set.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a235277f78702433448c9d0b46066964aeec8b8a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/set.mjs @@ -0,0 +1,21 @@ +import { setResponseValueAndErrors } from "../errorMessages.mjs"; +import { parseDef } from "../parseDef.mjs"; +export function parseSetDef(def, refs) { + const items = parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, 'items'], + }); + const schema = { + type: 'array', + uniqueItems: true, + items, + }; + if (def.minSize) { + setResponseValueAndErrors(schema, 'minItems', def.minSize.value, def.minSize.message, refs); + } + if (def.maxSize) { + setResponseValueAndErrors(schema, 'maxItems', def.maxSize.value, def.maxSize.message, refs); + } + return schema; +} +//# sourceMappingURL=set.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/set.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/set.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..3c6b4ad21b6500fe8c4029e6de0953efdab0e335 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/set.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"set.mjs","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/set.ts"],"names":[],"mappings":"OACO,EAAiB,yBAAyB,EAAE;OAC5C,EAAmB,QAAQ,EAAE;AAYpC,MAAM,UAAU,WAAW,CAAC,GAAc,EAAE,IAAU;IACpD,MAAM,KAAK,GAAG,QAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,EAAE;QACzC,GAAG,IAAI;QACP,WAAW,EAAE,CAAC,GAAG,IAAI,CAAC,WAAW,EAAE,OAAO,CAAC;KAC5C,CAAC,CAAC;IAEH,MAAM,MAAM,GAAuB;QACjC,IAAI,EAAE,OAAO;QACb,WAAW,EAAE,IAAI;QACjB,KAAK;KACN,CAAC;IAEF,IAAI,GAAG,CAAC,OAAO,EAAE,CAAC;QAChB,yBAAyB,CAAC,MAAM,EAAE,UAAU,EAAE,GAAG,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,OAAO,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;IAC9F,CAAC;IAED,IAAI,GAAG,CAAC,OAAO,EAAE,CAAC;QAChB,yBAAyB,CAAC,MAAM,EAAE,UAAU,EAAE,GAAG,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,OAAO,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;IAC9F,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/string.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/string.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..5baec722e092d5bc2b3391b5587a695941c0132e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/string.d.mts @@ -0,0 +1,70 @@ +import { ZodStringDef } from 'zod'; +import { ErrorMessages } from "../errorMessages.mjs"; +import { Refs } from "../Refs.mjs"; +/** + * Generated from the regular expressions found here as of 2024-05-22: + * https://github.com/colinhacks/zod/blob/master/src/types.ts. + * + * Expressions with /i flag have been changed accordingly. + */ +export declare const zodPatterns: { + /** + * `c` was changed to `[cC]` to replicate /i flag + */ + readonly cuid: RegExp; + readonly cuid2: RegExp; + readonly ulid: RegExp; + /** + * `a-z` was added to replicate /i flag + */ + readonly email: RegExp; + /** + * Constructed a valid Unicode RegExp + * + * Lazily instantiate since this type of regex isn't supported + * in all envs (e.g. React Native). + * + * See: + * https://github.com/colinhacks/zod/issues/2433 + * Fix in Zod: + * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b + */ + readonly emoji: () => RegExp; + /** + * Unused + */ + readonly uuid: RegExp; + /** + * Unused + */ + readonly ipv4: RegExp; + /** + * Unused + */ + readonly ipv6: RegExp; + readonly base64: RegExp; + readonly nanoid: RegExp; +}; +export type JsonSchema7StringType = { + type: 'string'; + minLength?: number; + maxLength?: number; + format?: 'email' | 'idn-email' | 'uri' | 'uuid' | 'date-time' | 'ipv4' | 'ipv6' | 'date' | 'time' | 'duration'; + pattern?: string; + allOf?: { + pattern: string; + errorMessage?: ErrorMessages<{ + pattern: string; + }>; + }[]; + anyOf?: { + format: string; + errorMessage?: ErrorMessages<{ + format: string; + }>; + }[]; + errorMessage?: ErrorMessages; + contentEncoding?: string; +}; +export declare function parseStringDef(def: ZodStringDef, refs: Refs): JsonSchema7StringType; +//# sourceMappingURL=string.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/string.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/string.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..cd1e699b1a6125ae1bd917ab554a899c2bc2ce3e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/string.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"string.d.mts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/string.ts"],"names":[],"mappings":"OACO,EAAE,YAAY,EAAE,MAAM,KAAK;OAC3B,EAAE,aAAa,EAA6B;OAC5C,EAAE,IAAI,EAAE;AAIf;;;;;GAKG;AACH,eAAO,MAAM,WAAW;IACtB;;OAEG;;;;IAIH;;OAEG;;IAEH;;;;;;;;;;OAUG;;IAOH;;OAEG;;IAEH;;OAEG;;IAEH;;OAEG;;;;CAIK,CAAC;AAEX,MAAM,MAAM,qBAAqB,GAAG;IAClC,IAAI,EAAE,QAAQ,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EACH,OAAO,GACP,WAAW,GACX,KAAK,GACL,MAAM,GACN,WAAW,GACX,MAAM,GACN,MAAM,GACN,MAAM,GACN,MAAM,GACN,UAAU,CAAC;IACf,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE;QACN,OAAO,EAAE,MAAM,CAAC;QAChB,YAAY,CAAC,EAAE,aAAa,CAAC;YAAE,OAAO,EAAE,MAAM,CAAA;SAAE,CAAC,CAAC;KACnD,EAAE,CAAC;IACJ,KAAK,CAAC,EAAE;QACN,MAAM,EAAE,MAAM,CAAC;QACf,YAAY,CAAC,EAAE,aAAa,CAAC;YAAE,MAAM,EAAE,MAAM,CAAA;SAAE,CAAC,CAAC;KAClD,EAAE,CAAC;IACJ,YAAY,CAAC,EAAE,aAAa,CAAC,qBAAqB,CAAC,CAAC;IACpD,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B,CAAC;AAEF,wBAAgB,cAAc,CAAC,GAAG,EAAE,YAAY,EAAE,IAAI,EAAE,IAAI,GAAG,qBAAqB,CAoJnF"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/string.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/string.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ce2e2c8eed5a072f65502ec82bb22e4974883ac9 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/string.d.ts @@ -0,0 +1,70 @@ +import { ZodStringDef } from 'zod'; +import { ErrorMessages } from "../errorMessages.js"; +import { Refs } from "../Refs.js"; +/** + * Generated from the regular expressions found here as of 2024-05-22: + * https://github.com/colinhacks/zod/blob/master/src/types.ts. + * + * Expressions with /i flag have been changed accordingly. + */ +export declare const zodPatterns: { + /** + * `c` was changed to `[cC]` to replicate /i flag + */ + readonly cuid: RegExp; + readonly cuid2: RegExp; + readonly ulid: RegExp; + /** + * `a-z` was added to replicate /i flag + */ + readonly email: RegExp; + /** + * Constructed a valid Unicode RegExp + * + * Lazily instantiate since this type of regex isn't supported + * in all envs (e.g. React Native). + * + * See: + * https://github.com/colinhacks/zod/issues/2433 + * Fix in Zod: + * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b + */ + readonly emoji: () => RegExp; + /** + * Unused + */ + readonly uuid: RegExp; + /** + * Unused + */ + readonly ipv4: RegExp; + /** + * Unused + */ + readonly ipv6: RegExp; + readonly base64: RegExp; + readonly nanoid: RegExp; +}; +export type JsonSchema7StringType = { + type: 'string'; + minLength?: number; + maxLength?: number; + format?: 'email' | 'idn-email' | 'uri' | 'uuid' | 'date-time' | 'ipv4' | 'ipv6' | 'date' | 'time' | 'duration'; + pattern?: string; + allOf?: { + pattern: string; + errorMessage?: ErrorMessages<{ + pattern: string; + }>; + }[]; + anyOf?: { + format: string; + errorMessage?: ErrorMessages<{ + format: string; + }>; + }[]; + errorMessage?: ErrorMessages; + contentEncoding?: string; +}; +export declare function parseStringDef(def: ZodStringDef, refs: Refs): JsonSchema7StringType; +//# sourceMappingURL=string.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/string.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/string.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..00c2eeb3347c42a5358c1c5ca6c7713760e5da86 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/string.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"string.d.ts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/string.ts"],"names":[],"mappings":"OACO,EAAE,YAAY,EAAE,MAAM,KAAK;OAC3B,EAAE,aAAa,EAA6B;OAC5C,EAAE,IAAI,EAAE;AAIf;;;;;GAKG;AACH,eAAO,MAAM,WAAW;IACtB;;OAEG;;;;IAIH;;OAEG;;IAEH;;;;;;;;;;OAUG;;IAOH;;OAEG;;IAEH;;OAEG;;IAEH;;OAEG;;;;CAIK,CAAC;AAEX,MAAM,MAAM,qBAAqB,GAAG;IAClC,IAAI,EAAE,QAAQ,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EACH,OAAO,GACP,WAAW,GACX,KAAK,GACL,MAAM,GACN,WAAW,GACX,MAAM,GACN,MAAM,GACN,MAAM,GACN,MAAM,GACN,UAAU,CAAC;IACf,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE;QACN,OAAO,EAAE,MAAM,CAAC;QAChB,YAAY,CAAC,EAAE,aAAa,CAAC;YAAE,OAAO,EAAE,MAAM,CAAA;SAAE,CAAC,CAAC;KACnD,EAAE,CAAC;IACJ,KAAK,CAAC,EAAE;QACN,MAAM,EAAE,MAAM,CAAC;QACf,YAAY,CAAC,EAAE,aAAa,CAAC;YAAE,MAAM,EAAE,MAAM,CAAA;SAAE,CAAC,CAAC;KAClD,EAAE,CAAC;IACJ,YAAY,CAAC,EAAE,aAAa,CAAC,qBAAqB,CAAC,CAAC;IACpD,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B,CAAC;AAEF,wBAAgB,cAAc,CAAC,GAAG,EAAE,YAAY,EAAE,IAAI,EAAE,IAAI,GAAG,qBAAqB,CAoJnF"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/string.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/string.js new file mode 100644 index 0000000000000000000000000000000000000000..54bf1582757c613702e5a7d756a1be302c2c1068 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/string.js @@ -0,0 +1,316 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.zodPatterns = void 0; +exports.parseStringDef = parseStringDef; +const errorMessages_1 = require("../errorMessages.js"); +let emojiRegex; +/** + * Generated from the regular expressions found here as of 2024-05-22: + * https://github.com/colinhacks/zod/blob/master/src/types.ts. + * + * Expressions with /i flag have been changed accordingly. + */ +exports.zodPatterns = { + /** + * `c` was changed to `[cC]` to replicate /i flag + */ + cuid: /^[cC][^\s-]{8,}$/, + cuid2: /^[0-9a-z]+$/, + ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/, + /** + * `a-z` was added to replicate /i flag + */ + email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/, + /** + * Constructed a valid Unicode RegExp + * + * Lazily instantiate since this type of regex isn't supported + * in all envs (e.g. React Native). + * + * See: + * https://github.com/colinhacks/zod/issues/2433 + * Fix in Zod: + * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b + */ + emoji: () => { + if (emojiRegex === undefined) { + emojiRegex = RegExp('^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$', 'u'); + } + return emojiRegex; + }, + /** + * Unused + */ + uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/, + /** + * Unused + */ + ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/, + /** + * Unused + */ + ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, + base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, + nanoid: /^[a-zA-Z0-9_-]{21}$/, +}; +function parseStringDef(def, refs) { + const res = { + type: 'string', + }; + function processPattern(value) { + return refs.patternStrategy === 'escape' ? escapeNonAlphaNumeric(value) : value; + } + if (def.checks) { + for (const check of def.checks) { + switch (check.kind) { + case 'min': + (0, errorMessages_1.setResponseValueAndErrors)(res, 'minLength', typeof res.minLength === 'number' ? Math.max(res.minLength, check.value) : check.value, check.message, refs); + break; + case 'max': + (0, errorMessages_1.setResponseValueAndErrors)(res, 'maxLength', typeof res.maxLength === 'number' ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); + break; + case 'email': + switch (refs.emailStrategy) { + case 'format:email': + addFormat(res, 'email', check.message, refs); + break; + case 'format:idn-email': + addFormat(res, 'idn-email', check.message, refs); + break; + case 'pattern:zod': + addPattern(res, exports.zodPatterns.email, check.message, refs); + break; + } + break; + case 'url': + addFormat(res, 'uri', check.message, refs); + break; + case 'uuid': + addFormat(res, 'uuid', check.message, refs); + break; + case 'regex': + addPattern(res, check.regex, check.message, refs); + break; + case 'cuid': + addPattern(res, exports.zodPatterns.cuid, check.message, refs); + break; + case 'cuid2': + addPattern(res, exports.zodPatterns.cuid2, check.message, refs); + break; + case 'startsWith': + addPattern(res, RegExp(`^${processPattern(check.value)}`), check.message, refs); + break; + case 'endsWith': + addPattern(res, RegExp(`${processPattern(check.value)}$`), check.message, refs); + break; + case 'datetime': + addFormat(res, 'date-time', check.message, refs); + break; + case 'date': + addFormat(res, 'date', check.message, refs); + break; + case 'time': + addFormat(res, 'time', check.message, refs); + break; + case 'duration': + addFormat(res, 'duration', check.message, refs); + break; + case 'length': + (0, errorMessages_1.setResponseValueAndErrors)(res, 'minLength', typeof res.minLength === 'number' ? Math.max(res.minLength, check.value) : check.value, check.message, refs); + (0, errorMessages_1.setResponseValueAndErrors)(res, 'maxLength', typeof res.maxLength === 'number' ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); + break; + case 'includes': { + addPattern(res, RegExp(processPattern(check.value)), check.message, refs); + break; + } + case 'ip': { + if (check.version !== 'v6') { + addFormat(res, 'ipv4', check.message, refs); + } + if (check.version !== 'v4') { + addFormat(res, 'ipv6', check.message, refs); + } + break; + } + case 'emoji': + addPattern(res, exports.zodPatterns.emoji, check.message, refs); + break; + case 'ulid': { + addPattern(res, exports.zodPatterns.ulid, check.message, refs); + break; + } + case 'base64': { + switch (refs.base64Strategy) { + case 'format:binary': { + addFormat(res, 'binary', check.message, refs); + break; + } + case 'contentEncoding:base64': { + (0, errorMessages_1.setResponseValueAndErrors)(res, 'contentEncoding', 'base64', check.message, refs); + break; + } + case 'pattern:zod': { + addPattern(res, exports.zodPatterns.base64, check.message, refs); + break; + } + } + break; + } + case 'nanoid': { + addPattern(res, exports.zodPatterns.nanoid, check.message, refs); + } + case 'toLowerCase': + case 'toUpperCase': + case 'trim': + break; + default: + ((_) => { })(check); + } + } + } + return res; +} +const escapeNonAlphaNumeric = (value) => Array.from(value) + .map((c) => (/[a-zA-Z0-9]/.test(c) ? c : `\\${c}`)) + .join(''); +const addFormat = (schema, value, message, refs) => { + if (schema.format || schema.anyOf?.some((x) => x.format)) { + if (!schema.anyOf) { + schema.anyOf = []; + } + if (schema.format) { + schema.anyOf.push({ + format: schema.format, + ...(schema.errorMessage && + refs.errorMessages && { + errorMessage: { format: schema.errorMessage.format }, + }), + }); + delete schema.format; + if (schema.errorMessage) { + delete schema.errorMessage.format; + if (Object.keys(schema.errorMessage).length === 0) { + delete schema.errorMessage; + } + } + } + schema.anyOf.push({ + format: value, + ...(message && refs.errorMessages && { errorMessage: { format: message } }), + }); + } + else { + (0, errorMessages_1.setResponseValueAndErrors)(schema, 'format', value, message, refs); + } +}; +const addPattern = (schema, regex, message, refs) => { + if (schema.pattern || schema.allOf?.some((x) => x.pattern)) { + if (!schema.allOf) { + schema.allOf = []; + } + if (schema.pattern) { + schema.allOf.push({ + pattern: schema.pattern, + ...(schema.errorMessage && + refs.errorMessages && { + errorMessage: { pattern: schema.errorMessage.pattern }, + }), + }); + delete schema.pattern; + if (schema.errorMessage) { + delete schema.errorMessage.pattern; + if (Object.keys(schema.errorMessage).length === 0) { + delete schema.errorMessage; + } + } + } + schema.allOf.push({ + pattern: processRegExp(regex, refs), + ...(message && refs.errorMessages && { errorMessage: { pattern: message } }), + }); + } + else { + (0, errorMessages_1.setResponseValueAndErrors)(schema, 'pattern', processRegExp(regex, refs), message, refs); + } +}; +// Mutate z.string.regex() in a best attempt to accommodate for regex flags when applyRegexFlags is true +const processRegExp = (regexOrFunction, refs) => { + const regex = typeof regexOrFunction === 'function' ? regexOrFunction() : regexOrFunction; + if (!refs.applyRegexFlags || !regex.flags) + return regex.source; + // Currently handled flags + const flags = { + i: regex.flags.includes('i'), // Case-insensitive + m: regex.flags.includes('m'), // `^` and `$` matches adjacent to newline characters + s: regex.flags.includes('s'), // `.` matches newlines + }; + // The general principle here is to step through each character, one at a time, applying mutations as flags require. We keep track when the current character is escaped, and when it's inside a group /like [this]/ or (also) a range like /[a-z]/. The following is fairly brittle imperative code; edit at your peril! + const source = flags.i ? regex.source.toLowerCase() : regex.source; + let pattern = ''; + let isEscaped = false; + let inCharGroup = false; + let inCharRange = false; + for (let i = 0; i < source.length; i++) { + if (isEscaped) { + pattern += source[i]; + isEscaped = false; + continue; + } + if (flags.i) { + if (inCharGroup) { + if (source[i].match(/[a-z]/)) { + if (inCharRange) { + pattern += source[i]; + pattern += `${source[i - 2]}-${source[i]}`.toUpperCase(); + inCharRange = false; + } + else if (source[i + 1] === '-' && source[i + 2]?.match(/[a-z]/)) { + pattern += source[i]; + inCharRange = true; + } + else { + pattern += `${source[i]}${source[i].toUpperCase()}`; + } + continue; + } + } + else if (source[i].match(/[a-z]/)) { + pattern += `[${source[i]}${source[i].toUpperCase()}]`; + continue; + } + } + if (flags.m) { + if (source[i] === '^') { + pattern += `(^|(?<=[\r\n]))`; + continue; + } + else if (source[i] === '$') { + pattern += `($|(?=[\r\n]))`; + continue; + } + } + if (flags.s && source[i] === '.') { + pattern += inCharGroup ? `${source[i]}\r\n` : `[${source[i]}\r\n]`; + continue; + } + pattern += source[i]; + if (source[i] === '\\') { + isEscaped = true; + } + else if (inCharGroup && source[i] === ']') { + inCharGroup = false; + } + else if (!inCharGroup && source[i] === '[') { + inCharGroup = true; + } + } + try { + const regexTest = new RegExp(pattern); + } + catch { + console.warn(`Could not convert regex pattern at ${refs.currentPath.join('/')} to a flag-independent form! Falling back to the flag-ignorant source`); + return regex.source; + } + return pattern; +}; +//# sourceMappingURL=string.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/string.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/string.js.map new file mode 100644 index 0000000000000000000000000000000000000000..857d1f39d2f2d5dbf073be2bb45054ada62369c6 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/string.js.map @@ -0,0 +1 @@ +{"version":3,"file":"string.js","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/string.ts"],"names":[],"mappings":";;;AAqFA,wCAoJC;AAvOD,uDAA4E;AAG5E,IAAI,UAA8B,CAAC;AAEnC;;;;;GAKG;AACU,QAAA,WAAW,GAAG;IACzB;;OAEG;IACH,IAAI,EAAE,kBAAkB;IACxB,KAAK,EAAE,aAAa;IACpB,IAAI,EAAE,0BAA0B;IAChC;;OAEG;IACH,KAAK,EAAE,kGAAkG;IACzG;;;;;;;;;;OAUG;IACH,KAAK,EAAE,GAAG,EAAE;QACV,IAAI,UAAU,KAAK,SAAS,EAAE,CAAC;YAC7B,UAAU,GAAG,MAAM,CAAC,sDAAsD,EAAE,GAAG,CAAC,CAAC;QACnF,CAAC;QACD,OAAO,UAAU,CAAC;IACpB,CAAC;IACD;;OAEG;IACH,IAAI,EAAE,uFAAuF;IAC7F;;OAEG;IACH,IAAI,EAAE,qHAAqH;IAC3H;;OAEG;IACH,IAAI,EAAE,8XAA8X;IACpY,MAAM,EAAE,kEAAkE;IAC1E,MAAM,EAAE,qBAAqB;CACrB,CAAC;AA8BX,SAAgB,cAAc,CAAC,GAAiB,EAAE,IAAU;IAC1D,MAAM,GAAG,GAA0B;QACjC,IAAI,EAAE,QAAQ;KACf,CAAC;IAEF,SAAS,cAAc,CAAC,KAAa;QACnC,OAAO,IAAI,CAAC,eAAe,KAAK,QAAQ,CAAC,CAAC,CAAC,qBAAqB,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;IAClF,CAAC;IAED,IAAI,GAAG,CAAC,MAAM,EAAE,CAAC;QACf,KAAK,MAAM,KAAK,IAA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CAAC;QACF,OAAO,KAAK,CAAC,MAAM,CAAC;IACtB,CAAC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/string.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/string.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0eb601495a8fa95c3f44dc40c2b957967945b28e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/string.mjs @@ -0,0 +1,312 @@ +import { setResponseValueAndErrors } from "../errorMessages.mjs"; +let emojiRegex; +/** + * Generated from the regular expressions found here as of 2024-05-22: + * https://github.com/colinhacks/zod/blob/master/src/types.ts. + * + * Expressions with /i flag have been changed accordingly. + */ +export const zodPatterns = { + /** + * `c` was changed to `[cC]` to replicate /i flag + */ + cuid: /^[cC][^\s-]{8,}$/, + cuid2: /^[0-9a-z]+$/, + ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/, + /** + * `a-z` was added to replicate /i flag + */ + email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/, + /** + * Constructed a valid Unicode RegExp + * + * Lazily instantiate since this type of regex isn't supported + * in all envs (e.g. React Native). + * + * See: + * https://github.com/colinhacks/zod/issues/2433 + * Fix in Zod: + * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b + */ + emoji: () => { + if (emojiRegex === undefined) { + emojiRegex = RegExp('^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$', 'u'); + } + return emojiRegex; + }, + /** + * Unused + */ + uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/, + /** + * Unused + */ + ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/, + /** + * Unused + */ + ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, + base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, + nanoid: /^[a-zA-Z0-9_-]{21}$/, +}; +export function parseStringDef(def, refs) { + const res = { + type: 'string', + }; + function processPattern(value) { + return refs.patternStrategy === 'escape' ? escapeNonAlphaNumeric(value) : value; + } + if (def.checks) { + for (const check of def.checks) { + switch (check.kind) { + case 'min': + setResponseValueAndErrors(res, 'minLength', typeof res.minLength === 'number' ? Math.max(res.minLength, check.value) : check.value, check.message, refs); + break; + case 'max': + setResponseValueAndErrors(res, 'maxLength', typeof res.maxLength === 'number' ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); + break; + case 'email': + switch (refs.emailStrategy) { + case 'format:email': + addFormat(res, 'email', check.message, refs); + break; + case 'format:idn-email': + addFormat(res, 'idn-email', check.message, refs); + break; + case 'pattern:zod': + addPattern(res, zodPatterns.email, check.message, refs); + break; + } + break; + case 'url': + addFormat(res, 'uri', check.message, refs); + break; + case 'uuid': + addFormat(res, 'uuid', check.message, refs); + break; + case 'regex': + addPattern(res, check.regex, check.message, refs); + break; + case 'cuid': + addPattern(res, zodPatterns.cuid, check.message, refs); + break; + case 'cuid2': + addPattern(res, zodPatterns.cuid2, check.message, refs); + break; + case 'startsWith': + addPattern(res, RegExp(`^${processPattern(check.value)}`), check.message, refs); + break; + case 'endsWith': + addPattern(res, RegExp(`${processPattern(check.value)}$`), check.message, refs); + break; + case 'datetime': + addFormat(res, 'date-time', check.message, refs); + break; + case 'date': + addFormat(res, 'date', check.message, refs); + break; + case 'time': + addFormat(res, 'time', check.message, refs); + break; + case 'duration': + addFormat(res, 'duration', check.message, refs); + break; + case 'length': + setResponseValueAndErrors(res, 'minLength', typeof res.minLength === 'number' ? Math.max(res.minLength, check.value) : check.value, check.message, refs); + setResponseValueAndErrors(res, 'maxLength', typeof res.maxLength === 'number' ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); + break; + case 'includes': { + addPattern(res, RegExp(processPattern(check.value)), check.message, refs); + break; + } + case 'ip': { + if (check.version !== 'v6') { + addFormat(res, 'ipv4', check.message, refs); + } + if (check.version !== 'v4') { + addFormat(res, 'ipv6', check.message, refs); + } + break; + } + case 'emoji': + addPattern(res, zodPatterns.emoji, check.message, refs); + break; + case 'ulid': { + addPattern(res, zodPatterns.ulid, check.message, refs); + break; + } + case 'base64': { + switch (refs.base64Strategy) { + case 'format:binary': { + addFormat(res, 'binary', check.message, refs); + break; + } + case 'contentEncoding:base64': { + setResponseValueAndErrors(res, 'contentEncoding', 'base64', check.message, refs); + break; + } + case 'pattern:zod': { + addPattern(res, zodPatterns.base64, check.message, refs); + break; + } + } + break; + } + case 'nanoid': { + addPattern(res, zodPatterns.nanoid, check.message, refs); + } + case 'toLowerCase': + case 'toUpperCase': + case 'trim': + break; + default: + ((_) => { })(check); + } + } + } + return res; +} +const escapeNonAlphaNumeric = (value) => Array.from(value) + .map((c) => (/[a-zA-Z0-9]/.test(c) ? c : `\\${c}`)) + .join(''); +const addFormat = (schema, value, message, refs) => { + if (schema.format || schema.anyOf?.some((x) => x.format)) { + if (!schema.anyOf) { + schema.anyOf = []; + } + if (schema.format) { + schema.anyOf.push({ + format: schema.format, + ...(schema.errorMessage && + refs.errorMessages && { + errorMessage: { format: schema.errorMessage.format }, + }), + }); + delete schema.format; + if (schema.errorMessage) { + delete schema.errorMessage.format; + if (Object.keys(schema.errorMessage).length === 0) { + delete schema.errorMessage; + } + } + } + schema.anyOf.push({ + format: value, + ...(message && refs.errorMessages && { errorMessage: { format: message } }), + }); + } + else { + setResponseValueAndErrors(schema, 'format', value, message, refs); + } +}; +const addPattern = (schema, regex, message, refs) => { + if (schema.pattern || schema.allOf?.some((x) => x.pattern)) { + if (!schema.allOf) { + schema.allOf = []; + } + if (schema.pattern) { + schema.allOf.push({ + pattern: schema.pattern, + ...(schema.errorMessage && + refs.errorMessages && { + errorMessage: { pattern: schema.errorMessage.pattern }, + }), + }); + delete schema.pattern; + if (schema.errorMessage) { + delete schema.errorMessage.pattern; + if (Object.keys(schema.errorMessage).length === 0) { + delete schema.errorMessage; + } + } + } + schema.allOf.push({ + pattern: processRegExp(regex, refs), + ...(message && refs.errorMessages && { errorMessage: { pattern: message } }), + }); + } + else { + setResponseValueAndErrors(schema, 'pattern', processRegExp(regex, refs), message, refs); + } +}; +// Mutate z.string.regex() in a best attempt to accommodate for regex flags when applyRegexFlags is true +const processRegExp = (regexOrFunction, refs) => { + const regex = typeof regexOrFunction === 'function' ? regexOrFunction() : regexOrFunction; + if (!refs.applyRegexFlags || !regex.flags) + return regex.source; + // Currently handled flags + const flags = { + i: regex.flags.includes('i'), // Case-insensitive + m: regex.flags.includes('m'), // `^` and `$` matches adjacent to newline characters + s: regex.flags.includes('s'), // `.` matches newlines + }; + // The general principle here is to step through each character, one at a time, applying mutations as flags require. We keep track when the current character is escaped, and when it's inside a group /like [this]/ or (also) a range like /[a-z]/. The following is fairly brittle imperative code; edit at your peril! + const source = flags.i ? regex.source.toLowerCase() : regex.source; + let pattern = ''; + let isEscaped = false; + let inCharGroup = false; + let inCharRange = false; + for (let i = 0; i < source.length; i++) { + if (isEscaped) { + pattern += source[i]; + isEscaped = false; + continue; + } + if (flags.i) { + if (inCharGroup) { + if (source[i].match(/[a-z]/)) { + if (inCharRange) { + pattern += source[i]; + pattern += `${source[i - 2]}-${source[i]}`.toUpperCase(); + inCharRange = false; + } + else if (source[i + 1] === '-' && source[i + 2]?.match(/[a-z]/)) { + pattern += source[i]; + inCharRange = true; + } + else { + pattern += `${source[i]}${source[i].toUpperCase()}`; + } + continue; + } + } + else if (source[i].match(/[a-z]/)) { + pattern += `[${source[i]}${source[i].toUpperCase()}]`; + continue; + } + } + if (flags.m) { + if (source[i] === '^') { + pattern += `(^|(?<=[\r\n]))`; + continue; + } + else if (source[i] === '$') { + pattern += `($|(?=[\r\n]))`; + continue; + } + } + if (flags.s && source[i] === '.') { + pattern += inCharGroup ? `${source[i]}\r\n` : `[${source[i]}\r\n]`; + continue; + } + pattern += source[i]; + if (source[i] === '\\') { + isEscaped = true; + } + else if (inCharGroup && source[i] === ']') { + inCharGroup = false; + } + else if (!inCharGroup && source[i] === '[') { + inCharGroup = true; + } + } + try { + const regexTest = new RegExp(pattern); + } + catch { + console.warn(`Could not convert regex pattern at ${refs.currentPath.join('/')} to a flag-independent form! Falling back to the flag-ignorant source`); + return regex.source; + } + return pattern; +}; +//# sourceMappingURL=string.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/string.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/string.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..a5f058c41d3e705e99e56e41ec63fcfddb0dac27 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/string.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"string.mjs","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/string.ts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AE,CAAC;gBAC7B,OAAO,IAAI,gBAAgB,CAAC;gBAC5B,SAAS;YACX,CAAC;QACH,CAAC;QAED,IAAI,KAAK,CAAC,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE,CAAC;YACjC,OAAO,IAAI,WAAW,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC;YACnE,SAAS;QACX,CAAC;QAED,OAAO,IAAI,MAAM,CAAC,CAAC,CAAC,CAAC;QACrB,IAAI,MAAM,CAAC,CAAC,CAAC,KAAK,IAAI,EAAE,CAAC;YACvB,SAAS,GAAG,IAAI,CAAC;QACnB,CAAC;aAAM,IAAI,WAAW,IAAI,MAAM,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE,CAAC;YAC5C,WAAW,GAAG,KAAK,CAAC;QACtB,CAAC;aAAM,IAAI,CAAC,WAAW,IAAI,MAAM,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE,CAAC;YAC7C,WAAW,GAAG,IAAI,CAAC;QACrB,CAAC;IACH,CAAC;IAED,IAAI,CAAC;QACH,MAAM,SAAS,GAAG,IAAI,MAAM,CAAC,OAAO,CAAC,CAAC;IACxC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,CAAC,IAAI,CACV,sCAAsC,IAAI,CAAC,WAAW,CAAC,IAAI,CACzD,GAAG,CACJ,uEAAuE,CACzE,CAAC;QACF,OAAO,KAAK,CAAC,MAAM,CAAC;IACtB,CAAC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/tuple.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/tuple.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..9eecf3c33659defcf2b30ca86cf4742912954294 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/tuple.d.mts @@ -0,0 +1,14 @@ +import { ZodTupleDef, ZodTupleItems, ZodTypeAny } from 'zod'; +import { JsonSchema7Type } from "../parseDef.mjs"; +import { Refs } from "../Refs.mjs"; +export type JsonSchema7TupleType = { + type: 'array'; + minItems: number; + items: JsonSchema7Type[]; +} & ({ + maxItems: number; +} | { + additionalItems?: JsonSchema7Type | undefined; +}); +export declare function parseTupleDef(def: ZodTupleDef, refs: Refs): JsonSchema7TupleType; +//# sourceMappingURL=tuple.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/tuple.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/tuple.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..edff208d45d4d279366988d3b5a75beac4b69a34 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/tuple.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"tuple.d.mts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/tuple.ts"],"names":[],"mappings":"OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,KAAK;OACrD,EAAE,eAAe,EAAY;OAC7B,EAAE,IAAI,EAAE;AAEf,MAAM,MAAM,oBAAoB,GAAG;IACjC,IAAI,EAAE,OAAO,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,eAAe,EAAE,CAAC;CAC1B,GAAG,CACA;IACE,QAAQ,EAAE,MAAM,CAAC;CAClB,GACD;IACE,eAAe,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC;CAC/C,CACJ,CAAC;AAEF,wBAAgB,aAAa,CAC3B,GAAG,EAAE,WAAW,CAAC,aAAa,GAAG,EAAE,EAAE,UAAU,GAAG,IAAI,CAAC,EACvD,IAAI,EAAE,IAAI,GACT,oBAAoB,CAiCtB"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/tuple.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/tuple.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..06cb1b7343ef13408d32d1412fd1ed4d02b60ca3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/tuple.d.ts @@ -0,0 +1,14 @@ +import { ZodTupleDef, ZodTupleItems, ZodTypeAny } from 'zod'; +import { JsonSchema7Type } from "../parseDef.js"; +import { Refs } from "../Refs.js"; +export type JsonSchema7TupleType = { + type: 'array'; + minItems: number; + items: JsonSchema7Type[]; +} & ({ + maxItems: number; +} | { + additionalItems?: JsonSchema7Type | undefined; +}); +export declare function parseTupleDef(def: ZodTupleDef, refs: Refs): JsonSchema7TupleType; +//# sourceMappingURL=tuple.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/tuple.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/tuple.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..e7cab4ac5885d415825ca11b01af2c5d26de713c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/tuple.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"tuple.d.ts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/tuple.ts"],"names":[],"mappings":"OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,KAAK;OACrD,EAAE,eAAe,EAAY;OAC7B,EAAE,IAAI,EAAE;AAEf,MAAM,MAAM,oBAAoB,GAAG;IACjC,IAAI,EAAE,OAAO,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,eAAe,EAAE,CAAC;CAC1B,GAAG,CACA;IACE,QAAQ,EAAE,MAAM,CAAC;CAClB,GACD;IACE,eAAe,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC;CAC/C,CACJ,CAAC;AAEF,wBAAgB,aAAa,CAC3B,GAAG,EAAE,WAAW,CAAC,aAAa,GAAG,EAAE,EAAE,UAAU,GAAG,IAAI,CAAC,EACvD,IAAI,EAAE,IAAI,GACT,oBAAoB,CAiCtB"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/tuple.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/tuple.js new file mode 100644 index 0000000000000000000000000000000000000000..35980cb96c3d764258e36db690e268e55279b5f8 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/tuple.js @@ -0,0 +1,36 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseTupleDef = parseTupleDef; +const parseDef_1 = require("../parseDef.js"); +function parseTupleDef(def, refs) { + if (def.rest) { + return { + type: 'array', + minItems: def.items.length, + items: def.items + .map((x, i) => (0, parseDef_1.parseDef)(x._def, { + ...refs, + currentPath: [...refs.currentPath, 'items', `${i}`], + })) + .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []), + additionalItems: (0, parseDef_1.parseDef)(def.rest._def, { + ...refs, + currentPath: [...refs.currentPath, 'additionalItems'], + }), + }; + } + else { + return { + type: 'array', + minItems: def.items.length, + maxItems: def.items.length, + items: def.items + .map((x, i) => (0, parseDef_1.parseDef)(x._def, { + ...refs, + currentPath: [...refs.currentPath, 'items', `${i}`], + })) + .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []), + }; + } +} +//# sourceMappingURL=tuple.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/tuple.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/tuple.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ce7994ef854fa0765133c72311e0ed3fd600f0c3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/tuple.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tuple.js","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/tuple.ts"],"names":[],"mappings":";;AAiBA,sCAoCC;AApDD,6CAAwD;AAgBxD,SAAgB,aAAa,CAC3B,GAAuD,EACvD,IAAU;IAEV,IAAI,GAAG,CAAC,IAAI,EAAE,CAAC;QACb,OAAO;YACL,IAAI,EAAE,OAAO;YACb,QAAQ,EAAE,GAAG,CAAC,KAAK,CAAC,MAAM;YAC1B,KAAK,EAAE,GAAG,CAAC,KAAK;iBACb,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CACZ,IAAA,mBAAQ,EAAC,CAAC,CAAC,IAAI,EAAE;gBACf,GAAG,IAAI;gBACP,WAAW,EAAE,CAAC,GAAG,IAAI,CAAC,WAAW,EAAE,OAAO,EAAE,GAAG,CAAC,EAAE,CAAC;aACpD,CAAC,CACH;iBACA,MAAM,CAAC,CAAC,GAAsB,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,GAAG,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;YACnF,eAAe,EAAE,IAAA,mBAAQ,EAAC,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE;gBACvC,GAAG,IAAI;gBACP,WAAW,EAAE,CAAC,GAAG,IAAI,CAAC,WAAW,EAAE,iBAAiB,CAAC;aACtD,CAAC;SACH,CAAC;IACJ,CAAC;SAAM,CAAC;QACN,OAAO;YACL,IAAI,EAAE,OAAO;YACb,QAAQ,EAAE,GAAG,CAAC,KAAK,CAAC,MAAM;YAC1B,QAAQ,EAAE,GAAG,CAAC,KAAK,CAAC,MAAM;YAC1B,KAAK,EAAE,GAAG,CAAC,KAAK;iBACb,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CACZ,IAAA,mBAAQ,EAAC,CAAC,CAAC,IAAI,EAAE;gBACf,GAAG,IAAI;gBACP,WAAW,EAAE,CAAC,GAAG,IAAI,CAAC,WAAW,EAAE,OAAO,EAAE,GAAG,CAAC,EAAE,CAAC;aACpD,CAAC,CACH;iBACA,MAAM,CAAC,CAAC,GAAsB,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,GAAG,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;SACpF,CAAC;IACJ,CAAC;AACH,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/tuple.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/tuple.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0acec70c10734838de224e1f7377e0ad428e2e06 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/tuple.mjs @@ -0,0 +1,33 @@ +import { parseDef } from "../parseDef.mjs"; +export function parseTupleDef(def, refs) { + if (def.rest) { + return { + type: 'array', + minItems: def.items.length, + items: def.items + .map((x, i) => parseDef(x._def, { + ...refs, + currentPath: [...refs.currentPath, 'items', `${i}`], + })) + .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []), + additionalItems: parseDef(def.rest._def, { + ...refs, + currentPath: [...refs.currentPath, 'additionalItems'], + }), + }; + } + else { + return { + type: 'array', + minItems: def.items.length, + maxItems: def.items.length, + items: def.items + .map((x, i) => parseDef(x._def, { + ...refs, + currentPath: [...refs.currentPath, 'items', `${i}`], + })) + .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []), + }; + } +} +//# sourceMappingURL=tuple.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/tuple.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/tuple.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..8d9f7d5f0c29b8f153d36cb38fb800f5c0cde7a5 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/tuple.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"tuple.mjs","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/tuple.ts"],"names":[],"mappings":"OACO,EAAmB,QAAQ,EAAE;AAgBpC,MAAM,UAAU,aAAa,CAC3B,GAAuD,EACvD,IAAU;IAEV,IAAI,GAAG,CAAC,IAAI,EAAE,CAAC;QACb,OAAO;YACL,IAAI,EAAE,OAAO;YACb,QAAQ,EAAE,GAAG,CAAC,KAAK,CAAC,MAAM;YAC1B,KAAK,EAAE,GAAG,CAAC,KAAK;iBACb,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CACZ,QAAQ,CAAC,CAAC,CAAC,IAAI,EAAE;gBACf,GAAG,IAAI;gBACP,WAAW,EAAE,CAAC,GAAG,IAAI,CAAC,WAAW,EAAE,OAAO,EAAE,GAAG,CAAC,EAAE,CAAC;aACpD,CAAC,CACH;iBACA,MAAM,CAAC,CAAC,GAAsB,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,GAAG,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;YACnF,eAAe,EAAE,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE;gBACvC,GAAG,IAAI;gBACP,WAAW,EAAE,CAAC,GAAG,IAAI,CAAC,WAAW,EAAE,iBAAiB,CAAC;aACtD,CAAC;SACH,CAAC;IACJ,CAAC;SAAM,CAAC;QACN,OAAO;YACL,IAAI,EAAE,OAAO;YACb,QAAQ,EAAE,GAAG,CAAC,KAAK,CAAC,MAAM;YAC1B,QAAQ,EAAE,GAAG,CAAC,KAAK,CAAC,MAAM;YAC1B,KAAK,EAAE,GAAG,CAAC,KAAK;iBACb,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CACZ,QAAQ,CAAC,CAAC,CAAC,IAAI,EAAE;gBACf,GAAG,IAAI;gBACP,WAAW,EAAE,CAAC,GAAG,IAAI,CAAC,WAAW,EAAE,OAAO,EAAE,GAAG,CAAC,EAAE,CAAC;aACpD,CAAC,CACH;iBACA,MAAM,CAAC,CAAC,GAAsB,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,GAAG,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;SACpF,CAAC;IACJ,CAAC;AACH,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/undefined.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/undefined.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..22c235b99f3981a58d02725311c5f96d0a1f1d83 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/undefined.d.mts @@ -0,0 +1,5 @@ +export type JsonSchema7UndefinedType = { + not: {}; +}; +export declare function parseUndefinedDef(): JsonSchema7UndefinedType; +//# sourceMappingURL=undefined.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/undefined.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/undefined.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..909455c3cc613faee5aa76e1a5cacc9029a63383 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/undefined.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"undefined.d.mts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/undefined.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,wBAAwB,GAAG;IACrC,GAAG,EAAE,EAAE,CAAC;CACT,CAAC;AAEF,wBAAgB,iBAAiB,IAAI,wBAAwB,CAI5D"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/undefined.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/undefined.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..95df6013494589ee146afc31e379878b64a11269 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/undefined.d.ts @@ -0,0 +1,5 @@ +export type JsonSchema7UndefinedType = { + not: {}; +}; +export declare function parseUndefinedDef(): JsonSchema7UndefinedType; +//# sourceMappingURL=undefined.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/undefined.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/undefined.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..f1358a0a2965081fd49ca271a95fef64c2940bd5 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/undefined.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"undefined.d.ts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/undefined.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,wBAAwB,GAAG;IACrC,GAAG,EAAE,EAAE,CAAC;CACT,CAAC;AAEF,wBAAgB,iBAAiB,IAAI,wBAAwB,CAI5D"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/undefined.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/undefined.js new file mode 100644 index 0000000000000000000000000000000000000000..40ea4929320200d08376152078a02b792746b1be --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/undefined.js @@ -0,0 +1,9 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseUndefinedDef = parseUndefinedDef; +function parseUndefinedDef() { + return { + not: {}, + }; +} +//# sourceMappingURL=undefined.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/undefined.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/undefined.js.map new file mode 100644 index 0000000000000000000000000000000000000000..3fc44dca31ba11f78a3da9f31077c9ba2dd26f94 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/undefined.js.map @@ -0,0 +1 @@ +{"version":3,"file":"undefined.js","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/undefined.ts"],"names":[],"mappings":";;AAIA,8CAIC;AAJD,SAAgB,iBAAiB;IAC/B,OAAO;QACL,GAAG,EAAE,EAAE;KACR,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/undefined.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/undefined.mjs new file mode 100644 index 0000000000000000000000000000000000000000..32ecd26ea94d0af2f2000bd6cfcfcbe899a45413 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/undefined.mjs @@ -0,0 +1,6 @@ +export function parseUndefinedDef() { + return { + not: {}, + }; +} +//# sourceMappingURL=undefined.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/undefined.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/undefined.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..01706a8ac241c955a56f163032e45e5091bdc74e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/undefined.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"undefined.mjs","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/undefined.ts"],"names":[],"mappings":"AAIA,MAAM,UAAU,iBAAiB;IAC/B,OAAO;QACL,GAAG,EAAE,EAAE;KACR,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/union.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/union.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..3d9a91f8c6c0e10305141a530b96db90b4298d73 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/union.d.mts @@ -0,0 +1,24 @@ +import { ZodDiscriminatedUnionDef, ZodUnionDef } from 'zod'; +import { JsonSchema7Type } from "../parseDef.mjs"; +import { Refs } from "../Refs.mjs"; +export declare const primitiveMappings: { + readonly ZodString: "string"; + readonly ZodNumber: "number"; + readonly ZodBigInt: "integer"; + readonly ZodBoolean: "boolean"; + readonly ZodNull: "null"; +}; +type JsonSchema7Primitive = (typeof primitiveMappings)[keyof typeof primitiveMappings]; +export type JsonSchema7UnionType = JsonSchema7PrimitiveUnionType | JsonSchema7AnyOfType; +type JsonSchema7PrimitiveUnionType = { + type: JsonSchema7Primitive | JsonSchema7Primitive[]; +} | { + type: JsonSchema7Primitive | JsonSchema7Primitive[]; + enum: (string | number | bigint | boolean | null)[]; +}; +type JsonSchema7AnyOfType = { + anyOf: JsonSchema7Type[]; +}; +export declare function parseUnionDef(def: ZodUnionDef | ZodDiscriminatedUnionDef, refs: Refs): JsonSchema7PrimitiveUnionType | JsonSchema7AnyOfType | undefined; +export {}; +//# sourceMappingURL=union.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/union.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/union.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..0be57676d99c9ba1f066388d59e44436a639d17f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/union.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"union.d.mts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/union.ts"],"names":[],"mappings":"OAAO,EAAE,wBAAwB,EAA6B,WAAW,EAAE,MAAM,KAAK;OAC/E,EAAE,eAAe,EAAY;OAC7B,EAAE,IAAI,EAAE;AAEf,eAAO,MAAM,iBAAiB;;;;;;CAMpB,CAAC;AAEX,KAAK,oBAAoB,GAAG,CAAC,OAAO,iBAAiB,CAAC,CAAC,MAAM,OAAO,iBAAiB,CAAC,CAAC;AAEvF,MAAM,MAAM,oBAAoB,GAAG,6BAA6B,GAAG,oBAAoB,CAAC;AAExF,KAAK,6BAA6B,GAC9B;IACE,IAAI,EAAE,oBAAoB,GAAG,oBAAoB,EAAE,CAAC;CACrD,GACD;IACE,IAAI,EAAE,oBAAoB,GAAG,oBAAoB,EAAE,CAAC;IACpD,IAAI,EAAE,CAAC,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,IAAI,CAAC,EAAE,CAAC;CACrD,CAAC;AAEN,KAAK,oBAAoB,GAAG;IAC1B,KAAK,EAAE,eAAe,EAAE,CAAC;CAC1B,CAAC;AAEF,wBAAgB,aAAa,CAC3B,GAAG,EAAE,WAAW,GAAG,wBAAwB,CAAC,GAAG,EAAE,GAAG,CAAC,EACrD,IAAI,EAAE,IAAI,GACT,6BAA6B,GAAG,oBAAoB,GAAG,SAAS,CAmElE"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/union.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/union.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..64178d4d12b98d292c9e6c89c1bcd41db9b8bd10 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/union.d.ts @@ -0,0 +1,24 @@ +import { ZodDiscriminatedUnionDef, ZodUnionDef } from 'zod'; +import { JsonSchema7Type } from "../parseDef.js"; +import { Refs } from "../Refs.js"; +export declare const primitiveMappings: { + readonly ZodString: "string"; + readonly ZodNumber: "number"; + readonly ZodBigInt: "integer"; + readonly ZodBoolean: "boolean"; + readonly ZodNull: "null"; +}; +type JsonSchema7Primitive = (typeof primitiveMappings)[keyof typeof primitiveMappings]; +export type JsonSchema7UnionType = JsonSchema7PrimitiveUnionType | JsonSchema7AnyOfType; +type JsonSchema7PrimitiveUnionType = { + type: JsonSchema7Primitive | JsonSchema7Primitive[]; +} | { + type: JsonSchema7Primitive | JsonSchema7Primitive[]; + enum: (string | number | bigint | boolean | null)[]; +}; +type JsonSchema7AnyOfType = { + anyOf: JsonSchema7Type[]; +}; +export declare function parseUnionDef(def: ZodUnionDef | ZodDiscriminatedUnionDef, refs: Refs): JsonSchema7PrimitiveUnionType | JsonSchema7AnyOfType | undefined; +export {}; +//# sourceMappingURL=union.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/union.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/union.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..e77a820548a33b772c0003d8ef0bdcd7f1ed73f4 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/union.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"union.d.ts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/union.ts"],"names":[],"mappings":"OAAO,EAAE,wBAAwB,EAA6B,WAAW,EAAE,MAAM,KAAK;OAC/E,EAAE,eAAe,EAAY;OAC7B,EAAE,IAAI,EAAE;AAEf,eAAO,MAAM,iBAAiB;;;;;;CAMpB,CAAC;AAEX,KAAK,oBAAoB,GAAG,CAAC,OAAO,iBAAiB,CAAC,CAAC,MAAM,OAAO,iBAAiB,CAAC,CAAC;AAEvF,MAAM,MAAM,oBAAoB,GAAG,6BAA6B,GAAG,oBAAoB,CAAC;AAExF,KAAK,6BAA6B,GAC9B;IACE,IAAI,EAAE,oBAAoB,GAAG,oBAAoB,EAAE,CAAC;CACrD,GACD;IACE,IAAI,EAAE,oBAAoB,GAAG,oBAAoB,EAAE,CAAC;IACpD,IAAI,EAAE,CAAC,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,IAAI,CAAC,EAAE,CAAC;CACrD,CAAC;AAEN,KAAK,oBAAoB,GAAG;IAC1B,KAAK,EAAE,eAAe,EAAE,CAAC;CAC1B,CAAC;AAEF,wBAAgB,aAAa,CAC3B,GAAG,EAAE,WAAW,GAAG,wBAAwB,CAAC,GAAG,EAAE,GAAG,CAAC,EACrD,IAAI,EAAE,IAAI,GACT,6BAA6B,GAAG,oBAAoB,GAAG,SAAS,CAmElE"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/union.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/union.js new file mode 100644 index 0000000000000000000000000000000000000000..4dd242a0d6995b24ff6a1563c06aa1a6d74ccda0 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/union.js @@ -0,0 +1,77 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.primitiveMappings = void 0; +exports.parseUnionDef = parseUnionDef; +const parseDef_1 = require("../parseDef.js"); +exports.primitiveMappings = { + ZodString: 'string', + ZodNumber: 'number', + ZodBigInt: 'integer', + ZodBoolean: 'boolean', + ZodNull: 'null', +}; +function parseUnionDef(def, refs) { + if (refs.target === 'openApi3') + return asAnyOf(def, refs); + const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; + // This blocks tries to look ahead a bit to produce nicer looking schemas with type array instead of anyOf. + if (options.every((x) => x._def.typeName in exports.primitiveMappings && (!x._def.checks || !x._def.checks.length))) { + // all types in union are primitive and lack checks, so might as well squash into {type: [...]} + const types = options.reduce((types, x) => { + const type = exports.primitiveMappings[x._def.typeName]; //Can be safely casted due to row 43 + return type && !types.includes(type) ? [...types, type] : types; + }, []); + return { + type: types.length > 1 ? types : types[0], + }; + } + else if (options.every((x) => x._def.typeName === 'ZodLiteral' && !x.description)) { + // all options literals + const types = options.reduce((acc, x) => { + const type = typeof x._def.value; + switch (type) { + case 'string': + case 'number': + case 'boolean': + return [...acc, type]; + case 'bigint': + return [...acc, 'integer']; + case 'object': + if (x._def.value === null) + return [...acc, 'null']; + case 'symbol': + case 'undefined': + case 'function': + default: + return acc; + } + }, []); + if (types.length === options.length) { + // all the literals are primitive, as far as null can be considered primitive + const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i); + return { + type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], + enum: options.reduce((acc, x) => { + return acc.includes(x._def.value) ? acc : [...acc, x._def.value]; + }, []), + }; + } + } + else if (options.every((x) => x._def.typeName === 'ZodEnum')) { + return { + type: 'string', + enum: options.reduce((acc, x) => [...acc, ...x._def.values.filter((x) => !acc.includes(x))], []), + }; + } + return asAnyOf(def, refs); +} +const asAnyOf = (def, refs) => { + const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options) + .map((x, i) => (0, parseDef_1.parseDef)(x._def, { + ...refs, + currentPath: [...refs.currentPath, 'anyOf', `${i}`], + })) + .filter((x) => !!x && (!refs.strictUnions || (typeof x === 'object' && Object.keys(x).length > 0))); + return anyOf.length ? { anyOf } : undefined; +}; +//# sourceMappingURL=union.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/union.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/union.js.map new file mode 100644 index 0000000000000000000000000000000000000000..5c5aca8f08101c9be9312deba8945c6ecc4d2edf --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/union.js.map @@ -0,0 +1 @@ +{"version":3,"file":"union.js","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/union.ts"],"names":[],"mappings":";;;AA6BA,sCAsEC;AAlGD,6CAAwD;AAG3C,QAAA,iBAAiB,GAAG;IAC/B,SAAS,EAAE,QAAQ;IACnB,SAAS,EAAE,QAAQ;IACnB,SAAS,EAAE,SAAS;IACpB,UAAU,EAAE,SAAS;IACrB,OAAO,EAAE,MAAM;CACP,CAAC;AAmBX,SAAgB,aAAa,CAC3B,GAAqD,EACrD,IAAU;IAEV,IAAI,IAAI,CAAC,MAAM,KAAK,UAAU;QAAE,OAAO,OAAO,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;IAE1D,MAAM,OAAO,GACX,GAAG,CAAC,OAAO,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O,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;AAC9C,CAAC,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/union.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/union.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c87356cbdc8e12849c90682dd1ad0c709fa03796 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/union.mjs @@ -0,0 +1,73 @@ +import { parseDef } from "../parseDef.mjs"; +export const primitiveMappings = { + ZodString: 'string', + ZodNumber: 'number', + ZodBigInt: 'integer', + ZodBoolean: 'boolean', + ZodNull: 'null', +}; +export function parseUnionDef(def, refs) { + if (refs.target === 'openApi3') + return asAnyOf(def, refs); + const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; + // This blocks tries to look ahead a bit to produce nicer looking schemas with type array instead of anyOf. + if (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) { + // all types in union are primitive and lack checks, so might as well squash into {type: [...]} + const types = options.reduce((types, x) => { + const type = primitiveMappings[x._def.typeName]; //Can be safely casted due to row 43 + return type && !types.includes(type) ? [...types, type] : types; + }, []); + return { + type: types.length > 1 ? types : types[0], + }; + } + else if (options.every((x) => x._def.typeName === 'ZodLiteral' && !x.description)) { + // all options literals + const types = options.reduce((acc, x) => { + const type = typeof x._def.value; + switch (type) { + case 'string': + case 'number': + case 'boolean': + return [...acc, type]; + case 'bigint': + return [...acc, 'integer']; + case 'object': + if (x._def.value === null) + return [...acc, 'null']; + case 'symbol': + case 'undefined': + case 'function': + default: + return acc; + } + }, []); + if (types.length === options.length) { + // all the literals are primitive, as far as null can be considered primitive + const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i); + return { + type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], + enum: options.reduce((acc, x) => { + return acc.includes(x._def.value) ? acc : [...acc, x._def.value]; + }, []), + }; + } + } + else if (options.every((x) => x._def.typeName === 'ZodEnum')) { + return { + type: 'string', + enum: options.reduce((acc, x) => [...acc, ...x._def.values.filter((x) => !acc.includes(x))], []), + }; + } + return asAnyOf(def, refs); +} +const asAnyOf = (def, refs) => { + const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options) + .map((x, i) => parseDef(x._def, { + ...refs, + currentPath: [...refs.currentPath, 'anyOf', `${i}`], + })) + .filter((x) => !!x && (!refs.strictUnions || (typeof x === 'object' && Object.keys(x).length > 0))); + return anyOf.length ? { anyOf } : undefined; +}; +//# sourceMappingURL=union.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/union.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/union.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..b2d1071f5fec915181b510f8b3570f3a2b73b70c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/union.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"union.mjs","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/union.ts"],"names":[],"mappings":"OACO,EAAmB,QAAQ,EAAE;AAGpC,MAAM,CAAC,MAAM,iBAAiB,GAAG;IAC/B,SAAS,EAAE,QAAQ;IACnB,SAAS,EAAE,QAAQ;IACnB,SAAS,EAAE,SAAS;IACpB,UAAU,EAAE,SAAS;IACrB,OAAO,EAAE,MAAM;CACP,CAAC;AAmBX,MAAM,UAAU,aAAa,CAC3B,GAAqD,EACrD,IAAU;IAEV,IAAI,IAAI,CAAC,MAAM,KAAK,UAAU;QAAE,OAAO,OAAO,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;IAE1D,MAAM,OAAO,GACX,GAAG,C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OAAO,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;AAC9C,CAAC,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/unknown.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/unknown.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..67b2020d2495d114001b5c3676afe5c0ff326350 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/unknown.d.mts @@ -0,0 +1,3 @@ +export type JsonSchema7UnknownType = {}; +export declare function parseUnknownDef(): JsonSchema7UnknownType; +//# sourceMappingURL=unknown.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/unknown.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/unknown.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..cd17cd4cd36b1379881e144714225660ab049e54 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/unknown.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"unknown.d.mts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/unknown.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,sBAAsB,GAAG,EAAE,CAAC;AAExC,wBAAgB,eAAe,IAAI,sBAAsB,CAExD"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/unknown.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/unknown.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0afe52fc8dd50f67e9ee52f437eb03faa48f4b94 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/unknown.d.ts @@ -0,0 +1,3 @@ +export type JsonSchema7UnknownType = {}; +export declare function parseUnknownDef(): JsonSchema7UnknownType; +//# sourceMappingURL=unknown.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/unknown.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/unknown.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..80253f3f86a4678f1299d3d0323bf630a9f41d87 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/unknown.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"unknown.d.ts","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/unknown.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,sBAAsB,GAAG,EAAE,CAAC;AAExC,wBAAgB,eAAe,IAAI,sBAAsB,CAExD"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/unknown.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/unknown.js new file mode 100644 index 0000000000000000000000000000000000000000..bc21055a8b7644f9f25545b77ff4b349ca41cd75 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/unknown.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseUnknownDef = parseUnknownDef; +function parseUnknownDef() { + return {}; +} +//# sourceMappingURL=unknown.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/unknown.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/unknown.js.map new file mode 100644 index 0000000000000000000000000000000000000000..cbfe7f49393b911dcc56298e805f49a418d415cf --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/unknown.js.map @@ -0,0 +1 @@ +{"version":3,"file":"unknown.js","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/unknown.ts"],"names":[],"mappings":";;AAEA,0CAEC;AAFD,SAAgB,eAAe;IAC7B,OAAO,EAAE,CAAC;AACZ,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/unknown.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/unknown.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6146dee23a89e66e7e420de9e3b72f7da7136f97 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/unknown.mjs @@ -0,0 +1,4 @@ +export function parseUnknownDef() { + return {}; +} +//# sourceMappingURL=unknown.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/unknown.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/unknown.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..557e5fabb2ff4f8d6eeea9020e5649ad14536a10 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/parsers/unknown.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"unknown.mjs","sourceRoot":"","sources":["../../../src/_vendor/zod-to-json-schema/parsers/unknown.ts"],"names":[],"mappings":"AAEA,MAAM,UAAU,eAAe;IAC7B,OAAO,EAAE,CAAC;AACZ,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/util.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/util.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..3005f0897e2e93428687db30944c5e2812c0ac18 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/util.d.mts @@ -0,0 +1,4 @@ +import type { ZodSchema, ZodTypeDef } from 'zod'; +export declare const zodDef: (zodSchema: ZodSchema | ZodTypeDef) => ZodTypeDef; +export declare function isEmptyObj(obj: Object | null | undefined): boolean; +//# sourceMappingURL=util.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/util.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/util.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..1612242d34478113128945a537de90cf90c4c4e9 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/util.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"util.d.mts","sourceRoot":"","sources":["../../src/_vendor/zod-to-json-schema/util.ts"],"names":[],"mappings":"OAAO,KAAK,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,KAAK;AAEhD,eAAO,MAAM,MAAM,GAAI,WAAW,SAAS,GAAG,UAAU,KAAG,UAE1D,CAAC;AAEF,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,OAAO,CAIlE"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/util.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/util.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e144363904abe9ae0a472323cf8a6afb06a7bec1 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/util.d.ts @@ -0,0 +1,4 @@ +import type { ZodSchema, ZodTypeDef } from 'zod'; +export declare const zodDef: (zodSchema: ZodSchema | ZodTypeDef) => ZodTypeDef; +export declare function isEmptyObj(obj: Object | null | undefined): boolean; +//# sourceMappingURL=util.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/util.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/util.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..623966f96c4524e25d250ed79226c4690a927147 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/util.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"util.d.ts","sourceRoot":"","sources":["../../src/_vendor/zod-to-json-schema/util.ts"],"names":[],"mappings":"OAAO,KAAK,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,KAAK;AAEhD,eAAO,MAAM,MAAM,GAAI,WAAW,SAAS,GAAG,UAAU,KAAG,UAE1D,CAAC;AAEF,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,OAAO,CAIlE"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/util.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/util.js new file mode 100644 index 0000000000000000000000000000000000000000..208d3d688d338f9eb8d658110ca1bd8729ba248a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/util.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.zodDef = void 0; +exports.isEmptyObj = isEmptyObj; +const zodDef = (zodSchema) => { + return '_def' in zodSchema ? zodSchema._def : zodSchema; +}; +exports.zodDef = zodDef; +function isEmptyObj(obj) { + if (!obj) + return true; + for (const _k in obj) + return false; + return true; +} +//# sourceMappingURL=util.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/util.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/util.js.map new file mode 100644 index 0000000000000000000000000000000000000000..177075dfe2020bf9a8e949ddd740058734005933 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/util.js.map @@ -0,0 +1 @@ +{"version":3,"file":"util.js","sourceRoot":"","sources":["../../src/_vendor/zod-to-json-schema/util.ts"],"names":[],"mappings":";;;AAMA,gCAIC;AARM,MAAM,MAAM,GAAG,CAAC,SAAiC,EAAc,EAAE;IACtE,OAAO,MAAM,IAAI,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;AAC1D,CAAC,CAAC;AAFW,QAAA,MAAM,UAEjB;AAEF,SAAgB,UAAU,CAAC,GAA8B;IACvD,IAAI,CAAC,GAAG;QAAE,OAAO,IAAI,CAAC;IACtB,KAAK,MAAM,EAAE,IAAI,GAAG;QAAE,OAAO,KAAK,CAAC;IACnC,OAAO,IAAI,CAAC;AACd,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/util.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/util.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4e6ef567e60fbd610a87fa84a88a1b1d7e12b7ca --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/util.mjs @@ -0,0 +1,11 @@ +export const zodDef = (zodSchema) => { + return '_def' in zodSchema ? zodSchema._def : zodSchema; +}; +export function isEmptyObj(obj) { + if (!obj) + return true; + for (const _k in obj) + return false; + return true; +} +//# sourceMappingURL=util.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/util.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/util.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..16c49e1042c00cc7525fc06b6436906c596c8660 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/util.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"util.mjs","sourceRoot":"","sources":["../../src/_vendor/zod-to-json-schema/util.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,MAAM,GAAG,CAAC,SAAiC,EAAc,EAAE;IACtE,OAAO,MAAM,IAAI,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;AAC1D,CAAC,CAAC;AAEF,MAAM,UAAU,UAAU,CAAC,GAA8B;IACvD,IAAI,CAAC,GAAG;QAAE,OAAO,IAAI,CAAC;IACtB,KAAK,MAAM,EAAE,IAAI,GAAG;QAAE,OAAO,KAAK,CAAC;IACnC,OAAO,IAAI,CAAC;AACd,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/zodToJsonSchema.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/zodToJsonSchema.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..6469a206957aaa099b67544cbc66590d3009cbb7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/zodToJsonSchema.d.mts @@ -0,0 +1,11 @@ +import { ZodSchema } from 'zod'; +import { Options, Targets } from "./Options.mjs"; +import { JsonSchema7Type } from "./parseDef.mjs"; +declare const zodToJsonSchema: (schema: ZodSchema, options?: Partial> | string) => (Target extends "jsonSchema7" ? JsonSchema7Type : object) & { + $schema?: string; + definitions?: { + [key: string]: Target extends "jsonSchema7" ? JsonSchema7Type : Target extends "jsonSchema2019-09" ? JsonSchema7Type : object; + }; +}; +export { zodToJsonSchema }; +//# sourceMappingURL=zodToJsonSchema.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/zodToJsonSchema.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/zodToJsonSchema.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..c6098f7bc3a3f5f070dea7f3e7e61e4ebecacf58 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/zodToJsonSchema.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"zodToJsonSchema.d.mts","sourceRoot":"","sources":["../../src/_vendor/zod-to-json-schema/zodToJsonSchema.ts"],"names":[],"mappings":"OAAO,EAAE,SAAS,EAAE,MAAM,KAAK;OACxB,EAAE,OAAO,EAAE,OAAO,EAAE;OACpB,EAAE,eAAe,EAAY;AAIpC,QAAA,MAAM,eAAe,GAAI,MAAM,SAAS,OAAO,GAAG,aAAa,EAC7D,QAAQ,SAAS,CAAC,GAAG,CAAC,EACtB,UAAU,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,GAAG,MAAM,KAC1C,CAAC,MAAM,SAAS,aAAa,GAAG,eAAe,GAAG,MAAM,CAAC,GAAG;IAC7D,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,WAAW,CAAC,EAAE;QACZ,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,SAAS,aAAa,GAAG,eAAe,GAC3D,MAAM,SAAS,mBAAmB,GAAG,eAAe,GACpD,MAAM,CAAC;KACV,CAAC;CAsGH,CAAC;AAEF,OAAO,EAAE,eAAe,EAAE,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/zodToJsonSchema.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/zodToJsonSchema.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f89bf62a9af30525414db3fb2642eed756e6e2e0 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/zodToJsonSchema.d.ts @@ -0,0 +1,11 @@ +import { ZodSchema } from 'zod'; +import { Options, Targets } from "./Options.js"; +import { JsonSchema7Type } from "./parseDef.js"; +declare const zodToJsonSchema: (schema: ZodSchema, options?: Partial> | string) => (Target extends "jsonSchema7" ? JsonSchema7Type : object) & { + $schema?: string; + definitions?: { + [key: string]: Target extends "jsonSchema7" ? JsonSchema7Type : Target extends "jsonSchema2019-09" ? JsonSchema7Type : object; + }; +}; +export { zodToJsonSchema }; +//# sourceMappingURL=zodToJsonSchema.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/zodToJsonSchema.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/zodToJsonSchema.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..155ad103a260d36ddd3aac7426f7ec3b4e67b305 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/zodToJsonSchema.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"zodToJsonSchema.d.ts","sourceRoot":"","sources":["../../src/_vendor/zod-to-json-schema/zodToJsonSchema.ts"],"names":[],"mappings":"OAAO,EAAE,SAAS,EAAE,MAAM,KAAK;OACxB,EAAE,OAAO,EAAE,OAAO,EAAE;OACpB,EAAE,eAAe,EAAY;AAIpC,QAAA,MAAM,eAAe,GAAI,MAAM,SAAS,OAAO,GAAG,aAAa,EAC7D,QAAQ,SAAS,CAAC,GAAG,CAAC,EACtB,UAAU,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,GAAG,MAAM,KAC1C,CAAC,MAAM,SAAS,aAAa,GAAG,eAAe,GAAG,MAAM,CAAC,GAAG;IAC7D,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,WAAW,CAAC,EAAE;QACZ,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,SAAS,aAAa,GAAG,eAAe,GAC3D,MAAM,SAAS,mBAAmB,GAAG,eAAe,GACpD,MAAM,CAAC;KACV,CAAC;CAsGH,CAAC;AAEF,OAAO,EAAE,eAAe,EAAE,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/zodToJsonSchema.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/zodToJsonSchema.js new file mode 100644 index 0000000000000000000000000000000000000000..bda18e8523f8b9dd025fbac2334415c6101420f1 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/zodToJsonSchema.js @@ -0,0 +1,82 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.zodToJsonSchema = void 0; +const parseDef_1 = require("./parseDef.js"); +const Refs_1 = require("./Refs.js"); +const util_1 = require("./util.js"); +const zodToJsonSchema = (schema, options) => { + const refs = (0, Refs_1.getRefs)(options); + const name = typeof options === 'string' ? options + : options?.nameStrategy === 'title' ? undefined + : options?.name; + const main = (0, parseDef_1.parseDef)(schema._def, name === undefined ? refs : ({ + ...refs, + currentPath: [...refs.basePath, refs.definitionPath, name], + }), false) ?? {}; + const title = typeof options === 'object' && options.name !== undefined && options.nameStrategy === 'title' ? + options.name + : undefined; + if (title !== undefined) { + main.title = title; + } + const definitions = (() => { + if ((0, util_1.isEmptyObj)(refs.definitions)) { + return undefined; + } + const definitions = {}; + const processedDefinitions = new Set(); + // the call to `parseDef()` here might itself add more entries to `.definitions` + // so we need to continually evaluate definitions until we've resolved all of them + // + // we have a generous iteration limit here to avoid blowing up the stack if there + // are any bugs that would otherwise result in us iterating indefinitely + for (let i = 0; i < 500; i++) { + const newDefinitions = Object.entries(refs.definitions).filter(([key]) => !processedDefinitions.has(key)); + if (newDefinitions.length === 0) + break; + for (const [key, schema] of newDefinitions) { + definitions[key] = + (0, parseDef_1.parseDef)((0, util_1.zodDef)(schema), { ...refs, currentPath: [...refs.basePath, refs.definitionPath, key] }, true) ?? {}; + processedDefinitions.add(key); + } + } + return definitions; + })(); + const combined = name === undefined ? + definitions ? + { + ...main, + [refs.definitionPath]: definitions, + } + : main + : refs.nameStrategy === 'duplicate-ref' ? + { + ...main, + ...(definitions || refs.seenRefs.size ? + { + [refs.definitionPath]: { + ...definitions, + // only actually duplicate the schema definition if it was ever referenced + // otherwise the duplication is completely pointless + ...(refs.seenRefs.size ? { [name]: main } : undefined), + }, + } + : undefined), + } + : { + $ref: [...(refs.$refStrategy === 'relative' ? [] : refs.basePath), refs.definitionPath, name].join('/'), + [refs.definitionPath]: { + ...definitions, + [name]: main, + }, + }; + if (refs.target === 'jsonSchema7') { + combined.$schema = 'http://json-schema.org/draft-07/schema#'; + } + else if (refs.target === 'jsonSchema2019-09') { + combined.$schema = 'https://json-schema.org/draft/2019-09/schema#'; + } + return combined; +}; +exports.zodToJsonSchema = zodToJsonSchema; +//# sourceMappingURL=zodToJsonSchema.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/zodToJsonSchema.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/zodToJsonSchema.js.map new file mode 100644 index 0000000000000000000000000000000000000000..05bf09d48127603369aeb47301f3cb19f3e097f9 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/zodToJsonSchema.js.map @@ -0,0 +1 @@ +{"version":3,"file":"zodToJsonSchema.js","sourceRoot":"","sources":["../../src/_vendor/zod-to-json-schema/zodToJsonSchema.ts"],"names":[],"mappings":";;;AAEA,4CAAuD;AACvD,oCAAiC;AACjC,oCAA4C;AAE5C,MAAM,eAAe,GAAG,CACtB,MAAsB,EACtB,OAA2C,EAQ3C,EAAE;IACF,MAAM,IAAI,GAAG,IAAA,cAAO,EAAC,OAAO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,CAAC;aACb;YACH,CAAC,CAAC;gBACE,IAAI,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,YAAY,KAAK,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,IAAI,CAAC,cAAc,EAAE,IAAI,CAAC,CAAC,IAAI,CAChG,GAAG,CACJ;gBACD,CAAC,IAAI,CAAC,cAAc,CAAC,EAAE;oBACrB,GAAG,WAAW;oBACd,CAAC,IAAI,CAAC,EAAE,IAAI;iBACb;aACF,CAAC;IAEN,IAAI,IAAI,CAAC,MAAM,KAAK,aAAa,EAAE,CAAC;QAClC,QAAQ,CAAC,OAAO,GAAG,yCAAyC,CAAC;IAC/D,CAAC;SAAM,IAAI,IAAI,CAAC,MAAM,KAAK,mBAAmB,EAAE,CAAC;QAC/C,QAAQ,CAAC,OAAO,GAAG,+CAA+C,CAAC;IACrE,CAAC;IAED,OAAO,QAAQ,CAAC;AAClB,CAAC,CAAC;AAEO,0CAAe"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/zodToJsonSchema.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/zodToJsonSchema.mjs new file mode 100644 index 0000000000000000000000000000000000000000..bc5b1606055e517ac242db28fbe62425922911b9 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/zodToJsonSchema.mjs @@ -0,0 +1,79 @@ +import { parseDef } from "./parseDef.mjs"; +import { getRefs } from "./Refs.mjs"; +import { zodDef, isEmptyObj } from "./util.mjs"; +const zodToJsonSchema = (schema, options) => { + const refs = getRefs(options); + const name = typeof options === 'string' ? options + : options?.nameStrategy === 'title' ? undefined + : options?.name; + const main = parseDef(schema._def, name === undefined ? refs : ({ + ...refs, + currentPath: [...refs.basePath, refs.definitionPath, name], + }), false) ?? {}; + const title = typeof options === 'object' && options.name !== undefined && options.nameStrategy === 'title' ? + options.name + : undefined; + if (title !== undefined) { + main.title = title; + } + const definitions = (() => { + if (isEmptyObj(refs.definitions)) { + return undefined; + } + const definitions = {}; + const processedDefinitions = new Set(); + // the call to `parseDef()` here might itself add more entries to `.definitions` + // so we need to continually evaluate definitions until we've resolved all of them + // + // we have a generous iteration limit here to avoid blowing up the stack if there + // are any bugs that would otherwise result in us iterating indefinitely + for (let i = 0; i < 500; i++) { + const newDefinitions = Object.entries(refs.definitions).filter(([key]) => !processedDefinitions.has(key)); + if (newDefinitions.length === 0) + break; + for (const [key, schema] of newDefinitions) { + definitions[key] = + parseDef(zodDef(schema), { ...refs, currentPath: [...refs.basePath, refs.definitionPath, key] }, true) ?? {}; + processedDefinitions.add(key); + } + } + return definitions; + })(); + const combined = name === undefined ? + definitions ? + { + ...main, + [refs.definitionPath]: definitions, + } + : main + : refs.nameStrategy === 'duplicate-ref' ? + { + ...main, + ...(definitions || refs.seenRefs.size ? + { + [refs.definitionPath]: { + ...definitions, + // only actually duplicate the schema definition if it was ever referenced + // otherwise the duplication is completely pointless + ...(refs.seenRefs.size ? { [name]: main } : undefined), + }, + } + : undefined), + } + : { + $ref: [...(refs.$refStrategy === 'relative' ? [] : refs.basePath), refs.definitionPath, name].join('/'), + [refs.definitionPath]: { + ...definitions, + [name]: main, + }, + }; + if (refs.target === 'jsonSchema7') { + combined.$schema = 'http://json-schema.org/draft-07/schema#'; + } + else if (refs.target === 'jsonSchema2019-09') { + combined.$schema = 'https://json-schema.org/draft/2019-09/schema#'; + } + return combined; +}; +export { zodToJsonSchema }; +//# sourceMappingURL=zodToJsonSchema.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/zodToJsonSchema.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/zodToJsonSchema.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..7a48a54422bd192636d1af0e2f859a1d61ea4923 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/_vendor/zod-to-json-schema/zodToJsonSchema.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"zodToJsonSchema.mjs","sourceRoot":"","sources":["../../src/_vendor/zod-to-json-schema/zodToJsonSchema.ts"],"names":[],"mappings":"OAEO,EAAmB,QAAQ,EAAE;OAC7B,EAAE,OAAO,EAAE;OACX,EAAE,MAAM,EAAE,UAAU,EAAE;AAE7B,MAAM,eAAe,GAAG,CACtB,MAAsB,EACtB,OAA2C,EAQ3C,EAAE;IACF,MAAM,IAAI,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAE9B,MAAM,IAAI,GACR,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO;QACrC,CAAC,CAAC,OAAO,EAAE,YAAY,KAAK,OAAO,CAAC,CAAC,CAAC,SAAS;YAC/C,CAAC,CAAC,OAAO,EAAE,IAAI,CAAC;IAElB,MAAM,IAAI,GACR,QAAQ,CACN,MAAM,CAAC,IAAI,EACX,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAC1B;QACE,GAAG,IAAI;QACP,WAAW,EAAE,CAAC,GAAG,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,cAAc,EAAE,IAAI,CAAC;KAC3D,CACF,EACD,KAAK,CACN,IAAI,EAAE,CAAC;IAEV,MAAM,KAAK,GACT,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,CAAC,IAAI,KAAK,SAAS,IAAI,OAAO,CAAC,YAAY,KAAK,OAAO,CAAC,CAAC;QAC7F,OAAO,CAAC,IAAI;QACd,CAAC,CAAC,SAAS,CAAC;IAEd,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QACxB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACrB,CAAC;IAED,MAAM,WAAW,GAAG,CAAC,GAAG,EAAE;QACxB,IAAI,UAAU,CAAC,IAAI,CAAC,WAAW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AG,IAAI;gBACP,GAAG,CAAC,WAAW,IAAI,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;oBACrC;wBACE,CAAC,IAAI,CAAC,cAAc,CAAC,EAAE;4BACrB,GAAG,WAAW;4BACd,0EAA0E;4BAC1E,oDAAoD;4BACpD,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;yBACvD;qBACF;oBACH,CAAC,CAAC,SAAS,CAAC;aACb;YACH,CAAC,CAAC;gBACE,IAAI,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,YAAY,KAAK,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,IAAI,CAAC,cAAc,EAAE,IAAI,CAAC,CAAC,IAAI,CAChG,GAAG,CACJ;gBACD,CAAC,IAAI,CAAC,cAAc,CAAC,EAAE;oBACrB,GAAG,WAAW;oBACd,CAAC,IAAI,CAAC,EAAE,IAAI;iBACb;aACF,CAAC;IAEN,IAAI,IAAI,CAAC,MAAM,KAAK,aAAa,EAAE,CAAC;QAClC,QAAQ,CAAC,OAAO,GAAG,yCAAyC,CAAC;IAC/D,CAAC;SAAM,IAAI,IAAI,CAAC,MAAM,KAAK,mBAAmB,EAAE,CAAC;QAC/C,QAAQ,CAAC,OAAO,GAAG,+CAA+C,CAAC;IACrE,CAAC;IAED,OAAO,QAAQ,CAAC;AAClB,CAAC,CAAC;AAEF,OAAO,EAAE,eAAe,EAAE,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/index.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..ba1a62f8634587be177afcb9f4f396bb8d88e422 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/index.d.mts @@ -0,0 +1,2 @@ +export { OpenAIRealtimeError } from "./internal-base.mjs"; +//# sourceMappingURL=index.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/index.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/index.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..45e40006dd824b9cce66166b9fac050c8e4d15f6 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/index.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../../src/beta/realtime/index.ts"],"names":[],"mappings":"OAAO,EAAE,mBAAmB,EAAE"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/index.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e9ecd9d60b1492dacd21345be1a3e6034275db2e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/index.d.ts @@ -0,0 +1,2 @@ +export { OpenAIRealtimeError } from "./internal-base.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/index.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..829e8fecfb8df35ceb9aa0d2f26e4bc39ce73163 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/beta/realtime/index.ts"],"names":[],"mappings":"OAAO,EAAE,mBAAmB,EAAE"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/index.js new file mode 100644 index 0000000000000000000000000000000000000000..28be6cc80a0a0992fa714e5c1b73835621755f0d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/index.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OpenAIRealtimeError = void 0; +var internal_base_1 = require("./internal-base.js"); +Object.defineProperty(exports, "OpenAIRealtimeError", { enumerable: true, get: function () { return internal_base_1.OpenAIRealtimeError; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/index.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..4939ba2d886f4182c2e7a555051e9c5d64c2165f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/beta/realtime/index.ts"],"names":[],"mappings":";;;AAAA,oDAAsD;AAA7C,oHAAA,mBAAmB,OAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/index.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6e7f5c297c82e80ff9d62c1690ff46969556e5a4 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/index.mjs @@ -0,0 +1,2 @@ +export { OpenAIRealtimeError } from "./internal-base.mjs"; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/index.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..921762852d4db8c9e079332b017281c4fad0d31e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../../src/beta/realtime/index.ts"],"names":[],"mappings":"OAAO,EAAE,mBAAmB,EAAE"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/internal-base.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/internal-base.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..494d3decc5056cb4a3027bbcebd7691568ccc767 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/internal-base.d.mts @@ -0,0 +1,45 @@ +import { RealtimeClientEvent, RealtimeServerEvent, ErrorEvent } from "../../resources/beta/realtime/realtime.mjs"; +import { EventEmitter } from "../../lib/EventEmitter.mjs"; +import { OpenAIError } from "../../error.mjs"; +import OpenAI, { AzureOpenAI } from "../../index.mjs"; +export declare class OpenAIRealtimeError extends OpenAIError { + /** + * The error data that the API sent back in an `error` event. + */ + error?: ErrorEvent.Error | undefined; + /** + * The unique ID of the server event. + */ + event_id?: string | undefined; + constructor(message: string, event: ErrorEvent | null); +} +type Simplify = { + [KeyType in keyof T]: T[KeyType]; +} & {}; +type RealtimeEvents = Simplify<{ + event: (event: RealtimeServerEvent) => void; + error: (error: OpenAIRealtimeError) => void; +} & { + [EventType in Exclude]: (event: Extract) => unknown; +}>; +export declare abstract class OpenAIRealtimeEmitter extends EventEmitter { + /** + * Send an event to the API. + */ + abstract send(event: RealtimeClientEvent): void; + /** + * Close the websocket connection. + */ + abstract close(props?: { + code: number; + reason: string; + }): void; + protected _onError(event: null, message: string, cause: any): void; + protected _onError(event: ErrorEvent, message?: string | undefined): void; +} +export declare function isAzure(client: Pick): client is AzureOpenAI; +export declare function buildRealtimeURL(client: Pick, model: string): URL; +export {}; +//# sourceMappingURL=internal-base.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/internal-base.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/internal-base.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..443e9a497e206e4a325b93a8c4870a13160f28a9 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/internal-base.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"internal-base.d.mts","sourceRoot":"","sources":["../../src/beta/realtime/internal-base.ts"],"names":[],"mappings":"OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,UAAU,EAAE;OACxD,EAAE,YAAY,EAAE;OAChB,EAAE,WAAW,EAAE;OACf,MAAM,EAAE,EAAE,WAAW,EAAE;AAE9B,qBAAa,mBAAoB,SAAQ,WAAW;IAClD;;OAEG;IACH,KAAK,CAAC,EAAE,UAAU,CAAC,KAAK,GAAG,SAAS,CAAC;IAErC;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;gBAElB,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,UAAU,GAAG,IAAI;CAMtD;AAED,KAAK,QAAQ,CAAC,CAAC,IAAI;KAAG,OAAO,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC;CAAE,GAAG,EAAE,CAAC;AAE7D,KAAK,cAAc,GAAG,QAAQ,CAC5B;IACE,KAAK,EAAE,CAAC,KAAK,EAAE,mBAAmB,KAAK,IAAI,CAAC;IAC5C,KAAK,EAAE,CAAC,KAAK,EAAE,mBAAmB,KAAK,IAAI,CAAC;CAC7C,GAAG;KACD,SAAS,IAAI,OAAO,CAAC,mBAAmB,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC,GAAG,CAC5D,KAAK,EAAE,OAAO,CAAC,mBAAmB,EAAE;QAAE,IAAI,EAAE,SAAS,CAAA;KAAE,CAAC,KACrD,OAAO;CACb,CACF,CAAC;AAEF,8BAAsB,qBAAsB,SAAQ,YAAY,CAAC,cAAc,CAAC;IAC9E;;OAEG;IACH,QAAQ,CAAC,IAAI,CAAC,KAAK,EAAE,mBAAmB,GAAG,IAAI;IAE/C;;OAEG;IACH,QAAQ,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI;IAE9D,SAAS,CAAC,QAAQ,CAAC,KAAK,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,GAAG,IAAI;IAClE,SAAS,CAAC,QAAQ,CAAC,KAAK,EAAE,UAAU,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI;CAyB1E;AAED,wBAAgB,OAAO,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,QAAQ,GAAG,SAAS,CAAC,GAAG,MAAM,IAAI,WAAW,CAEzF;AAED,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,QAAQ,GAAG,SAAS,CAAC,EAAE,KAAK,EAAE,MAAM,GAAG,GAAG,CAY/F"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/internal-base.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/internal-base.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d4879ef7a3af401962c7d70900e00c22d8969ef8 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/internal-base.d.ts @@ -0,0 +1,45 @@ +import { RealtimeClientEvent, RealtimeServerEvent, ErrorEvent } from "../../resources/beta/realtime/realtime.js"; +import { EventEmitter } from "../../lib/EventEmitter.js"; +import { OpenAIError } from "../../error.js"; +import OpenAI, { AzureOpenAI } from "../../index.js"; +export declare class OpenAIRealtimeError extends OpenAIError { + /** + * The error data that the API sent back in an `error` event. + */ + error?: ErrorEvent.Error | undefined; + /** + * The unique ID of the server event. + */ + event_id?: string | undefined; + constructor(message: string, event: ErrorEvent | null); +} +type Simplify = { + [KeyType in keyof T]: T[KeyType]; +} & {}; +type RealtimeEvents = Simplify<{ + event: (event: RealtimeServerEvent) => void; + error: (error: OpenAIRealtimeError) => void; +} & { + [EventType in Exclude]: (event: Extract) => unknown; +}>; +export declare abstract class OpenAIRealtimeEmitter extends EventEmitter { + /** + * Send an event to the API. + */ + abstract send(event: RealtimeClientEvent): void; + /** + * Close the websocket connection. + */ + abstract close(props?: { + code: number; + reason: string; + }): void; + protected _onError(event: null, message: string, cause: any): void; + protected _onError(event: ErrorEvent, message?: string | undefined): void; +} +export declare function isAzure(client: Pick): client is AzureOpenAI; +export declare function buildRealtimeURL(client: Pick, model: string): URL; +export {}; +//# sourceMappingURL=internal-base.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/internal-base.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/internal-base.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..028428ec3e57b213c94034534a62a7897f2717c1 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/internal-base.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"internal-base.d.ts","sourceRoot":"","sources":["../../src/beta/realtime/internal-base.ts"],"names":[],"mappings":"OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,UAAU,EAAE;OACxD,EAAE,YAAY,EAAE;OAChB,EAAE,WAAW,EAAE;OACf,MAAM,EAAE,EAAE,WAAW,EAAE;AAE9B,qBAAa,mBAAoB,SAAQ,WAAW;IAClD;;OAEG;IACH,KAAK,CAAC,EAAE,UAAU,CAAC,KAAK,GAAG,SAAS,CAAC;IAErC;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;gBAElB,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,UAAU,GAAG,IAAI;CAMtD;AAED,KAAK,QAAQ,CAAC,CAAC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novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/internal-base.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/internal-base.js new file mode 100644 index 0000000000000000000000000000000000000000..48c53a9256312dffb770faf0798842df505c1bcc --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/internal-base.js @@ -0,0 +1,55 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OpenAIRealtimeEmitter = exports.OpenAIRealtimeError = void 0; +exports.isAzure = isAzure; +exports.buildRealtimeURL = buildRealtimeURL; +const EventEmitter_1 = require("../../lib/EventEmitter.js"); +const error_1 = require("../../error.js"); +const index_1 = require("../../index.js"); +class OpenAIRealtimeError extends error_1.OpenAIError { + constructor(message, event) { + super(message); + this.error = event?.error; + this.event_id = event?.event_id; + } +} +exports.OpenAIRealtimeError = OpenAIRealtimeError; +class OpenAIRealtimeEmitter extends EventEmitter_1.EventEmitter { + _onError(event, message, cause) { + message = + event?.error ? + `${event.error.message} code=${event.error.code} param=${event.error.param} type=${event.error.type} event_id=${event.error.event_id}` + : message ?? 'unknown error'; + if (!this._hasListener('error')) { + const error = new OpenAIRealtimeError(message + + `\n\nTo resolve these unhandled rejection errors you should bind an \`error\` callback, e.g. \`rt.on('error', (error) => ...)\` `, event); + // @ts-ignore + error.cause = cause; + Promise.reject(error); + return; + } + const error = new OpenAIRealtimeError(message, event); + // @ts-ignore + error.cause = cause; + this._emit('error', error); + } +} +exports.OpenAIRealtimeEmitter = OpenAIRealtimeEmitter; +function isAzure(client) { + return client instanceof index_1.AzureOpenAI; +} +function buildRealtimeURL(client, model) { + const path = '/realtime'; + const baseURL = client.baseURL; + const url = new URL(baseURL + (baseURL.endsWith('/') ? path.slice(1) : path)); + url.protocol = 'wss'; + if (isAzure(client)) { + url.searchParams.set('api-version', client.apiVersion); + url.searchParams.set('deployment', model); + } + else { + url.searchParams.set('model', model); + } + return url; +} +//# sourceMappingURL=internal-base.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/internal-base.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/internal-base.js.map new file mode 100644 index 0000000000000000000000000000000000000000..655ab3c3f2a9e9223df9351bf568fc6d07618ae4 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/internal-base.js.map @@ -0,0 +1 @@ +{"version":3,"file":"internal-base.js","sourceRoot":"","sources":["../../src/beta/realtime/internal-base.ts"],"names":[],"mappings":";;;AA4EA,0BAEC;AAED,4CAYC;AA3FD,4DAAsD;AACtD,0CAA0C;AAC1C,0CAAkD;AAElD,MAAa,mBAAoB,SAAQ,mBAAW;IAWlD,YAAY,OAAe,EAAE,KAAwB;QACnD,KAAK,CAAC,OAAO,CAAC,CAAC;QAEf,IAAI,CAAC,KAAK,GAAG,KAAK,EAAE,KAAK,CAAC;QAC1B,IAAI,CAAC,QAAQ,GAAG,KAAK,EAAE,QAAQ,CAAC;IAClC,CAAC;CACF;AAjBD,kDAiBC;AAeD,MAAsB,qBAAsB,SAAQ,2BAA4B;IAapE,QAAQ,CAAC,KAAwB,EAAE,OAA4B,EAAE,KAAW;QACpF,OAAO;YACL,KAAK,EAAE,KAAK,CAAC,CAAC;gBACZ,GAAG,KAAK,CAAC,KAAK,CAAC,OAAO,SAAS,KAAK,CAAC,KAAK,CAAC,IAAI,UAAU,KAAK,CAAC,KAAK,CAAC,KAAK,SAAS,KAAK,CAAC,KAAK,CAAC,IAAI,aAAa,KAAK,CAAC,KAAK,CAAC,QAAQ,EAAE;gBACxI,CAAC,CAAC,OAAO,IAAI,eAAe,CAAC;QAE/B,IAAI,CAAC,IAAI,CAAC,YAAY,CAAC,OAAO,CAAC,EAAE,CAAC;YAChC,MAAM,KAAK,GAAG,IAAI,mBAAmB,CACnC,OAAO;gBACL,iIAAiI,EACnI,KAAK,CACN,CAAC;YACF,aAAa;YACb,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC;YACpB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YACtB,OAAO;QACT,CAAC;QAED,MAAM,KAAK,GAAG,IAAI,mBAAmB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;QACtD,aAAa;QACb,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC;QAEpB,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IAC7B,CAAC;CACF;AArCD,sDAqCC;AAED,SAAgB,OAAO,CAAC,MAA0C;IAChE,OAAO,MAAM,YAAY,mBAAW,CAAC;AACvC,CAAC;AAED,SAAgB,gBAAgB,CAAC,MAA0C,EAAE,KAAa;IACxF,MAAM,IAAI,GAAG,WAAW,CAAC;IACzB,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC;IAC/B,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,OAAO,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;IAC9E,GAAG,CAAC,QAAQ,GAAG,KAAK,CAAC;IACrB,IAAI,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;QACpB,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,aAAa,EAAE,MAAM,CAAC,UAAU,CAAC,CAAC;QACvD,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,YAAY,EAAE,KAAK,CAAC,CAAC;IAC5C,CAAC;SAAM,CAAC;QACN,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IACvC,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/internal-base.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/internal-base.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5cdc787aded13e2eabdf5541f69ed9d83c647f1a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/internal-base.mjs @@ -0,0 +1,48 @@ +import { EventEmitter } from "../../lib/EventEmitter.mjs"; +import { OpenAIError } from "../../error.mjs"; +import { AzureOpenAI } from "../../index.mjs"; +export class OpenAIRealtimeError extends OpenAIError { + constructor(message, event) { + super(message); + this.error = event?.error; + this.event_id = event?.event_id; + } +} +export class OpenAIRealtimeEmitter extends EventEmitter { + _onError(event, message, cause) { + message = + event?.error ? + `${event.error.message} code=${event.error.code} param=${event.error.param} type=${event.error.type} event_id=${event.error.event_id}` + : message ?? 'unknown error'; + if (!this._hasListener('error')) { + const error = new OpenAIRealtimeError(message + + `\n\nTo resolve these unhandled rejection errors you should bind an \`error\` callback, e.g. \`rt.on('error', (error) => ...)\` `, event); + // @ts-ignore + error.cause = cause; + Promise.reject(error); + return; + } + const error = new OpenAIRealtimeError(message, event); + // @ts-ignore + error.cause = cause; + this._emit('error', error); + } +} +export function isAzure(client) { + return client instanceof AzureOpenAI; +} +export function buildRealtimeURL(client, model) { + const path = '/realtime'; + const baseURL = client.baseURL; + const url = new URL(baseURL + (baseURL.endsWith('/') ? path.slice(1) : path)); + url.protocol = 'wss'; + if (isAzure(client)) { + url.searchParams.set('api-version', client.apiVersion); + url.searchParams.set('deployment', model); + } + else { + url.searchParams.set('model', model); + } + return url; +} +//# sourceMappingURL=internal-base.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/internal-base.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/internal-base.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..e701fbf86d97a4aa48db6c55750ae43d06825540 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/internal-base.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"internal-base.mjs","sourceRoot":"","sources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,CAAC,MAA0C;IAChE,OAAO,MAAM,YAAY,WAAW,CAAC;AACvC,CAAC;AAED,MAAM,UAAU,gBAAgB,CAAC,MAA0C,EAAE,KAAa;IACxF,MAAM,IAAI,GAAG,WAAW,CAAC;IACzB,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC;IAC/B,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,OAAO,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;IAC9E,GAAG,CAAC,QAAQ,GAAG,KAAK,CAAC;IACrB,IAAI,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;QACpB,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,aAAa,EAAE,MAAM,CAAC,UAAU,CAAC,CAAC;QACvD,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,YAAY,EAAE,KAAK,CAAC,CAAC;IAC5C,CAAC;SAAM,CAAC;QACN,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IACvC,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/websocket.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/websocket.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..ea3547f08d3154c6ac034417c2859c4b5f61d94a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/websocket.d.mts @@ -0,0 +1,30 @@ +import { AzureOpenAI, OpenAI } from "../../index.mjs"; +import type { RealtimeClientEvent } from "../../resources/beta/realtime/realtime.mjs"; +import { OpenAIRealtimeEmitter } from "./internal-base.mjs"; +type _WebSocket = typeof globalThis extends ({ + WebSocket: infer ws extends abstract new (...args: any) => any; +}) ? InstanceType : any; +export declare class OpenAIRealtimeWebSocket extends OpenAIRealtimeEmitter { + url: URL; + socket: _WebSocket; + constructor(props: { + model: string; + dangerouslyAllowBrowser?: boolean; + /** + * Callback to mutate the URL, needed for Azure. + * @internal + */ + onURL?: (url: URL) => void; + }, client?: Pick); + static azure(client: Pick, options?: { + deploymentName?: string; + dangerouslyAllowBrowser?: boolean; + }): Promise; + send(event: RealtimeClientEvent): void; + close(props?: { + code: number; + reason: string; + }): void; +} +export {}; +//# sourceMappingURL=websocket.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/websocket.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/websocket.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..8cce7ca6a40dbb37dbf69e35221f790d5d45d951 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/websocket.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"websocket.d.mts","sourceRoot":"","sources":["../../src/beta/realtime/websocket.ts"],"names":[],"mappings":"OAAO,EAAE,WAAW,EAAE,MAAM,EAAE;OAEvB,KAAK,EAAE,mBAAmB,EAAuB;OACjD,EAAE,qBAAqB,EAA6B;AAO3D,KAAK,UAAU,GACb,OAAO,UAAU,SAAS,CACxB;IACE,SAAS,EAAE,MAAM,EAAE,SAAS,QAAQ,MAAM,GAAG,IAAI,EAAE,GAAG,KAAK,GAAG,CAAC;CAChE,CACF,GAEC,YAAY,CAAC,EAAE,CAAC,GAChB,GAAG,CAAC;AAER,qBAAa,uBAAwB,SAAQ,qBAAqB;IAChE,GAAG,EAAE,GAAG,CAAC;IACT,MAAM,EAAE,UAAU,CAAC;gBAGjB,KAAK,EAAE;QACL,KAAK,EAAE,MAAM,CAAC;QACd,uBAAuB,CAAC,EAAE,OAAO,CAAC;QAClC;;;WAGG;QACH,KAAK,CAAC,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK,IAAI,CAAC;KAC5B,EACD,MAAM,CAAC,EAAE,IAAI,CAAC,MAAM,EAAE,QAAQ,GAAG,SAAS,CAAC;WA8DhC,KAAK,CAChB,MAAM,EAAE,IAAI,CAAC,WAAW,EAAE,kBAAkB,GAAG,YAAY,GAAG,QAAQ,GAAG,SAAS,GAAG,gBAAgB,CAAC,EACtG,OAAO,GAAE;QAAE,cAAc,CAAC,EAAE,MAAM,CAAC;QAAC,uBAAuB,CAAC,EAAE,OAAO,CAAA;KAAO,GAC3E,OAAO,CAAC,uBAAuB,CAAC;IA4BnC,IAAI,CAAC,KAAK,EAAE,mBAAmB;IAQ/B,KAAK,CAAC,KAAK,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE;CAO/C"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/websocket.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/websocket.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..46c75ea3979332fd41598347c9f4f14352984b79 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/websocket.d.ts @@ -0,0 +1,30 @@ +import { AzureOpenAI, OpenAI } from "../../index.js"; +import type { RealtimeClientEvent } from "../../resources/beta/realtime/realtime.js"; +import { OpenAIRealtimeEmitter } from "./internal-base.js"; +type _WebSocket = typeof globalThis extends ({ + WebSocket: infer ws extends abstract new (...args: any) => any; +}) ? InstanceType : any; +export declare class OpenAIRealtimeWebSocket extends OpenAIRealtimeEmitter { + url: URL; + socket: _WebSocket; + constructor(props: { + model: string; + dangerouslyAllowBrowser?: boolean; + /** + * Callback to mutate the URL, needed for Azure. + * @internal + */ + onURL?: (url: URL) => void; + }, client?: Pick); + static azure(client: Pick, options?: { + deploymentName?: string; + dangerouslyAllowBrowser?: boolean; + }): Promise; + send(event: RealtimeClientEvent): void; + close(props?: { + code: number; + reason: string; + }): void; +} +export {}; +//# sourceMappingURL=websocket.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/websocket.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/websocket.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..0a9519dc69381e81e889ff043a089857ded8f5b8 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/websocket.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"websocket.d.ts","sourceRoot":"","sources":["../../src/beta/realtime/websocket.ts"],"names":[],"mappings":"OAAO,EAAE,WAAW,EAAE,MAAM,EAAE;OAEvB,KAAK,EAAE,mBAAmB,EAAuB;OACjD,EAAE,qBAAqB,EAA6B;AAO3D,KAAK,UAAU,GACb,OAAO,UAAU,SAAS,CACxB;IACE,SAAS,EAAE,MAAM,EAAE,SAAS,QAAQ,MAAM,GAAG,IAAI,EAAE,GAAG,KAAK,GAAG,CAAC;CAChE,CACF,GAEC,YAAY,CAAC,EAAE,CAAC,GAChB,GAAG,CAAC;AAER,qBAAa,uBAAwB,SAAQ,qBAAqB;IAChE,GAAG,EAAE,GAAG,CAAC;IACT,MAAM,EAAE,UAAU,CAAC;gBAGjB,KAAK,EAAE;QACL,KAAK,EAAE,MAAM,CAAC;QACd,uBAAuB,CAAC,EAAE,OAAO,CAAC;QAClC;;;WAGG;QACH,KAAK,CAAC,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK,IAAI,CAAC;KAC5B,EACD,MAAM,CAAC,EAAE,IAAI,CAAC,MAAM,EAAE,QAAQ,GAAG,SAAS,CAAC;WA8DhC,KAAK,CAChB,MAAM,EAAE,IAAI,CAAC,WAAW,EAAE,kBAAkB,GAAG,YAAY,GAAG,QAAQ,GAAG,SAAS,GAAG,gBAAgB,CAAC,EACtG,OAAO,GAAE;QAAE,cAAc,CAAC,EAAE,MAAM,CAAC;QAAC,uBAAuB,CAAC,EAAE,OAAO,CAAA;KAAO,GAC3E,OAAO,CAAC,uBAAuB,CAAC;IA4BnC,IAAI,CAAC,KAAK,EAAE,mBAAmB;IAQ/B,KAAK,CAAC,KAAK,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE;CAO/C"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/websocket.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/websocket.js new file mode 100644 index 0000000000000000000000000000000000000000..477d4709a74e231b4c721f1a0b102f3ec5983be4 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/websocket.js @@ -0,0 +1,103 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OpenAIRealtimeWebSocket = void 0; +const index_1 = require("../../index.js"); +const error_1 = require("../../error.js"); +const internal_base_1 = require("./internal-base.js"); +const detect_platform_1 = require("../../internal/detect-platform.js"); +class OpenAIRealtimeWebSocket extends internal_base_1.OpenAIRealtimeEmitter { + constructor(props, client) { + super(); + const dangerouslyAllowBrowser = props.dangerouslyAllowBrowser ?? + client?._options?.dangerouslyAllowBrowser ?? + (client?.apiKey.startsWith('ek_') ? true : null); + if (!dangerouslyAllowBrowser && (0, detect_platform_1.isRunningInBrowser)()) { + throw new error_1.OpenAIError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\n\nYou can avoid this error by creating an ephemeral session token:\nhttps://platform.openai.com/docs/api-reference/realtime-sessions\n"); + } + client ?? (client = new index_1.OpenAI({ dangerouslyAllowBrowser })); + this.url = (0, internal_base_1.buildRealtimeURL)(client, props.model); + props.onURL?.(this.url); + // @ts-ignore + this.socket = new WebSocket(this.url.toString(), [ + 'realtime', + ...((0, internal_base_1.isAzure)(client) ? [] : [`openai-insecure-api-key.${client.apiKey}`]), + 'openai-beta.realtime-v1', + ]); + this.socket.addEventListener('message', (websocketEvent) => { + const event = (() => { + try { + return JSON.parse(websocketEvent.data.toString()); + } + catch (err) { + this._onError(null, 'could not parse websocket event', err); + return null; + } + })(); + if (event) { + this._emit('event', event); + if (event.type === 'error') { + this._onError(event); + } + else { + // @ts-expect-error TS isn't smart enough to get the relationship right here + this._emit(event.type, event); + } + } + }); + this.socket.addEventListener('error', (event) => { + this._onError(null, event.message, null); + }); + if ((0, internal_base_1.isAzure)(client)) { + if (this.url.searchParams.get('Authorization') !== null) { + this.url.searchParams.set('Authorization', ''); + } + else { + this.url.searchParams.set('api-key', ''); + } + } + } + static async azure(client, options = {}) { + const token = await client._getAzureADToken(); + function onURL(url) { + if (client.apiKey !== '') { + url.searchParams.set('api-key', client.apiKey); + } + else { + if (token) { + url.searchParams.set('Authorization', `Bearer ${token}`); + } + else { + throw new Error('AzureOpenAI is not instantiated correctly. No API key or token provided.'); + } + } + } + const deploymentName = options.deploymentName ?? client.deploymentName; + if (!deploymentName) { + throw new Error('No deployment name provided'); + } + const { dangerouslyAllowBrowser } = options; + return new OpenAIRealtimeWebSocket({ + model: deploymentName, + onURL, + ...(dangerouslyAllowBrowser ? { dangerouslyAllowBrowser } : {}), + }, client); + } + send(event) { + try { + this.socket.send(JSON.stringify(event)); + } + catch (err) { + this._onError(null, 'could not send data', err); + } + } + close(props) { + try { + this.socket.close(props?.code ?? 1000, props?.reason ?? 'OK'); + } + catch (err) { + this._onError(null, 'could not close the connection', err); + } + } +} +exports.OpenAIRealtimeWebSocket = OpenAIRealtimeWebSocket; +//# sourceMappingURL=websocket.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/websocket.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/websocket.js.map new file mode 100644 index 0000000000000000000000000000000000000000..60e404995fd3279e40392c40697ebe8e95a97b55 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/websocket.js.map @@ -0,0 +1 @@ +{"version":3,"file":"websocket.js","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AAwC;QAC5C,IAAI,CAAC;YACH,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,EAAE,IAAI,IAAI,IAAI,EAAE,KAAK,EAAE,MAAM,IAAI,IAAI,CAAC,CAAC;QAChE,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,gCAAgC,EAAE,GAAG,CAAC,CAAC;QAC7D,CAAC;IACH,CAAC;CACF;AA1HD,0DA0HC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/websocket.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/websocket.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ebcfab1d47e9259c8f8c2d1091a7cd489938d9d1 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/websocket.mjs @@ -0,0 +1,99 @@ +import { OpenAI } from "../../index.mjs"; +import { OpenAIError } from "../../error.mjs"; +import { OpenAIRealtimeEmitter, buildRealtimeURL, isAzure } from "./internal-base.mjs"; +import { isRunningInBrowser } from "../../internal/detect-platform.mjs"; +export class OpenAIRealtimeWebSocket extends OpenAIRealtimeEmitter { + constructor(props, client) { + super(); + const dangerouslyAllowBrowser = props.dangerouslyAllowBrowser ?? + client?._options?.dangerouslyAllowBrowser ?? + (client?.apiKey.startsWith('ek_') ? true : null); + if (!dangerouslyAllowBrowser && isRunningInBrowser()) { + throw new OpenAIError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\n\nYou can avoid this error by creating an ephemeral session token:\nhttps://platform.openai.com/docs/api-reference/realtime-sessions\n"); + } + client ?? (client = new OpenAI({ dangerouslyAllowBrowser })); + this.url = buildRealtimeURL(client, props.model); + props.onURL?.(this.url); + // @ts-ignore + this.socket = new WebSocket(this.url.toString(), [ + 'realtime', + ...(isAzure(client) ? [] : [`openai-insecure-api-key.${client.apiKey}`]), + 'openai-beta.realtime-v1', + ]); + this.socket.addEventListener('message', (websocketEvent) => { + const event = (() => { + try { + return JSON.parse(websocketEvent.data.toString()); + } + catch (err) { + this._onError(null, 'could not parse websocket event', err); + return null; + } + })(); + if (event) { + this._emit('event', event); + if (event.type === 'error') { + this._onError(event); + } + else { + // @ts-expect-error TS isn't smart enough to get the relationship right here + this._emit(event.type, event); + } + } + }); + this.socket.addEventListener('error', (event) => { + this._onError(null, event.message, null); + }); + if (isAzure(client)) { + if (this.url.searchParams.get('Authorization') !== null) { + this.url.searchParams.set('Authorization', ''); + } + else { + this.url.searchParams.set('api-key', ''); + } + } + } + static async azure(client, options = {}) { + const token = await client._getAzureADToken(); + function onURL(url) { + if (client.apiKey !== '') { + url.searchParams.set('api-key', client.apiKey); + } + else { + if (token) { + url.searchParams.set('Authorization', `Bearer ${token}`); + } + else { + throw new Error('AzureOpenAI is not instantiated correctly. No API key or token provided.'); + } + } + } + const deploymentName = options.deploymentName ?? client.deploymentName; + if (!deploymentName) { + throw new Error('No deployment name provided'); + } + const { dangerouslyAllowBrowser } = options; + return new OpenAIRealtimeWebSocket({ + model: deploymentName, + onURL, + ...(dangerouslyAllowBrowser ? { dangerouslyAllowBrowser } : {}), + }, client); + } + send(event) { + try { + this.socket.send(JSON.stringify(event)); + } + catch (err) { + this._onError(null, 'could not send data', err); + } + } + close(props) { + try { + this.socket.close(props?.code ?? 1000, props?.reason ?? 'OK'); + } + catch (err) { + this._onError(null, 'could not close the connection', err); + } + } +} +//# sourceMappingURL=websocket.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/websocket.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/websocket.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..469a11c3187c0f685f5a93b1c35fb95ffe9ff1f3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/websocket.mjs.map @@ -0,0 +1 @@ +{"version":3,"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AAG,CAAC,CAAC;QAClD,CAAC;IACH,CAAC;IAED,KAAK,CAAC,KAAwC;QAC5C,IAAI,CAAC;YACH,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,EAAE,IAAI,IAAI,IAAI,EAAE,KAAK,EAAE,MAAM,IAAI,IAAI,CAAC,CAAC;QAChE,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,gCAAgC,EAAE,GAAG,CAAC,CAAC;QAC7D,CAAC;IACH,CAAC;CACF"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/ws.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/ws.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..21ca1c4035f855d2fc384ac4f0047866fa3a3d8a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/ws.d.mts @@ -0,0 +1,22 @@ +import * as WS from 'ws'; +import { AzureOpenAI, OpenAI } from "../../index.mjs"; +import type { RealtimeClientEvent } from "../../resources/beta/realtime/realtime.mjs"; +import { OpenAIRealtimeEmitter } from "./internal-base.mjs"; +export declare class OpenAIRealtimeWS extends OpenAIRealtimeEmitter { + url: URL; + socket: WS.WebSocket; + constructor(props: { + model: string; + options?: WS.ClientOptions | undefined; + }, client?: Pick); + static azure(client: Pick, options?: { + deploymentName?: string; + options?: WS.ClientOptions | undefined; + }): Promise; + send(event: RealtimeClientEvent): void; + close(props?: { + code: number; + reason: string; + }): void; +} +//# sourceMappingURL=ws.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/ws.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/ws.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..0712ff403d184f00ce21ea48b4c8dcdcf7f231a2 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/ws.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"ws.d.mts","sourceRoot":"","sources":["../../src/beta/realtime/ws.ts"],"names":[],"mappings":"OAAO,KAAK,EAAE,MAAM,IAAI;OACjB,EAAE,WAAW,EAAE,MAAM,EAAE;OACvB,KAAK,EAAE,mBAAmB,EAAuB;OACjD,EAAE,qBAAqB,EAA6B;AAE3D,qBAAa,gBAAiB,SAAQ,qBAAqB;IACzD,GAAG,EAAE,GAAG,CAAC;IACT,MAAM,EAAE,EAAE,CAAC,SAAS,CAAC;gBAGnB,KAAK,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,EAAE,CAAC,aAAa,GAAG,SAAS,CAAA;KAAE,EAChE,MAAM,CAAC,EAAE,IAAI,CAAC,MAAM,EAAE,QAAQ,GAAG,SAAS,CAAC;WA0ChC,KAAK,CAChB,MAAM,EAAE,IAAI,CAAC,WAAW,EAAE,kBAAkB,GAAG,YAAY,GAAG,QAAQ,GAAG,SAAS,GAAG,gBAAgB,CAAC,EACtG,OAAO,GAAE;QAAE,cAAc,CAAC,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,EAAE,CAAC,aAAa,GAAG,SAAS,CAAA;KAAO,GAChF,OAAO,CAAC,gBAAgB,CAAC;IAW5B,IAAI,CAAC,KAAK,EAAE,mBAAmB;IAQ/B,KAAK,CAAC,KAAK,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE;CAO/C"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/ws.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/ws.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..879aaa0b1e86e7affc8ec8c88bcf760877996058 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/ws.d.ts @@ -0,0 +1,22 @@ +import * as WS from 'ws'; +import { AzureOpenAI, OpenAI } from "../../index.js"; +import type { RealtimeClientEvent } from "../../resources/beta/realtime/realtime.js"; +import { OpenAIRealtimeEmitter } from "./internal-base.js"; +export declare class OpenAIRealtimeWS extends OpenAIRealtimeEmitter { + url: URL; + socket: WS.WebSocket; + constructor(props: { + model: string; + options?: WS.ClientOptions | undefined; + }, client?: Pick); + static azure(client: Pick, options?: { + deploymentName?: string; + options?: WS.ClientOptions | undefined; + }): Promise; + send(event: RealtimeClientEvent): void; + close(props?: { + code: number; + reason: string; + }): void; +} +//# sourceMappingURL=ws.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/ws.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/ws.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..f4e9d0d3056b04b9b877895424790847641293ee --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/ws.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ws.d.ts","sourceRoot":"","sources":["../../src/beta/realtime/ws.ts"],"names":[],"mappings":"OAAO,KAAK,EAAE,MAAM,IAAI;OACjB,EAAE,WAAW,EAAE,MAAM,EAAE;OACvB,KAAK,EAAE,mBAAmB,EAAuB;OACjD,EAAE,qBAAqB,EAA6B;AAE3D,qBAAa,gBAAiB,SAAQ,qBAAqB;IACzD,GAAG,EAAE,GAAG,CAAC;IACT,MAAM,EAAE,EAAE,CAAC,SAAS,CAAC;gBAGnB,KAAK,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,EAAE,CAAC,aAAa,GAAG,SAAS,CAAA;KAAE,EAChE,MAAM,CAAC,EAAE,IAAI,CAAC,MAAM,EAAE,QAAQ,GAAG,SAAS,CAAC;WA0ChC,KAAK,CAChB,MAAM,EAAE,IAAI,CAAC,WAAW,EAAE,kBAAkB,GAAG,YAAY,GAAG,QAAQ,GAAG,SAAS,GAAG,gBAAgB,CAAC,EACtG,OAAO,GAAE;QAAE,cAAc,CAAC,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,EAAE,CAAC,aAAa,GAAG,SAAS,CAAA;KAAO,GAChF,OAAO,CAAC,gBAAgB,CAAC;IAW5B,IAAI,CAAC,KAAK,EAAE,mBAAmB;IAQ/B,KAAK,CAAC,KAAK,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE;CAO/C"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/ws.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/ws.js new file mode 100644 index 0000000000000000000000000000000000000000..36f6b02421b8dbc4276f67c4e35d45b72e22d72a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/ws.js @@ -0,0 +1,85 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OpenAIRealtimeWS = void 0; +const tslib_1 = require("../../internal/tslib.js"); +const WS = tslib_1.__importStar(require("ws")); +const index_1 = require("../../index.js"); +const internal_base_1 = require("./internal-base.js"); +class OpenAIRealtimeWS extends internal_base_1.OpenAIRealtimeEmitter { + constructor(props, client) { + super(); + client ?? (client = new index_1.OpenAI()); + this.url = (0, internal_base_1.buildRealtimeURL)(client, props.model); + this.socket = new WS.WebSocket(this.url, { + ...props.options, + headers: { + ...props.options?.headers, + ...((0, internal_base_1.isAzure)(client) ? {} : { Authorization: `Bearer ${client.apiKey}` }), + 'OpenAI-Beta': 'realtime=v1', + }, + }); + this.socket.on('message', (wsEvent) => { + const event = (() => { + try { + return JSON.parse(wsEvent.toString()); + } + catch (err) { + this._onError(null, 'could not parse websocket event', err); + return null; + } + })(); + if (event) { + this._emit('event', event); + if (event.type === 'error') { + this._onError(event); + } + else { + // @ts-expect-error TS isn't smart enough to get the relationship right here + this._emit(event.type, event); + } + } + }); + this.socket.on('error', (err) => { + this._onError(null, err.message, err); + }); + } + static async azure(client, options = {}) { + const deploymentName = options.deploymentName ?? client.deploymentName; + if (!deploymentName) { + throw new Error('No deployment name provided'); + } + return new OpenAIRealtimeWS({ model: deploymentName, options: { headers: await getAzureHeaders(client) } }, client); + } + send(event) { + try { + this.socket.send(JSON.stringify(event)); + } + catch (err) { + this._onError(null, 'could not send data', err); + } + } + close(props) { + try { + this.socket.close(props?.code ?? 1000, props?.reason ?? 'OK'); + } + catch (err) { + this._onError(null, 'could not close the connection', err); + } + } +} +exports.OpenAIRealtimeWS = OpenAIRealtimeWS; +async function getAzureHeaders(client) { + if (client.apiKey !== '') { + return { 'api-key': client.apiKey }; + } + else { + const token = await client._getAzureADToken(); + if (token) { + return { Authorization: `Bearer ${token}` }; + } + else { + throw new Error('AzureOpenAI is not instantiated correctly. No API key or token provided.'); + } + } +} +//# sourceMappingURL=ws.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/ws.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/ws.js.map new file mode 100644 index 0000000000000000000000000000000000000000..06554f4bfba7ecce5ee1851ac19aa718d801c5b3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/ws.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ws.js","sourceRoot":"","sources":["../../src/beta/realtime/ws.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,0CAAkD;AAElD,sDAAmF;AAEnF,MAAa,gBAAiB,SAAQ,qCAAqB;IAIzD,YACE,KAAgE,EAChE,MAA2C;QAE3C,KAAK,EAAE,CAAC;QACR,MAAM,KAAN,MAAM,GAAK,IAAI,cAAM,EAAE,EAAC;QAExB,IAAI,CAAC,GAAG,GAAG,IAAA,gCAAgB,EAAC,MAAM,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;QACjD,IAAI,CAAC,MAAM,GAAG,IAAI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tC,CAAC;SAAM,CAAC;QACN,MAAM,KAAK,GAAG,MAAM,MAAM,CAAC,gBAAgB,EAAE,CAAC;QAC9C,IAAI,KAAK,EAAE,CAAC;YACV,OAAO,EAAE,aAAa,EAAE,UAAU,KAAK,EAAE,EAAE,CAAC;QAC9C,CAAC;aAAM,CAAC;YACN,MAAM,IAAI,KAAK,CAAC,0EAA0E,CAAC,CAAC;QAC9F,CAAC;IACH,CAAC;AACH,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/ws.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/ws.mjs new file mode 100644 index 0000000000000000000000000000000000000000..773a51ac72a77d00178692c79907d93af7f06dd0 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/ws.mjs @@ -0,0 +1,80 @@ +import * as WS from 'ws'; +import { OpenAI } from "../../index.mjs"; +import { OpenAIRealtimeEmitter, buildRealtimeURL, isAzure } from "./internal-base.mjs"; +export class OpenAIRealtimeWS extends OpenAIRealtimeEmitter { + constructor(props, client) { + super(); + client ?? (client = new OpenAI()); + this.url = buildRealtimeURL(client, props.model); + this.socket = new WS.WebSocket(this.url, { + ...props.options, + headers: { + ...props.options?.headers, + ...(isAzure(client) ? {} : { Authorization: `Bearer ${client.apiKey}` }), + 'OpenAI-Beta': 'realtime=v1', + }, + }); + this.socket.on('message', (wsEvent) => { + const event = (() => { + try { + return JSON.parse(wsEvent.toString()); + } + catch (err) { + this._onError(null, 'could not parse websocket event', err); + return null; + } + })(); + if (event) { + this._emit('event', event); + if (event.type === 'error') { + this._onError(event); + } + else { + // @ts-expect-error TS isn't smart enough to get the relationship right here + this._emit(event.type, event); + } + } + }); + this.socket.on('error', (err) => { + this._onError(null, err.message, err); + }); + } + static async azure(client, options = {}) { + const deploymentName = options.deploymentName ?? client.deploymentName; + if (!deploymentName) { + throw new Error('No deployment name provided'); + } + return new OpenAIRealtimeWS({ model: deploymentName, options: { headers: await getAzureHeaders(client) } }, client); + } + send(event) { + try { + this.socket.send(JSON.stringify(event)); + } + catch (err) { + this._onError(null, 'could not send data', err); + } + } + close(props) { + try { + this.socket.close(props?.code ?? 1000, props?.reason ?? 'OK'); + } + catch (err) { + this._onError(null, 'could not close the connection', err); + } + } +} +async function getAzureHeaders(client) { + if (client.apiKey !== '') { + return { 'api-key': client.apiKey }; + } + else { + const token = await client._getAzureADToken(); + if (token) { + return { Authorization: `Bearer ${token}` }; + } + else { + throw new Error('AzureOpenAI is not instantiated correctly. No API key or token provided.'); + } + } +} +//# sourceMappingURL=ws.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/ws.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/ws.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..b3cfd083d6eb7401d72c9d6aba1b84b606cfacda --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/beta/realtime/ws.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"ws.mjs","sourceRoot":"","sources":["../../src/beta/realtime/ws.ts"],"names":[],"mappings":"OAAO,KAAK,EAAE,MAAM,IAAI;OACjB,EAAe,MAAM,EAAE;OAEvB,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,OAAO,EAAE;AAE3D,MAAM,OAAO,gBAAiB,SAAQ,qBAAqB;IAIzD,YACE,KAAgE,EAChE,MAA2C;QAE3C,KAAK,EAAE,CAAC;QACR,MAAM,KAAN,MAAM,GAAK,IAAI,MAAM,EAAE,EAAC;QAExB,IAAI,CAAC,GAAG,GAAG,gBAAgB,CAAC,MAAM,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;QACjD,IAAI,CAAC,MAAM,GAAG,IAAI,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,GAAG,EAAE;YACvC,GAAG,KAAK,CAAC,OAAO;YAChB,OAAO,EAAE;gBACP,GAAG,KAAK,CAAC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UAAU,KAAK,EAAE,EAAE,CAAC;QAC9C,CAAC;aAAM,CAAC;YACN,MAAM,IAAI,KAAK,CAAC,0EAA0E,CAAC,CAAC;QAC9F,CAAC;IACH,CAAC;AACH,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/alpha/index.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/alpha/index.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..48af8624764a34d0b9858f4e16f8575ba5ed29bf --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/alpha/index.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../../../src/resources/fine-tuning/alpha/index.ts"],"names":[],"mappings":"OAEO,EAAE,KAAK,EAAE;OACT,EACL,OAAO,EACP,KAAK,iBAAiB,EACtB,KAAK,sBAAsB,EAC3B,KAAK,eAAe,EACpB,KAAK,oBAAoB,GAC1B"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/alpha/index.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/alpha/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ad27c4e49f4873d3b3bd5499227e3a0fef551437 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/alpha/index.d.ts @@ -0,0 +1,3 @@ +export { Alpha } from "./alpha.js"; +export { Graders, type GraderRunResponse, type GraderValidateResponse, type GraderRunParams, type GraderValidateParams, } from "./graders.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/alpha/index.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/alpha/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..9c09c3e8eaa1331abdb1a79d8a56821f0027f722 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/alpha/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/resources/fine-tuning/alpha/index.ts"],"names":[],"mappings":"OAEO,EAAE,KAAK,EAAE;OACT,EACL,OAAO,EACP,KAAK,iBAAiB,EACtB,KAAK,sBAAsB,EAC3B,KAAK,eAAe,EACpB,KAAK,oBAAoB,GAC1B"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/alpha/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/alpha/index.js new file mode 100644 index 0000000000000000000000000000000000000000..2dbb68aa251db57a005f6b3823b14477ba7d08e9 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/alpha/index.js @@ -0,0 +1,9 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Graders = exports.Alpha = void 0; +var alpha_1 = require("./alpha.js"); +Object.defineProperty(exports, "Alpha", { enumerable: true, get: function () { return alpha_1.Alpha; } }); +var graders_1 = require("./graders.js"); +Object.defineProperty(exports, "Graders", { enumerable: true, get: function () { return graders_1.Graders; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/alpha/index.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/alpha/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..f9804380cb031423700a7978b71bb39729b0dac2 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/alpha/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/resources/fine-tuning/alpha/index.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAEtF,oCAAgC;AAAvB,8FAAA,KAAK,OAAA;AACd,wCAMmB;AALjB,kGAAA,OAAO,OAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/alpha/index.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/alpha/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d67cbef850cd79bbead5360961020fbfff4238c1 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/alpha/index.mjs @@ -0,0 +1,4 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +export { Alpha } from "./alpha.mjs"; +export { Graders, } from "./graders.mjs"; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/alpha/index.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/alpha/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..8e4cc1d8c19e65aa38ebda52533c49c28d0e5e61 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/alpha/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../../../src/resources/fine-tuning/alpha/index.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAE/E,EAAE,KAAK,EAAE;OACT,EACL,OAAO,GAKR"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..f7a44268caf0cd4209433ada8d69738a96aab80d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.d.mts @@ -0,0 +1,10 @@ +import { APIResource } from "../../../core/resource.mjs"; +import * as PermissionsAPI from "./permissions.mjs"; +import { PermissionCreateParams, PermissionCreateResponse, PermissionCreateResponsesPage, PermissionDeleteParams, PermissionDeleteResponse, PermissionRetrieveParams, PermissionRetrieveResponse, Permissions } from "./permissions.mjs"; +export declare class Checkpoints extends APIResource { + permissions: PermissionsAPI.Permissions; +} +export declare namespace Checkpoints { + export { Permissions as Permissions, type PermissionCreateResponse as PermissionCreateResponse, type PermissionRetrieveResponse as PermissionRetrieveResponse, type PermissionDeleteResponse as PermissionDeleteResponse, type PermissionCreateResponsesPage as PermissionCreateResponsesPage, type PermissionCreateParams as PermissionCreateParams, type PermissionRetrieveParams as PermissionRetrieveParams, type PermissionDeleteParams as PermissionDeleteParams, }; +} +//# sourceMappingURL=checkpoints.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..863cbca201aa7a98b718d1a97114d0bea25eb2de --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"checkpoints.d.mts","sourceRoot":"","sources":["../../../src/resources/fine-tuning/checkpoints/checkpoints.ts"],"names":[],"mappings":"OAEO,EAAE,WAAW,EAAE;OACf,KAAK,cAAc;OACnB,EACL,sBAAsB,EACtB,wBAAwB,EACxB,6BAA6B,EAC7B,sBAAsB,EACtB,wBAAwB,EACxB,wBAAwB,EACxB,0BAA0B,EAC1B,WAAW,EACZ;AAED,qBAAa,WAAY,SAAQ,WAAW;IAC1C,WAAW,EAAE,cAAc,CAAC,WAAW,CAAgD;CACxF;AAID,MAAM,CAAC,OAAO,WAAW,WAAW,CAAC;IACnC,OAAO,EACL,WAAW,IAAI,WAAW,EAC1B,KAAK,wBAAwB,IAAI,wBAAwB,EACzD,KAAK,0BAA0B,IAAI,0BAA0B,EAC7D,KAAK,wBAAwB,IAAI,wBAAwB,EACzD,KAAK,6BAA6B,IAAI,6BAA6B,EACnE,KAAK,sBAAsB,IAAI,sBAAsB,EACrD,KAAK,wBAAwB,IAAI,wBAAwB,EACzD,KAAK,sBAAsB,IAAI,sBAAsB,GACtD,CAAC;CACH"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4ad818ea7c6e8abe62f66c454be61c6957687050 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.d.ts @@ -0,0 +1,10 @@ +import { APIResource } from "../../../core/resource.js"; +import * as PermissionsAPI from "./permissions.js"; +import { PermissionCreateParams, PermissionCreateResponse, PermissionCreateResponsesPage, PermissionDeleteParams, PermissionDeleteResponse, PermissionRetrieveParams, PermissionRetrieveResponse, Permissions } from "./permissions.js"; +export declare class Checkpoints extends APIResource { + permissions: PermissionsAPI.Permissions; +} +export declare namespace Checkpoints { + export { Permissions as Permissions, type PermissionCreateResponse as PermissionCreateResponse, type PermissionRetrieveResponse as PermissionRetrieveResponse, type PermissionDeleteResponse as PermissionDeleteResponse, type PermissionCreateResponsesPage as PermissionCreateResponsesPage, type PermissionCreateParams as PermissionCreateParams, type PermissionRetrieveParams as PermissionRetrieveParams, type PermissionDeleteParams as PermissionDeleteParams, }; +} +//# sourceMappingURL=checkpoints.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..6cc942e789456051e36cc88598be4262ff996d9a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"checkpoints.d.ts","sourceRoot":"","sources":["../../../src/resources/fine-tuning/checkpoints/checkpoints.ts"],"names":[],"mappings":"OAEO,EAAE,WAAW,EAAE;OACf,KAAK,cAAc;OACnB,EACL,sBAAsB,EACtB,wBAAwB,EACxB,6BAA6B,EAC7B,sBAAsB,EACtB,wBAAwB,EACxB,wBAAwB,EACxB,0BAA0B,EAC1B,WAAW,EACZ;AAED,qBAAa,WAAY,SAAQ,WAAW;IAC1C,WAAW,EAAE,cAAc,CAAC,WAAW,CAAgD;CACxF;AAID,MAAM,CAAC,OAAO,WAAW,WAAW,CAAC;IACnC,OAAO,EACL,WAAW,IAAI,WAAW,EAC1B,KAAK,wBAAwB,IAAI,wBAAwB,EACzD,KAAK,0BAA0B,IAAI,0BAA0B,EAC7D,KAAK,wBAAwB,IAAI,wBAAwB,EACzD,KAAK,6BAA6B,IAAI,6BAA6B,EACnE,KAAK,sBAAsB,IAAI,sBAAsB,EACrD,KAAK,wBAAwB,IAAI,wBAAwB,EACzD,KAAK,sBAAsB,IAAI,sBAAsB,GACtD,CAAC;CACH"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.js new file mode 100644 index 0000000000000000000000000000000000000000..3bae7a413f87a548b8521d8c24c12c89d05103b9 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.js @@ -0,0 +1,17 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Checkpoints = void 0; +const tslib_1 = require("../../../internal/tslib.js"); +const resource_1 = require("../../../core/resource.js"); +const PermissionsAPI = tslib_1.__importStar(require("./permissions.js")); +const permissions_1 = require("./permissions.js"); +class Checkpoints extends resource_1.APIResource { + constructor() { + super(...arguments); + this.permissions = new PermissionsAPI.Permissions(this._client); + } +} +exports.Checkpoints = Checkpoints; +Checkpoints.Permissions = permissions_1.Permissions; +//# sourceMappingURL=checkpoints.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.js.map new file mode 100644 index 0000000000000000000000000000000000000000..61ed86f014fac7f9f8b3ba8f25ed4face46ac6c1 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.js.map @@ -0,0 +1 @@ +{"version":3,"file":"checkpoints.js","sourceRoot":"","sources":["../../../src/resources/fine-tuning/checkpoints/checkpoints.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;;AAEtF,wDAAqD;AACrD,yEAAgD;AAChD,kDASuB;AAEvB,MAAa,WAAY,SAAQ,sBAAW;IAA5C;;QACE,gBAAW,GAA+B,IAAI,cAAc,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACzF,CAAC;CAAA;AAFD,kCAEC;AAED,WAAW,CAAC,WAAW,GAAG,yBAAW,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a76e13d6f9e0ce4fd4b001d83ed1462192ad6253 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs @@ -0,0 +1,12 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from "../../../core/resource.mjs"; +import * as PermissionsAPI from "./permissions.mjs"; +import { Permissions, } from "./permissions.mjs"; +export class Checkpoints extends APIResource { + constructor() { + super(...arguments); + this.permissions = new PermissionsAPI.Permissions(this._client); + } +} +Checkpoints.Permissions = Permissions; +//# sourceMappingURL=checkpoints.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..fdfab44ca66dc4d008d0b1d523466e7be44dfa07 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"checkpoints.mjs","sourceRoot":"","sources":["../../../src/resources/fine-tuning/checkpoints/checkpoints.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAE/E,EAAE,WAAW,EAAE;OACf,KAAK,cAAc;OACnB,EAQL,WAAW,GACZ;AAED,MAAM,OAAO,WAAY,SAAQ,WAAW;IAA5C;;QACE,gBAAW,GAA+B,IAAI,cAAc,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACzF,CAAC;CAAA;AAED,WAAW,CAAC,WAAW,GAAG,WAAW,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/index.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..5b0092f430775b5692d3bc1539d4a2b59aa21f86 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/index.d.mts @@ -0,0 +1,3 @@ +export { Checkpoints } from "./checkpoints.mjs"; +export { Permissions, type PermissionCreateResponse, type PermissionRetrieveResponse, type PermissionDeleteResponse, type PermissionCreateParams, type PermissionRetrieveParams, type PermissionDeleteParams, type PermissionCreateResponsesPage, } from "./permissions.mjs"; +//# sourceMappingURL=index.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/index.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/index.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..753bc7fcededbfe6bc1afccc8ca21da8024f05c1 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/index.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../../../src/resources/fine-tuning/checkpoints/index.ts"],"names":[],"mappings":"OAEO,EAAE,WAAW,EAAE;OACf,EACL,WAAW,EACX,KAAK,wBAAwB,EAC7B,KAAK,0BAA0B,EAC/B,KAAK,wBAAwB,EAC7B,KAAK,sBAAsB,EAC3B,KAAK,wBAAwB,EAC7B,KAAK,sBAAsB,EAC3B,KAAK,6BAA6B,GACnC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/index.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6953e4933e2b5a56d6e5c3797c6422f6e4682bf3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/index.d.ts @@ -0,0 +1,3 @@ +export { Checkpoints } from "./checkpoints.js"; +export { Permissions, type PermissionCreateResponse, type PermissionRetrieveResponse, type PermissionDeleteResponse, type PermissionCreateParams, type PermissionRetrieveParams, type PermissionDeleteParams, type PermissionCreateResponsesPage, } from "./permissions.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/index.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..7e09abf28589319620e3513d8ac2306580cd1668 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/resources/fine-tuning/checkpoints/index.ts"],"names":[],"mappings":"OAEO,EAAE,WAAW,EAAE;OACf,EACL,WAAW,EACX,KAAK,wBAAwB,EAC7B,KAAK,0BAA0B,EAC/B,KAAK,wBAAwB,EAC7B,KAAK,sBAAsB,EAC3B,KAAK,wBAAwB,EAC7B,KAAK,sBAAsB,EAC3B,KAAK,6BAA6B,GACnC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e845d5d395d69b363489bdef15b12642afbcc5fb --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/index.js @@ -0,0 +1,9 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Permissions = exports.Checkpoints = void 0; +var checkpoints_1 = require("./checkpoints.js"); +Object.defineProperty(exports, "Checkpoints", { enumerable: true, get: function () { return checkpoints_1.Checkpoints; } }); +var permissions_1 = require("./permissions.js"); +Object.defineProperty(exports, "Permissions", { enumerable: true, get: function () { return permissions_1.Permissions; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/index.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..cd26f840184450a0b8b3accab0f82b05afe086a0 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/resources/fine-tuning/checkpoints/index.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAEtF,gDAA4C;AAAnC,0GAAA,WAAW,OAAA;AACpB,gDASuB;AARrB,0GAAA,WAAW,OAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/index.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d3a52462191eba7df0cc71a2643600548a9f9420 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/index.mjs @@ -0,0 +1,4 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +export { Checkpoints } from "./checkpoints.mjs"; +export { Permissions, } from "./permissions.mjs"; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/index.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..175d84e6a946f839c7d39feb324bcdb0d7c7c0c8 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../../../src/resources/fine-tuning/checkpoints/index.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAE/E,EAAE,WAAW,EAAE;OACf,EACL,WAAW,GAQZ"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/permissions.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/permissions.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..cbaac796c81b53fe768f140cd1c497e0ad20e5cf --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/permissions.d.mts @@ -0,0 +1,160 @@ +import { APIResource } from "../../../core/resource.mjs"; +import { APIPromise } from "../../../core/api-promise.mjs"; +import { Page, PagePromise } from "../../../core/pagination.mjs"; +import { RequestOptions } from "../../../internal/request-options.mjs"; +export declare class Permissions extends APIResource { + /** + * **NOTE:** Calling this endpoint requires an [admin API key](../admin-api-keys). + * + * This enables organization owners to share fine-tuned models with other projects + * in their organization. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const permissionCreateResponse of client.fineTuning.checkpoints.permissions.create( + * 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd', + * { project_ids: ['string'] }, + * )) { + * // ... + * } + * ``` + */ + create(fineTunedModelCheckpoint: string, body: PermissionCreateParams, options?: RequestOptions): PagePromise; + /** + * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). + * + * Organization owners can use this endpoint to view all permissions for a + * fine-tuned model checkpoint. + * + * @example + * ```ts + * const permission = + * await client.fineTuning.checkpoints.permissions.retrieve( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + retrieve(fineTunedModelCheckpoint: string, query?: PermissionRetrieveParams | null | undefined, options?: RequestOptions): APIPromise; + /** + * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). + * + * Organization owners can use this endpoint to delete a permission for a + * fine-tuned model checkpoint. + * + * @example + * ```ts + * const permission = + * await client.fineTuning.checkpoints.permissions.delete( + * 'cp_zc4Q7MP6XxulcVzj4MZdwsAB', + * { + * fine_tuned_model_checkpoint: + * 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd', + * }, + * ); + * ``` + */ + delete(permissionID: string, params: PermissionDeleteParams, options?: RequestOptions): APIPromise; +} +export type PermissionCreateResponsesPage = Page; +/** + * The `checkpoint.permission` object represents a permission for a fine-tuned + * model checkpoint. + */ +export interface PermissionCreateResponse { + /** + * The permission identifier, which can be referenced in the API endpoints. + */ + id: string; + /** + * The Unix timestamp (in seconds) for when the permission was created. + */ + created_at: number; + /** + * The object type, which is always "checkpoint.permission". + */ + object: 'checkpoint.permission'; + /** + * The project identifier that the permission is for. + */ + project_id: string; +} +export interface PermissionRetrieveResponse { + data: Array; + has_more: boolean; + object: 'list'; + first_id?: string | null; + last_id?: string | null; +} +export declare namespace PermissionRetrieveResponse { + /** + * The `checkpoint.permission` object represents a permission for a fine-tuned + * model checkpoint. + */ + interface Data { + /** + * The permission identifier, which can be referenced in the API endpoints. + */ + id: string; + /** + * The Unix timestamp (in seconds) for when the permission was created. + */ + created_at: number; + /** + * The object type, which is always "checkpoint.permission". + */ + object: 'checkpoint.permission'; + /** + * The project identifier that the permission is for. + */ + project_id: string; + } +} +export interface PermissionDeleteResponse { + /** + * The ID of the fine-tuned model checkpoint permission that was deleted. + */ + id: string; + /** + * Whether the fine-tuned model checkpoint permission was successfully deleted. + */ + deleted: boolean; + /** + * The object type, which is always "checkpoint.permission". + */ + object: 'checkpoint.permission'; +} +export interface PermissionCreateParams { + /** + * The project identifiers to grant access to. + */ + project_ids: Array; +} +export interface PermissionRetrieveParams { + /** + * Identifier for the last permission ID from the previous pagination request. + */ + after?: string; + /** + * Number of permissions to retrieve. + */ + limit?: number; + /** + * The order in which to retrieve permissions. + */ + order?: 'ascending' | 'descending'; + /** + * The ID of the project to get permissions for. + */ + project_id?: string; +} +export interface PermissionDeleteParams { + /** + * The ID of the fine-tuned model checkpoint to delete a permission for. + */ + fine_tuned_model_checkpoint: string; +} +export declare namespace Permissions { + export { type PermissionCreateResponse as PermissionCreateResponse, type PermissionRetrieveResponse as PermissionRetrieveResponse, type PermissionDeleteResponse as PermissionDeleteResponse, type PermissionCreateResponsesPage as PermissionCreateResponsesPage, type PermissionCreateParams as PermissionCreateParams, type PermissionRetrieveParams as PermissionRetrieveParams, type PermissionDeleteParams as PermissionDeleteParams, }; +} +//# sourceMappingURL=permissions.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/permissions.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/permissions.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..ff5dd8a559874de64817054bcd8326c5b6934065 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/permissions.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"permissions.d.mts","sourceRoot":"","sources":["../../../src/resources/fine-tuning/checkpoints/permissions.ts"],"names":[],"mappings":"OAEO,EAAE,WAAW,EAAE;OACf,EAAE,UAAU,EAAE;OACd,EAAE,IAAI,EAAE,WAAW,EAAE;OACrB,EAAE,cAAc,EAAE;AAGzB,qBAAa,WAAY,SAAQ,WAAW;IAC1C;;;;;;;;;;;;;;;;OAgBG;IACH,MAAM,CACJ,wBAAwB,EAAE,MAAM,EAChC,IAAI,EAAE,sBAAsB,EAC5B,OAAO,CAAC,EAAE,cAAc,GACvB,WAAW,CAAC,6BAA6B,EAAE,wBAAwB,CAAC;IAQvE;;;;;;;;;;;;;OAaG;IACH,QAAQ,CACN,wBAAwB,EAAE,MAAM,EAChC,KAAK,GAAE,wBAAwB,GAAG,IAAI,GAAG,SAAc,EACvD,OAAO,CAAC,EAAE,cAAc,GACvB,UAAU,CAAC,0BAA0B,CAAC;IAOzC;;;;;;;;;;;;;;;;;OAiBG;IACH,MAAM,CACJ,YAAY,EAAE,MAAM,EACpB,MAAM,EAAE,sBAAsB,EAC9B,OAAO,CAAC,EAAE,cAAc,GACvB,UAAU,CAAC,wBAAwB,CAAC;CAOxC;AAGD,MAAM,M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,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,sBAAsB;IACrC;;OAEG;IACH,2BAA2B,EAAE,MAAM,CAAC;CACrC;AAED,MAAM,CAAC,OAAO,WAAW,WAAW,CAAC;IACnC,OAAO,EACL,KAAK,wBAAwB,IAAI,wBAAwB,EACzD,KAAK,0BAA0B,IAAI,0BAA0B,EAC7D,KAAK,wBAAwB,IAAI,wBAAwB,EACzD,KAAK,6BAA6B,IAAI,6BAA6B,EACnE,KAAK,sBAAsB,IAAI,sBAAsB,EACrD,KAAK,wBAAwB,IAAI,wBAAwB,EACzD,KAAK,sBAAsB,IAAI,sBAAsB,GACtD,CAAC;CACH"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/permissions.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/permissions.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b95dc65694d6b41d560b648d9303b9514d08622b --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/permissions.d.ts @@ -0,0 +1,160 @@ +import { APIResource } from "../../../core/resource.js"; +import { APIPromise } from "../../../core/api-promise.js"; +import { Page, PagePromise } from "../../../core/pagination.js"; +import { RequestOptions } from "../../../internal/request-options.js"; +export declare class Permissions extends APIResource { + /** + * **NOTE:** Calling this endpoint requires an [admin API key](../admin-api-keys). + * + * This enables organization owners to share fine-tuned models with other projects + * in their organization. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const permissionCreateResponse of client.fineTuning.checkpoints.permissions.create( + * 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd', + * { project_ids: ['string'] }, + * )) { + * // ... + * } + * ``` + */ + create(fineTunedModelCheckpoint: string, body: PermissionCreateParams, options?: RequestOptions): PagePromise; + /** + * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). + * + * Organization owners can use this endpoint to view all permissions for a + * fine-tuned model checkpoint. + * + * @example + * ```ts + * const permission = + * await client.fineTuning.checkpoints.permissions.retrieve( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + retrieve(fineTunedModelCheckpoint: string, query?: PermissionRetrieveParams | null | undefined, options?: RequestOptions): APIPromise; + /** + * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). + * + * Organization owners can use this endpoint to delete a permission for a + * fine-tuned model checkpoint. + * + * @example + * ```ts + * const permission = + * await client.fineTuning.checkpoints.permissions.delete( + * 'cp_zc4Q7MP6XxulcVzj4MZdwsAB', + * { + * fine_tuned_model_checkpoint: + * 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd', + * }, + * ); + * ``` + */ + delete(permissionID: string, params: PermissionDeleteParams, options?: RequestOptions): APIPromise; +} +export type PermissionCreateResponsesPage = Page; +/** + * The `checkpoint.permission` object represents a permission for a fine-tuned + * model checkpoint. + */ +export interface PermissionCreateResponse { + /** + * The permission identifier, which can be referenced in the API endpoints. + */ + id: string; + /** + * The Unix timestamp (in seconds) for when the permission was created. + */ + created_at: number; + /** + * The object type, which is always "checkpoint.permission". + */ + object: 'checkpoint.permission'; + /** + * The project identifier that the permission is for. + */ + project_id: string; +} +export interface PermissionRetrieveResponse { + data: Array; + has_more: boolean; + object: 'list'; + first_id?: string | null; + last_id?: string | null; +} +export declare namespace PermissionRetrieveResponse { + /** + * The `checkpoint.permission` object represents a permission for a fine-tuned + * model checkpoint. + */ + interface Data { + /** + * The permission identifier, which can be referenced in the API endpoints. + */ + id: string; + /** + * The Unix timestamp (in seconds) for when the permission was created. + */ + created_at: number; + /** + * The object type, which is always "checkpoint.permission". + */ + object: 'checkpoint.permission'; + /** + * The project identifier that the permission is for. + */ + project_id: string; + } +} +export interface PermissionDeleteResponse { + /** + * The ID of the fine-tuned model checkpoint permission that was deleted. + */ + id: string; + /** + * Whether the fine-tuned model checkpoint permission was successfully deleted. + */ + deleted: boolean; + /** + * The object type, which is always "checkpoint.permission". + */ + object: 'checkpoint.permission'; +} +export interface PermissionCreateParams { + /** + * The project identifiers to grant access to. + */ + project_ids: Array; +} +export interface PermissionRetrieveParams { + /** + * Identifier for the last permission ID from the previous pagination request. + */ + after?: string; + /** + * Number of permissions to retrieve. + */ + limit?: number; + /** + * The order in which to retrieve permissions. + */ + order?: 'ascending' | 'descending'; + /** + * The ID of the project to get permissions for. + */ + project_id?: string; +} +export interface PermissionDeleteParams { + /** + * The ID of the fine-tuned model checkpoint to delete a permission for. + */ + fine_tuned_model_checkpoint: string; +} +export declare namespace Permissions { + export { type PermissionCreateResponse as PermissionCreateResponse, type PermissionRetrieveResponse as PermissionRetrieveResponse, type PermissionDeleteResponse as PermissionDeleteResponse, type PermissionCreateResponsesPage as PermissionCreateResponsesPage, type PermissionCreateParams as PermissionCreateParams, type PermissionRetrieveParams as PermissionRetrieveParams, type PermissionDeleteParams as PermissionDeleteParams, }; +} +//# sourceMappingURL=permissions.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/permissions.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/permissions.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..530ad9e8078bda5f35985c6a5508fb477ce40948 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/permissions.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"permissions.d.ts","sourceRoot":"","sources":["../../../src/resources/fine-tuning/checkpoints/permissions.ts"],"names":[],"mappings":"OAEO,EAAE,WAAW,EAAE;OACf,EAAE,UAAU,EAAE;OACd,EAAE,IAAI,EAAE,WAAW,EAAE;OACrB,EAAE,cAAc,EAAE;AAGzB,qBAAa,WAAY,SAAQ,WAAW;IAC1C;;;;;;;;;;;;;;;;OAgBG;IACH,MAAM,CACJ,wBAAwB,EAAE,MAAM,EAChC,IAAI,EAAE,sBAAsB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B;IACvC;;OAEG;IACH,EAAE,EAAE,MAAM,CAAC;IAEX;;OAEG;IACH,OAAO,EAAE,OAAO,CAAC;IAEjB;;OAEG;IACH,MAAM,EAAE,uBAAuB,CAAC;CACjC;AAED,MAAM,WAAW,sBAAsB;IACrC;;OAEG;IACH,WAAW,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;CAC5B;AAED,MAAM,WAAW,wBAAwB;IACvC;;OAEG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;IAEf;;OAEG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;IAEf;;OAEG;IACH,KAAK,CAAC,EAAE,WAAW,GAAG,YAAY,CAAC;IAEnC;;OAEG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,sBAAsB;IACrC;;OAEG;IACH,2BAA2B,EAAE,MAAM,CAAC;CACrC;AAED,MAAM,CAAC,OAAO,WAAW,WAAW,CAAC;IACnC,OAAO,EACL,KAAK,wBAAwB,IAAI,wBAAwB,EACzD,KAAK,0BAA0B,IAAI,0BAA0B,EAC7D,KAAK,wBAAwB,IAAI,wBAAwB,EACzD,KAAK,6BAA6B,IAAI,6BAA6B,EACnE,KAAK,sBAAsB,IAAI,sBAAsB,EACrD,KAAK,wBAAwB,IAAI,wBAAwB,EACzD,KAAK,sBAAsB,IAAI,sBAAsB,GACtD,CAAC;CACH"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/permissions.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/permissions.js new file mode 100644 index 0000000000000000000000000000000000000000..a1a4a7264b525f54ee965e365d33dbcddd6fff75 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/permissions.js @@ -0,0 +1,73 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Permissions = void 0; +const resource_1 = require("../../../core/resource.js"); +const pagination_1 = require("../../../core/pagination.js"); +const path_1 = require("../../../internal/utils/path.js"); +class Permissions extends resource_1.APIResource { + /** + * **NOTE:** Calling this endpoint requires an [admin API key](../admin-api-keys). + * + * This enables organization owners to share fine-tuned models with other projects + * in their organization. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const permissionCreateResponse of client.fineTuning.checkpoints.permissions.create( + * 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd', + * { project_ids: ['string'] }, + * )) { + * // ... + * } + * ``` + */ + create(fineTunedModelCheckpoint, body, options) { + return this._client.getAPIList((0, path_1.path) `/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, (pagination_1.Page), { body, method: 'post', ...options }); + } + /** + * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). + * + * Organization owners can use this endpoint to view all permissions for a + * fine-tuned model checkpoint. + * + * @example + * ```ts + * const permission = + * await client.fineTuning.checkpoints.permissions.retrieve( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + retrieve(fineTunedModelCheckpoint, query = {}, options) { + return this._client.get((0, path_1.path) `/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, { + query, + ...options, + }); + } + /** + * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). + * + * Organization owners can use this endpoint to delete a permission for a + * fine-tuned model checkpoint. + * + * @example + * ```ts + * const permission = + * await client.fineTuning.checkpoints.permissions.delete( + * 'cp_zc4Q7MP6XxulcVzj4MZdwsAB', + * { + * fine_tuned_model_checkpoint: + * 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd', + * }, + * ); + * ``` + */ + delete(permissionID, params, options) { + const { fine_tuned_model_checkpoint } = params; + return this._client.delete((0, path_1.path) `/fine_tuning/checkpoints/${fine_tuned_model_checkpoint}/permissions/${permissionID}`, options); + } +} +exports.Permissions = Permissions; +//# sourceMappingURL=permissions.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/permissions.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/permissions.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ab49976a6772d5bdbe750ff57b9d940b19d8154f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/permissions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"permissions.js","sourceRoot":"","sources":["../../../src/resources/fine-tuning/checkpoints/permissions.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAEtF,wDAAqD;AAErD,4DAA6D;AAE7D,0DAAoD;AAEpD,MAAa,WAAY,SAAQ,sBAAW;IAC1C;;;;;;;;;;;;;;;;OAgBG;IACH,MAAM,CACJ,wBAAgC,EAChC,IAA4B,EAC5B,OAAwB;QAExB,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,CAC5B,IAAA,WAAI,EAAA,4BAA4B,wBAAwB,cAAc,EACtE,CAAA,iBAA8B,CAAA,EAC9B,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,EAAE,CACrC,CAAC;IACJ,CAAC;IAED;;;;;;;;;;;;;OAaG;IACH,QAAQ,CACN,wBAAgC,EAChC,QAAqD,EAAE,EACvD,OAAwB;QAExB,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,IAAA,WAAI,EAAA,4BAA4B,wBAAwB,cAAc,EAAE;YAC9F,KAAK;YACL,GAAG,OAAO;SACX,CAAC,CAAC;IACL,CAAC;IAED;;;;;;;;;;;;;;;;;OAiBG;IACH,MAAM,CACJ,YAAoB,EACpB,MAA8B,EAC9B,OAAwB;QAExB,MAAM,EAAE,2BAA2B,EAAE,GAAG,MAAM,CAAC;QAC/C,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM,CACxB,IAAA,WAAI,EAAA,4BAA4B,2BAA2B,gBAAgB,YAAY,EAAE,EACzF,OAAO,CACR,CAAC;IACJ,CAAC;CACF;AApFD,kCAoFC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/permissions.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/permissions.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a3c8a4e54b996f1e7ad43a90808867d79ba683d7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/permissions.mjs @@ -0,0 +1,69 @@ +// 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 { path } from "../../../internal/utils/path.mjs"; +export class Permissions extends APIResource { + /** + * **NOTE:** Calling this endpoint requires an [admin API key](../admin-api-keys). + * + * This enables organization owners to share fine-tuned models with other projects + * in their organization. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const permissionCreateResponse of client.fineTuning.checkpoints.permissions.create( + * 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd', + * { project_ids: ['string'] }, + * )) { + * // ... + * } + * ``` + */ + create(fineTunedModelCheckpoint, body, options) { + return this._client.getAPIList(path `/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, (Page), { body, method: 'post', ...options }); + } + /** + * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). + * + * Organization owners can use this endpoint to view all permissions for a + * fine-tuned model checkpoint. + * + * @example + * ```ts + * const permission = + * await client.fineTuning.checkpoints.permissions.retrieve( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + retrieve(fineTunedModelCheckpoint, query = {}, options) { + return this._client.get(path `/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, { + query, + ...options, + }); + } + /** + * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). + * + * Organization owners can use this endpoint to delete a permission for a + * fine-tuned model checkpoint. + * + * @example + * ```ts + * const permission = + * await client.fineTuning.checkpoints.permissions.delete( + * 'cp_zc4Q7MP6XxulcVzj4MZdwsAB', + * { + * fine_tuned_model_checkpoint: + * 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd', + * }, + * ); + * ``` + */ + delete(permissionID, params, options) { + const { fine_tuned_model_checkpoint } = params; + return this._client.delete(path `/fine_tuning/checkpoints/${fine_tuned_model_checkpoint}/permissions/${permissionID}`, options); + } +} +//# sourceMappingURL=permissions.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/permissions.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/permissions.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..a0f5887874bb8571fa63b40607c1046cb621f845 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/checkpoints/permissions.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"permissions.mjs","sourceRoot":"","sources":["../../../src/resources/fine-tuning/checkpoints/permissions.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAE/E,EAAE,WAAW,EAAE;OAEf,EAAE,IAAI,EAAe;OAErB,EAAE,IAAI,EAAE;AAEf,MAAM,OAAO,WAAY,SAAQ,WAAW;IAC1C;;;;;;;;;;;;;;;;OAgBG;IACH,MAAM,CACJ,wBAAgC,EAChC,IAA4B,EAC5B,OAAwB;QAExB,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,CAC5B,IAAI,CAAA,4BAA4B,wBAAwB,cAAc,EACtE,CAAA,IAA8B,CAAA,EAC9B,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,EAAE,CACrC,CAAC;IACJ,CAAC;IAED;;;;;;;;;;;;;OAaG;IACH,QAAQ,CACN,wBAAgC,EAChC,QAAqD,EAAE,EACvD,OAAwB;QAExB,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAA,4BAA4B,wBAAwB,cAAc,EAAE;YAC9F,KAAK;YACL,GAAG,OAAO;SACX,CAAC,CAAC;IACL,CAAC;IAED;;;;;;;;;;;;;;;;;OAiBG;IACH,MAAM,CACJ,YAAoB,EACpB,MAA8B,EAC9B,OAAwB;QAExB,MAAM,EAAE,2BAA2B,EAAE,GAAG,MAAM,CAAC;QAC/C,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM,CACxB,IAAI,CAAA,4BAA4B,2BAA2B,gBAAgB,YAAY,EAAE,EACzF,OAAO,CACR,CAAC;IACJ,CAAC;CACF"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/checkpoints.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/checkpoints.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..5028f5bad0fd3696eda712c3ed4514419c90a3b8 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/checkpoints.d.mts @@ -0,0 +1,74 @@ +import { APIResource } from "../../../core/resource.mjs"; +import { CursorPage, type CursorPageParams, PagePromise } from "../../../core/pagination.mjs"; +import { RequestOptions } from "../../../internal/request-options.mjs"; +export declare class Checkpoints extends APIResource { + /** + * List checkpoints for a fine-tuning job. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const fineTuningJobCheckpoint of client.fineTuning.jobs.checkpoints.list( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * )) { + * // ... + * } + * ``` + */ + list(fineTuningJobID: string, query?: CheckpointListParams | null | undefined, options?: RequestOptions): PagePromise; +} +export type FineTuningJobCheckpointsPage = CursorPage; +/** + * The `fine_tuning.job.checkpoint` object represents a model checkpoint for a + * fine-tuning job that is ready to use. + */ +export interface FineTuningJobCheckpoint { + /** + * The checkpoint identifier, which can be referenced in the API endpoints. + */ + id: string; + /** + * The Unix timestamp (in seconds) for when the checkpoint was created. + */ + created_at: number; + /** + * The name of the fine-tuned checkpoint model that is created. + */ + fine_tuned_model_checkpoint: string; + /** + * The name of the fine-tuning job that this checkpoint was created from. + */ + fine_tuning_job_id: string; + /** + * Metrics at the step number during the fine-tuning job. + */ + metrics: FineTuningJobCheckpoint.Metrics; + /** + * The object type, which is always "fine_tuning.job.checkpoint". + */ + object: 'fine_tuning.job.checkpoint'; + /** + * The step number that the checkpoint was created at. + */ + step_number: number; +} +export declare namespace FineTuningJobCheckpoint { + /** + * Metrics at the step number during the fine-tuning job. + */ + interface Metrics { + full_valid_loss?: number; + full_valid_mean_token_accuracy?: number; + step?: number; + train_loss?: number; + train_mean_token_accuracy?: number; + valid_loss?: number; + valid_mean_token_accuracy?: number; + } +} +export interface CheckpointListParams extends CursorPageParams { +} +export declare namespace Checkpoints { + export { type FineTuningJobCheckpoint as FineTuningJobCheckpoint, type FineTuningJobCheckpointsPage as FineTuningJobCheckpointsPage, type CheckpointListParams as CheckpointListParams, }; +} +//# sourceMappingURL=checkpoints.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/checkpoints.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/checkpoints.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..ed9c25d7420f5eb670bd83288114f22361e9897d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/checkpoints.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"checkpoints.d.mts","sourceRoot":"","sources":["../../../src/resources/fine-tuning/jobs/checkpoints.ts"],"names":[],"mappings":"OAEO,EAAE,WAAW,EAAE;OACf,EAAE,UAAU,EAAE,KAAK,gBAAgB,EAAE,WAAW,EAAE;OAClD,EAAE,cAAc,EAAE;AAGzB,qBAAa,WAAY,SAAQ,WAAW;IAC1C;;;;;;;;;;;;OAYG;IACH,IAAI,CACF,eAAe,EAAE,MAAM,EACvB,KAAK,GAAE,oBAAoB,GAAG,IAAI,GAAG,SAAc,EACnD,OAAO,CAAC,EAAE,cAAc,GACvB,WAAW,CAAC,4BAA4B,EAAE,uBAAuB,CAAC;CAOtE;AAED,MAAM,MAAM,4BAA4B,GAAG,UAAU,CAAC,uBAAuB,CAAC,CAAC;AAE/E;;;GAGG;AACH,MAAM,WAAW,uBAAuB;IACtC;;OAEG;IACH,EAAE,EAAE,MAAM,CAAC;IAEX;;OAEG;IACH,UAAU,EAAE,MAAM,CAAC;IAEnB;;OAEG;IACH,2BAA2B,EAAE,MAAM,CAAC;IAEpC;;OAEG;IACH,kBAAkB,EAAE,MAAM,CAAC;IAE3B;;OAEG;IACH,OAAO,EAAE,uBAAuB,CAAC,OAAO,CAAC;IAEzC;;OAEG;IACH,MAAM,EAAE,4BAA4B,CAAC;IAErC;;OAEG;IACH,WAAW,EAAE,MAAM,CAAC;CACrB;AAED,yBAAiB,uBAAuB,CAAC;IACvC;;OAEG;IACH,UAAiB,OAAO;QACtB,eAAe,CAAC,EAAE,MAAM,CAAC;QAEzB,8BAA8B,CAAC,EAAE,MAAM,CAAC;QAExC,IAAI,CAAC,EAAE,MAAM,CAAC;QAEd,UAAU,CAAC,EAAE,MAAM,CAAC;QAEpB,yBAAyB,CAAC,EAAE,MAAM,CAAC;QAEnC,UAAU,CAAC,EAAE,MAAM,CAAC;QAEpB,yBAAyB,CAAC,EAAE,MAAM,CAAC;KACpC;CACF;AAED,MAAM,WAAW,oBAAqB,SAAQ,gBAAgB;CAAG;AAEjE,MAAM,CAAC,OAAO,WAAW,WAAW,CAAC;IACnC,OAAO,EACL,KAAK,uBAAuB,IAAI,uBAAuB,EACvD,KAAK,4BAA4B,IAAI,4BAA4B,EACjE,KAAK,oBAAoB,IAAI,oBAAoB,GAClD,CAAC;CACH"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/checkpoints.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/checkpoints.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1ec97a80e946e5efe4e0bba8458ae7d845a91aad --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/checkpoints.d.ts @@ -0,0 +1,74 @@ +import { APIResource } from "../../../core/resource.js"; +import { CursorPage, type CursorPageParams, PagePromise } from "../../../core/pagination.js"; +import { RequestOptions } from "../../../internal/request-options.js"; +export declare class Checkpoints extends APIResource { + /** + * List checkpoints for a fine-tuning job. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const fineTuningJobCheckpoint of client.fineTuning.jobs.checkpoints.list( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * )) { + * // ... + * } + * ``` + */ + list(fineTuningJobID: string, query?: CheckpointListParams | null | undefined, options?: RequestOptions): PagePromise; +} +export type FineTuningJobCheckpointsPage = CursorPage; +/** + * The `fine_tuning.job.checkpoint` object represents a model checkpoint for a + * fine-tuning job that is ready to use. + */ +export interface FineTuningJobCheckpoint { + /** + * The checkpoint identifier, which can be referenced in the API endpoints. + */ + id: string; + /** + * The Unix timestamp (in seconds) for when the checkpoint was created. + */ + created_at: number; + /** + * The name of the fine-tuned checkpoint model that is created. + */ + fine_tuned_model_checkpoint: string; + /** + * The name of the fine-tuning job that this checkpoint was created from. + */ + fine_tuning_job_id: string; + /** + * Metrics at the step number during the fine-tuning job. + */ + metrics: FineTuningJobCheckpoint.Metrics; + /** + * The object type, which is always "fine_tuning.job.checkpoint". + */ + object: 'fine_tuning.job.checkpoint'; + /** + * The step number that the checkpoint was created at. + */ + step_number: number; +} +export declare namespace FineTuningJobCheckpoint { + /** + * Metrics at the step number during the fine-tuning job. + */ + interface Metrics { + full_valid_loss?: number; + full_valid_mean_token_accuracy?: number; + step?: number; + train_loss?: number; + train_mean_token_accuracy?: number; + valid_loss?: number; + valid_mean_token_accuracy?: number; + } +} +export interface CheckpointListParams extends CursorPageParams { +} +export declare namespace Checkpoints { + export { type FineTuningJobCheckpoint as FineTuningJobCheckpoint, type FineTuningJobCheckpointsPage as FineTuningJobCheckpointsPage, type CheckpointListParams as CheckpointListParams, }; +} +//# sourceMappingURL=checkpoints.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/checkpoints.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/checkpoints.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..49f49baa28572641f6057adfb4f2bab9c0a28d55 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/checkpoints.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"checkpoints.d.ts","sourceRoot":"","sources":["../../../src/resources/fine-tuning/jobs/checkpoints.ts"],"names":[],"mappings":"OAEO,EAAE,WAAW,EAAE;OACf,EAAE,UAAU,EAAE,KAAK,gBAAgB,EAAE,WAAW,EAAE;OAClD,EAAE,cAAc,EAAE;AAGzB,qBAAa,WAAY,SAAQ,WAAW;IAC1C;;;;;;;;;;;;OAYG;IACH,IAAI,CACF,eAAe,EAAE,MAAM,EACvB,KAAK,GAAE,oBAAoB,GAAG,IAAI,GAAG,SAAc,EACnD,OAAO,CAAC,EAAE,cAAc,GACvB,WAAW,CAAC,4BAA4B,EAAE,uBAAuB,CAAC;CAOtE;AAED,MAAM,MAAM,4BAA4B,GAAG,UAAU,CAAC,uBAAuB,CAAC,CAAC;AAE/E;;;GAGG;AACH,MAAM,WAAW,uBAAuB;IACtC;;OAEG;IACH,EAAE,EAAE,MAAM,CAAC;IAEX;;OAEG;IACH,UAAU,EAAE,MAAM,CAAC;IAEnB;;OAEG;IACH,2BAA2B,EAAE,MAAM,CAAC;IAEpC;;OAEG;IACH,kBAAkB,EAAE,MAAM,CAAC;IAE3B;;OAEG;IACH,OAAO,EAAE,uBAAuB,CAAC,OAAO,CAAC;IAEzC;;OAEG;IACH,MAAM,EAAE,4BAA4B,CAAC;IAErC;;OAEG;IACH,WAAW,EAAE,MAAM,CAAC;CACrB;AAED,yBAAiB,uBAAuB,CAAC;IACvC;;OAEG;IACH,UAAiB,OAAO;QACtB,eAAe,CAAC,EAAE,MAAM,CAAC;QAEzB,8BAA8B,CAAC,EAAE,MAAM,CAAC;QAExC,IAAI,CAAC,EAAE,MAAM,CAAC;QAEd,UAAU,CAAC,EAAE,MAAM,CAAC;QAEpB,yBAAyB,CAAC,EAAE,MAAM,CAAC;QAEnC,UAAU,CAAC,EAAE,MAAM,CAAC;QAEpB,yBAAyB,CAAC,EAAE,MAAM,CAAC;KACpC;CACF;AAED,MAAM,WAAW,oBAAqB,SAAQ,gBAAgB;CAAG;AAEjE,MAAM,CAAC,OAAO,WAAW,WAAW,CAAC;IACnC,OAAO,EACL,KAAK,uBAAuB,IAAI,uBAAuB,EACvD,KAAK,4BAA4B,IAAI,4BAA4B,EACjE,KAAK,oBAAoB,IAAI,oBAAoB,GAClD,CAAC;CACH"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/checkpoints.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/checkpoints.js new file mode 100644 index 0000000000000000000000000000000000000000..5e4e68354f813c80a0c7504a6c9d3b00ec2ac71c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/checkpoints.js @@ -0,0 +1,27 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Checkpoints = void 0; +const resource_1 = require("../../../core/resource.js"); +const pagination_1 = require("../../../core/pagination.js"); +const path_1 = require("../../../internal/utils/path.js"); +class Checkpoints extends resource_1.APIResource { + /** + * List checkpoints for a fine-tuning job. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const fineTuningJobCheckpoint of client.fineTuning.jobs.checkpoints.list( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * )) { + * // ... + * } + * ``` + */ + list(fineTuningJobID, query = {}, options) { + return this._client.getAPIList((0, path_1.path) `/fine_tuning/jobs/${fineTuningJobID}/checkpoints`, (pagination_1.CursorPage), { query, ...options }); + } +} +exports.Checkpoints = Checkpoints; +//# sourceMappingURL=checkpoints.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/checkpoints.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/checkpoints.js.map new file mode 100644 index 0000000000000000000000000000000000000000..0aaa078380bf3672da5bc4f18d2d02a20a3bf407 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/checkpoints.js.map @@ -0,0 +1 @@ +{"version":3,"file":"checkpoints.js","sourceRoot":"","sources":["../../../src/resources/fine-tuning/jobs/checkpoints.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAEtF,wDAAqD;AACrD,4DAA0F;AAE1F,0DAAoD;AAEpD,MAAa,WAAY,SAAQ,sBAAW;IAC1C;;;;;;;;;;;;OAYG;IACH,IAAI,CACF,eAAuB,EACvB,QAAiD,EAAE,EACnD,OAAwB;QAExB,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,CAC5B,IAAA,WAAI,EAAA,qBAAqB,eAAe,cAAc,EACtD,CAAA,uBAAmC,CAAA,EACnC,EAAE,KAAK,EAAE,GAAG,OAAO,EAAE,CACtB,CAAC;IACJ,CAAC;CACF;AAzBD,kCAyBC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6d2b3c1760227f21f20cf7c794cf7897ba0acd37 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs @@ -0,0 +1,23 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from "../../../core/resource.mjs"; +import { CursorPage } from "../../../core/pagination.mjs"; +import { path } from "../../../internal/utils/path.mjs"; +export class Checkpoints extends APIResource { + /** + * List checkpoints for a fine-tuning job. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const fineTuningJobCheckpoint of client.fineTuning.jobs.checkpoints.list( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * )) { + * // ... + * } + * ``` + */ + list(fineTuningJobID, query = {}, options) { + return this._client.getAPIList(path `/fine_tuning/jobs/${fineTuningJobID}/checkpoints`, (CursorPage), { query, ...options }); + } +} +//# sourceMappingURL=checkpoints.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..304415553732681e19dc6cd14675856e593edb82 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"checkpoints.mjs","sourceRoot":"","sources":["../../../src/resources/fine-tuning/jobs/checkpoints.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAE/E,EAAE,WAAW,EAAE;OACf,EAAE,UAAU,EAAsC;OAElD,EAAE,IAAI,EAAE;AAEf,MAAM,OAAO,WAAY,SAAQ,WAAW;IAC1C;;;;;;;;;;;;OAYG;IACH,IAAI,CACF,eAAuB,EACvB,QAAiD,EAAE,EACnD,OAAwB;QAExB,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,CAC5B,IAAI,CAAA,qBAAqB,eAAe,cAAc,EACtD,CAAA,UAAmC,CAAA,EACnC,EAAE,KAAK,EAAE,GAAG,OAAO,EAAE,CACtB,CAAC;IACJ,CAAC;CACF"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/index.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..e51220bc7fe11fd38915c64695a0bc95399e9ad8 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/index.d.mts @@ -0,0 +1,3 @@ +export { Checkpoints, type FineTuningJobCheckpoint, type CheckpointListParams, type FineTuningJobCheckpointsPage, } from "./checkpoints.mjs"; +export { Jobs, type FineTuningJob, type FineTuningJobEvent, type FineTuningJobWandbIntegration, type FineTuningJobWandbIntegrationObject, type FineTuningJobIntegration, type JobCreateParams, type JobListParams, type JobListEventsParams, type FineTuningJobsPage, type FineTuningJobEventsPage, } from "./jobs.mjs"; +//# sourceMappingURL=index.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/index.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/index.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..54ff55d0781015d7b926f0984fc90db0370609e3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/index.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../../../src/resources/fine-tuning/jobs/index.ts"],"names":[],"mappings":"OAEO,EACL,WAAW,EACX,KAAK,uBAAuB,EAC5B,KAAK,oBAAoB,EACzB,KAAK,4BAA4B,GAClC;OACM,EACL,IAAI,EACJ,KAAK,aAAa,EAClB,KAAK,kBAAkB,EACvB,KAAK,6BAA6B,EAClC,KAAK,mCAAmC,EACxC,KAAK,wBAAwB,EAC7B,KAAK,eAAe,EACpB,KAAK,aAAa,EAClB,KAAK,mBAAmB,EACxB,KAAK,kBAAkB,EACvB,KAAK,uBAAuB,GAC7B"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/index.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..75017b233bf877c53db39e7610779bbce830e765 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/index.d.ts @@ -0,0 +1,3 @@ +export { Checkpoints, type FineTuningJobCheckpoint, type CheckpointListParams, type FineTuningJobCheckpointsPage, } from "./checkpoints.js"; +export { Jobs, type FineTuningJob, type FineTuningJobEvent, type FineTuningJobWandbIntegration, type FineTuningJobWandbIntegrationObject, type FineTuningJobIntegration, type JobCreateParams, type JobListParams, type JobListEventsParams, type FineTuningJobsPage, type FineTuningJobEventsPage, } from "./jobs.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/index.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..9fe5afe604c1952f29688ac0041388069f5354ca --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/resources/fine-tuning/jobs/index.ts"],"names":[],"mappings":"OAEO,EACL,WAAW,EACX,KAAK,uBAAuB,EAC5B,KAAK,oBAAoB,EACzB,KAAK,4BAA4B,GAClC;OACM,EACL,IAAI,EACJ,KAAK,aAAa,EAClB,KAAK,kBAAkB,EACvB,KAAK,6BAA6B,EAClC,KAAK,mCAAmC,EACxC,KAAK,wBAAwB,EAC7B,KAAK,eAAe,EACpB,KAAK,aAAa,EAClB,KAAK,mBAAmB,EACxB,KAAK,kBAAkB,EACvB,KAAK,uBAAuB,GAC7B"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e9083d80a5d2f03f46c95ef58301e3c319a7e432 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/index.js @@ -0,0 +1,9 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Jobs = exports.Checkpoints = void 0; +var checkpoints_1 = require("./checkpoints.js"); +Object.defineProperty(exports, "Checkpoints", { enumerable: true, get: function () { return checkpoints_1.Checkpoints; } }); +var jobs_1 = require("./jobs.js"); +Object.defineProperty(exports, "Jobs", { enumerable: true, get: function () { return jobs_1.Jobs; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/index.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..cb33be5fdd9c929b8e9e688ee17f1e1206d73835 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/resources/fine-tuning/jobs/index.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAEtF,gDAKuB;AAJrB,0GAAA,WAAW,OAAA;AAKb,kCAYgB;AAXd,4FAAA,IAAI,OAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/index.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..07490244e4938c57e9b5487e641a6eff9fda8b09 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/index.mjs @@ -0,0 +1,4 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +export { Checkpoints, } from "./checkpoints.mjs"; +export { Jobs, } from "./jobs.mjs"; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/index.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..d84c46287a5fca5719445f26f994e938535241be --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../../../src/resources/fine-tuning/jobs/index.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAE/E,EACL,WAAW,GAIZ;OACM,EACL,IAAI,GAWL"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/jobs.d.mts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/jobs.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..d2b7d106f5e802893f712b426ad34bcdd38797da --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/jobs.d.mts @@ -0,0 +1,528 @@ +import { APIResource } from "../../../core/resource.mjs"; +import * as Shared from "../../shared.mjs"; +import * as MethodsAPI from "../methods.mjs"; +import * as CheckpointsAPI from "./checkpoints.mjs"; +import { CheckpointListParams, Checkpoints, FineTuningJobCheckpoint, FineTuningJobCheckpointsPage } from "./checkpoints.mjs"; +import { APIPromise } from "../../../core/api-promise.mjs"; +import { CursorPage, type CursorPageParams, PagePromise } from "../../../core/pagination.mjs"; +import { RequestOptions } from "../../../internal/request-options.mjs"; +export declare class Jobs extends APIResource { + checkpoints: CheckpointsAPI.Checkpoints; + /** + * Creates a fine-tuning job which begins the process of creating a new model from + * a given dataset. + * + * Response includes details of the enqueued job including job status and the name + * of the fine-tuned models once complete. + * + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization) + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.create({ + * model: 'gpt-4o-mini', + * training_file: 'file-abc123', + * }); + * ``` + */ + create(body: JobCreateParams, options?: RequestOptions): APIPromise; + /** + * Get info about a fine-tuning job. + * + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization) + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.retrieve( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + retrieve(fineTuningJobID: string, options?: RequestOptions): APIPromise; + /** + * List your organization's fine-tuning jobs + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const fineTuningJob of client.fineTuning.jobs.list()) { + * // ... + * } + * ``` + */ + list(query?: JobListParams | null | undefined, options?: RequestOptions): PagePromise; + /** + * Immediately cancel a fine-tune job. + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.cancel( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + cancel(fineTuningJobID: string, options?: RequestOptions): APIPromise; + /** + * Get status updates for a fine-tuning job. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const fineTuningJobEvent of client.fineTuning.jobs.listEvents( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * )) { + * // ... + * } + * ``` + */ + listEvents(fineTuningJobID: string, query?: JobListEventsParams | null | undefined, options?: RequestOptions): PagePromise; + /** + * Pause a fine-tune job. + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.pause( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + pause(fineTuningJobID: string, options?: RequestOptions): APIPromise; + /** + * Resume a fine-tune job. + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.resume( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + resume(fineTuningJobID: string, options?: RequestOptions): APIPromise; +} +export type FineTuningJobsPage = CursorPage; +export type FineTuningJobEventsPage = CursorPage; +/** + * The `fine_tuning.job` object represents a fine-tuning job that has been created + * through the API. + */ +export interface FineTuningJob { + /** + * The object identifier, which can be referenced in the API endpoints. + */ + id: string; + /** + * The Unix timestamp (in seconds) for when the fine-tuning job was created. + */ + created_at: number; + /** + * For fine-tuning jobs that have `failed`, this will contain more information on + * the cause of the failure. + */ + error: FineTuningJob.Error | null; + /** + * The name of the fine-tuned model that is being created. The value will be null + * if the fine-tuning job is still running. + */ + fine_tuned_model: string | null; + /** + * The Unix timestamp (in seconds) for when the fine-tuning job was finished. The + * value will be null if the fine-tuning job is still running. + */ + finished_at: number | null; + /** + * The hyperparameters used for the fine-tuning job. This value will only be + * returned when running `supervised` jobs. + */ + hyperparameters: FineTuningJob.Hyperparameters; + /** + * The base model that is being fine-tuned. + */ + model: string; + /** + * The object type, which is always "fine_tuning.job". + */ + object: 'fine_tuning.job'; + /** + * The organization that owns the fine-tuning job. + */ + organization_id: string; + /** + * The compiled results file ID(s) for the fine-tuning job. You can retrieve the + * results with the + * [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). + */ + result_files: Array; + /** + * The seed used for the fine-tuning job. + */ + seed: number; + /** + * The current status of the fine-tuning job, which can be either + * `validating_files`, `queued`, `running`, `succeeded`, `failed`, or `cancelled`. + */ + status: 'validating_files' | 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelled'; + /** + * The total number of billable tokens processed by this fine-tuning job. The value + * will be null if the fine-tuning job is still running. + */ + trained_tokens: number | null; + /** + * The file ID used for training. You can retrieve the training data with the + * [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). + */ + training_file: string; + /** + * The file ID used for validation. You can retrieve the validation results with + * the + * [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). + */ + validation_file: string | null; + /** + * The Unix timestamp (in seconds) for when the fine-tuning job is estimated to + * finish. The value will be null if the fine-tuning job is not running. + */ + estimated_finish?: number | null; + /** + * A list of integrations to enable for this fine-tuning job. + */ + integrations?: Array | null; + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; + /** + * The method used for fine-tuning. + */ + method?: FineTuningJob.Method; +} +export declare namespace FineTuningJob { + /** + * For fine-tuning jobs that have `failed`, this will contain more information on + * the cause of the failure. + */ + interface Error { + /** + * A machine-readable error code. + */ + code: string; + /** + * A human-readable error message. + */ + message: string; + /** + * The parameter that was invalid, usually `training_file` or `validation_file`. + * This field will be null if the failure was not parameter-specific. + */ + param: string | null; + } + /** + * The hyperparameters used for the fine-tuning job. This value will only be + * returned when running `supervised` jobs. + */ + interface Hyperparameters { + /** + * Number of examples in each batch. A larger batch size means that model + * parameters are updated less frequently, but with lower variance. + */ + batch_size?: 'auto' | number | null; + /** + * Scaling factor for the learning rate. A smaller learning rate may be useful to + * avoid overfitting. + */ + learning_rate_multiplier?: 'auto' | number; + /** + * The number of epochs to train the model for. An epoch refers to one full cycle + * through the training dataset. + */ + n_epochs?: 'auto' | number; + } + /** + * The method used for fine-tuning. + */ + interface Method { + /** + * The type of method. Is either `supervised`, `dpo`, or `reinforcement`. + */ + type: 'supervised' | 'dpo' | 'reinforcement'; + /** + * Configuration for the DPO fine-tuning method. + */ + dpo?: MethodsAPI.DpoMethod; + /** + * Configuration for the reinforcement fine-tuning method. + */ + reinforcement?: MethodsAPI.ReinforcementMethod; + /** + * Configuration for the supervised fine-tuning method. + */ + supervised?: MethodsAPI.SupervisedMethod; + } +} +/** + * Fine-tuning job event object + */ +export interface FineTuningJobEvent { + /** + * The object identifier. + */ + id: string; + /** + * The Unix timestamp (in seconds) for when the fine-tuning job was created. + */ + created_at: number; + /** + * The log level of the event. + */ + level: 'info' | 'warn' | 'error'; + /** + * The message of the event. + */ + message: string; + /** + * The object type, which is always "fine_tuning.job.event". + */ + object: 'fine_tuning.job.event'; + /** + * The data associated with the event. + */ + data?: unknown; + /** + * The type of event. + */ + type?: 'message' | 'metrics'; +} +/** + * The settings for your integration with Weights and Biases. This payload + * specifies the project that metrics will be sent to. Optionally, you can set an + * explicit display name for your run, add tags to your run, and set a default + * entity (team, username, etc) to be associated with your run. + */ +export interface FineTuningJobWandbIntegration { + /** + * The name of the project that the new run will be created under. + */ + project: string; + /** + * The entity to use for the run. This allows you to set the team or username of + * the WandB user that you would like associated with the run. If not set, the + * default entity for the registered WandB API key is used. + */ + entity?: string | null; + /** + * A display name to set for the run. If not set, we will use the Job ID as the + * name. + */ + name?: string | null; + /** + * A list of tags to be attached to the newly created run. These tags are passed + * through directly to WandB. Some default tags are generated by OpenAI: + * "openai/finetune", "openai/{base-model}", "openai/{ftjob-abcdef}". + */ + tags?: Array; +} +export interface FineTuningJobWandbIntegrationObject { + /** + * The type of the integration being enabled for the fine-tuning job + */ + type: 'wandb'; + /** + * The settings for your integration with Weights and Biases. This payload + * specifies the project that metrics will be sent to. Optionally, you can set an + * explicit display name for your run, add tags to your run, and set a default + * entity (team, username, etc) to be associated with your run. + */ + wandb: FineTuningJobWandbIntegration; +} +export type FineTuningJobIntegration = FineTuningJobWandbIntegrationObject; +export interface JobCreateParams { + /** + * The name of the model to fine-tune. You can select one of the + * [supported models](https://platform.openai.com/docs/guides/fine-tuning#which-models-can-be-fine-tuned). + */ + model: (string & {}) | 'babbage-002' | 'davinci-002' | 'gpt-3.5-turbo' | 'gpt-4o-mini'; + /** + * The ID of an uploaded file that contains training data. + * + * See [upload file](https://platform.openai.com/docs/api-reference/files/create) + * for how to upload a file. + * + * Your dataset must be formatted as a JSONL file. Additionally, you must upload + * your file with the purpose `fine-tune`. + * + * The contents of the file should differ depending on if the model uses the + * [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input), + * [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) + * format, or if the fine-tuning method uses the + * [preference](https://platform.openai.com/docs/api-reference/fine-tuning/preference-input) + * format. + * + * See the + * [fine-tuning guide](https://platform.openai.com/docs/guides/model-optimization) + * for more details. + */ + training_file: string; + /** + * @deprecated The hyperparameters used for the fine-tuning job. This value is now + * deprecated in favor of `method`, and should be passed in under the `method` + * parameter. + */ + hyperparameters?: JobCreateParams.Hyperparameters; + /** + * A list of integrations to enable for your fine-tuning job. + */ + integrations?: Array | null; + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; + /** + * The method used for fine-tuning. + */ + method?: JobCreateParams.Method; + /** + * The seed controls the reproducibility of the job. Passing in the same seed and + * job parameters should produce the same results, but may differ in rare cases. If + * a seed is not specified, one will be generated for you. + */ + seed?: number | null; + /** + * A string of up to 64 characters that will be added to your fine-tuned model + * name. + * + * For example, a `suffix` of "custom-model-name" would produce a model name like + * `ft:gpt-4o-mini:openai:custom-model-name:7p4lURel`. + */ + suffix?: string | null; + /** + * The ID of an uploaded file that contains validation data. + * + * If you provide this file, the data is used to generate validation metrics + * periodically during fine-tuning. These metrics can be viewed in the fine-tuning + * results file. The same data should not be present in both train and validation + * files. + * + * Your dataset must be formatted as a JSONL file. You must upload your file with + * the purpose `fine-tune`. + * + * See the + * [fine-tuning guide](https://platform.openai.com/docs/guides/model-optimization) + * for more details. + */ + validation_file?: string | null; +} +export declare namespace JobCreateParams { + /** + * @deprecated The hyperparameters used for the fine-tuning job. This value is now + * deprecated in favor of `method`, and should be passed in under the `method` + * parameter. + */ + interface Hyperparameters { + /** + * Number of examples in each batch. A larger batch size means that model + * parameters are updated less frequently, but with lower variance. + */ + batch_size?: 'auto' | number; + /** + * Scaling factor for the learning rate. A smaller learning rate may be useful to + * avoid overfitting. + */ + learning_rate_multiplier?: 'auto' | number; + /** + * The number of epochs to train the model for. An epoch refers to one full cycle + * through the training dataset. + */ + n_epochs?: 'auto' | number; + } + interface Integration { + /** + * The type of integration to enable. Currently, only "wandb" (Weights and Biases) + * is supported. + */ + type: 'wandb'; + /** + * The settings for your integration with Weights and Biases. This payload + * specifies the project that metrics will be sent to. Optionally, you can set an + * explicit display name for your run, add tags to your run, and set a default + * entity (team, username, etc) to be associated with your run. + */ + wandb: Integration.Wandb; + } + namespace Integration { + /** + * The settings for your integration with Weights and Biases. This payload + * specifies the project that metrics will be sent to. Optionally, you can set an + * explicit display name for your run, add tags to your run, and set a default + * entity (team, username, etc) to be associated with your run. + */ + interface Wandb { + /** + * The name of the project that the new run will be created under. + */ + project: string; + /** + * The entity to use for the run. This allows you to set the team or username of + * the WandB user that you would like associated with the run. If not set, the + * default entity for the registered WandB API key is used. + */ + entity?: string | null; + /** + * A display name to set for the run. If not set, we will use the Job ID as the + * name. + */ + name?: string | null; + /** + * A list of tags to be attached to the newly created run. These tags are passed + * through directly to WandB. Some default tags are generated by OpenAI: + * "openai/finetune", "openai/{base-model}", "openai/{ftjob-abcdef}". + */ + tags?: Array; + } + } + /** + * The method used for fine-tuning. + */ + interface Method { + /** + * The type of method. Is either `supervised`, `dpo`, or `reinforcement`. + */ + type: 'supervised' | 'dpo' | 'reinforcement'; + /** + * Configuration for the DPO fine-tuning method. + */ + dpo?: MethodsAPI.DpoMethod; + /** + * Configuration for the reinforcement fine-tuning method. + */ + reinforcement?: MethodsAPI.ReinforcementMethod; + /** + * Configuration for the supervised fine-tuning method. + */ + supervised?: MethodsAPI.SupervisedMethod; + } +} +export interface JobListParams extends CursorPageParams { + /** + * Optional metadata filter. To filter, use the syntax `metadata[k]=v`. + * Alternatively, set `metadata=null` to indicate no metadata. + */ + metadata?: { + [key: string]: string; + } | null; +} +export interface JobListEventsParams extends CursorPageParams { +} +export declare namespace Jobs { + export { type FineTuningJob as FineTuningJob, type FineTuningJobEvent as FineTuningJobEvent, type FineTuningJobWandbIntegration as FineTuningJobWandbIntegration, type FineTuningJobWandbIntegrationObject as FineTuningJobWandbIntegrationObject, type FineTuningJobIntegration as FineTuningJobIntegration, type FineTuningJobsPage as FineTuningJobsPage, type FineTuningJobEventsPage as FineTuningJobEventsPage, type JobCreateParams as JobCreateParams, type JobListParams as JobListParams, type JobListEventsParams as JobListEventsParams, }; + export { Checkpoints as Checkpoints, type FineTuningJobCheckpoint as FineTuningJobCheckpoint, type FineTuningJobCheckpointsPage as FineTuningJobCheckpointsPage, type CheckpointListParams as CheckpointListParams, }; +} +//# sourceMappingURL=jobs.d.mts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/jobs.d.mts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/jobs.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..ca8b3934c5e1360b4df2f66cb91718d3344bba51 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/jobs.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"jobs.d.mts","sourceRoot":"","sources":["../../../src/resources/fine-tuning/jobs/jobs.ts"],"names":[],"mappings":"OAEO,EAAE,WAAW,EAAE;OACf,KAAK,MAAM;OACX,KAAK,UAAU;OACf,KAAK,cAAc;OACnB,EACL,oBAAoB,EACpB,WAAW,EACX,uBAAuB,EACvB,4BAA4B,EAC7B;OACM,EAAE,UAAU,EAAE;OACd,EAAE,UAAU,EAAE,KAAK,gBAAgB,EAAE,WAAW,EAAE;OAClD,EAAE,cAAc,EAAE;AAGzB,qBAAa,IAAK,SAAQ,WAAW;IACnC,WAAW,EAAE,cAAc,CAAC,WA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F,OAAO,EACL,WAAW,IAAI,WAAW,EAC1B,KAAK,uBAAuB,IAAI,uBAAuB,EACvD,KAAK,4BAA4B,IAAI,4BAA4B,EACjE,KAAK,oBAAoB,IAAI,oBAAoB,GAClD,CAAC;CACH"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/jobs.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/jobs.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..454b7316a53b0d38f3560c9e7755b753fe343e07 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/jobs.d.ts @@ -0,0 +1,528 @@ +import { APIResource } from "../../../core/resource.js"; +import * as Shared from "../../shared.js"; +import * as MethodsAPI from "../methods.js"; +import * as CheckpointsAPI from "./checkpoints.js"; +import { CheckpointListParams, Checkpoints, FineTuningJobCheckpoint, FineTuningJobCheckpointsPage } from "./checkpoints.js"; +import { APIPromise } from "../../../core/api-promise.js"; +import { CursorPage, type CursorPageParams, PagePromise } from "../../../core/pagination.js"; +import { RequestOptions } from "../../../internal/request-options.js"; +export declare class Jobs extends APIResource { + checkpoints: CheckpointsAPI.Checkpoints; + /** + * Creates a fine-tuning job which begins the process of creating a new model from + * a given dataset. + * + * Response includes details of the enqueued job including job status and the name + * of the fine-tuned models once complete. + * + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization) + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.create({ + * model: 'gpt-4o-mini', + * training_file: 'file-abc123', + * }); + * ``` + */ + create(body: JobCreateParams, options?: RequestOptions): APIPromise; + /** + * Get info about a fine-tuning job. + * + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization) + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.retrieve( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + retrieve(fineTuningJobID: string, options?: RequestOptions): APIPromise; + /** + * List your organization's fine-tuning jobs + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const fineTuningJob of client.fineTuning.jobs.list()) { + * // ... + * } + * ``` + */ + list(query?: JobListParams | null | undefined, options?: RequestOptions): PagePromise; + /** + * Immediately cancel a fine-tune job. + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.cancel( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + cancel(fineTuningJobID: string, options?: RequestOptions): APIPromise; + /** + * Get status updates for a fine-tuning job. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const fineTuningJobEvent of client.fineTuning.jobs.listEvents( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * )) { + * // ... + * } + * ``` + */ + listEvents(fineTuningJobID: string, query?: JobListEventsParams | null | undefined, options?: RequestOptions): PagePromise; + /** + * Pause a fine-tune job. + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.pause( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + pause(fineTuningJobID: string, options?: RequestOptions): APIPromise; + /** + * Resume a fine-tune job. + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.resume( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + resume(fineTuningJobID: string, options?: RequestOptions): APIPromise; +} +export type FineTuningJobsPage = CursorPage; +export type FineTuningJobEventsPage = CursorPage; +/** + * The `fine_tuning.job` object represents a fine-tuning job that has been created + * through the API. + */ +export interface FineTuningJob { + /** + * The object identifier, which can be referenced in the API endpoints. + */ + id: string; + /** + * The Unix timestamp (in seconds) for when the fine-tuning job was created. + */ + created_at: number; + /** + * For fine-tuning jobs that have `failed`, this will contain more information on + * the cause of the failure. + */ + error: FineTuningJob.Error | null; + /** + * The name of the fine-tuned model that is being created. The value will be null + * if the fine-tuning job is still running. + */ + fine_tuned_model: string | null; + /** + * The Unix timestamp (in seconds) for when the fine-tuning job was finished. The + * value will be null if the fine-tuning job is still running. + */ + finished_at: number | null; + /** + * The hyperparameters used for the fine-tuning job. This value will only be + * returned when running `supervised` jobs. + */ + hyperparameters: FineTuningJob.Hyperparameters; + /** + * The base model that is being fine-tuned. + */ + model: string; + /** + * The object type, which is always "fine_tuning.job". + */ + object: 'fine_tuning.job'; + /** + * The organization that owns the fine-tuning job. + */ + organization_id: string; + /** + * The compiled results file ID(s) for the fine-tuning job. You can retrieve the + * results with the + * [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). + */ + result_files: Array; + /** + * The seed used for the fine-tuning job. + */ + seed: number; + /** + * The current status of the fine-tuning job, which can be either + * `validating_files`, `queued`, `running`, `succeeded`, `failed`, or `cancelled`. + */ + status: 'validating_files' | 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelled'; + /** + * The total number of billable tokens processed by this fine-tuning job. The value + * will be null if the fine-tuning job is still running. + */ + trained_tokens: number | null; + /** + * The file ID used for training. You can retrieve the training data with the + * [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). + */ + training_file: string; + /** + * The file ID used for validation. You can retrieve the validation results with + * the + * [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). + */ + validation_file: string | null; + /** + * The Unix timestamp (in seconds) for when the fine-tuning job is estimated to + * finish. The value will be null if the fine-tuning job is not running. + */ + estimated_finish?: number | null; + /** + * A list of integrations to enable for this fine-tuning job. + */ + integrations?: Array | null; + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; + /** + * The method used for fine-tuning. + */ + method?: FineTuningJob.Method; +} +export declare namespace FineTuningJob { + /** + * For fine-tuning jobs that have `failed`, this will contain more information on + * the cause of the failure. + */ + interface Error { + /** + * A machine-readable error code. + */ + code: string; + /** + * A human-readable error message. + */ + message: string; + /** + * The parameter that was invalid, usually `training_file` or `validation_file`. + * This field will be null if the failure was not parameter-specific. + */ + param: string | null; + } + /** + * The hyperparameters used for the fine-tuning job. This value will only be + * returned when running `supervised` jobs. + */ + interface Hyperparameters { + /** + * Number of examples in each batch. A larger batch size means that model + * parameters are updated less frequently, but with lower variance. + */ + batch_size?: 'auto' | number | null; + /** + * Scaling factor for the learning rate. A smaller learning rate may be useful to + * avoid overfitting. + */ + learning_rate_multiplier?: 'auto' | number; + /** + * The number of epochs to train the model for. An epoch refers to one full cycle + * through the training dataset. + */ + n_epochs?: 'auto' | number; + } + /** + * The method used for fine-tuning. + */ + interface Method { + /** + * The type of method. Is either `supervised`, `dpo`, or `reinforcement`. + */ + type: 'supervised' | 'dpo' | 'reinforcement'; + /** + * Configuration for the DPO fine-tuning method. + */ + dpo?: MethodsAPI.DpoMethod; + /** + * Configuration for the reinforcement fine-tuning method. + */ + reinforcement?: MethodsAPI.ReinforcementMethod; + /** + * Configuration for the supervised fine-tuning method. + */ + supervised?: MethodsAPI.SupervisedMethod; + } +} +/** + * Fine-tuning job event object + */ +export interface FineTuningJobEvent { + /** + * The object identifier. + */ + id: string; + /** + * The Unix timestamp (in seconds) for when the fine-tuning job was created. + */ + created_at: number; + /** + * The log level of the event. + */ + level: 'info' | 'warn' | 'error'; + /** + * The message of the event. + */ + message: string; + /** + * The object type, which is always "fine_tuning.job.event". + */ + object: 'fine_tuning.job.event'; + /** + * The data associated with the event. + */ + data?: unknown; + /** + * The type of event. + */ + type?: 'message' | 'metrics'; +} +/** + * The settings for your integration with Weights and Biases. This payload + * specifies the project that metrics will be sent to. Optionally, you can set an + * explicit display name for your run, add tags to your run, and set a default + * entity (team, username, etc) to be associated with your run. + */ +export interface FineTuningJobWandbIntegration { + /** + * The name of the project that the new run will be created under. + */ + project: string; + /** + * The entity to use for the run. This allows you to set the team or username of + * the WandB user that you would like associated with the run. If not set, the + * default entity for the registered WandB API key is used. + */ + entity?: string | null; + /** + * A display name to set for the run. If not set, we will use the Job ID as the + * name. + */ + name?: string | null; + /** + * A list of tags to be attached to the newly created run. These tags are passed + * through directly to WandB. Some default tags are generated by OpenAI: + * "openai/finetune", "openai/{base-model}", "openai/{ftjob-abcdef}". + */ + tags?: Array; +} +export interface FineTuningJobWandbIntegrationObject { + /** + * The type of the integration being enabled for the fine-tuning job + */ + type: 'wandb'; + /** + * The settings for your integration with Weights and Biases. This payload + * specifies the project that metrics will be sent to. Optionally, you can set an + * explicit display name for your run, add tags to your run, and set a default + * entity (team, username, etc) to be associated with your run. + */ + wandb: FineTuningJobWandbIntegration; +} +export type FineTuningJobIntegration = FineTuningJobWandbIntegrationObject; +export interface JobCreateParams { + /** + * The name of the model to fine-tune. You can select one of the + * [supported models](https://platform.openai.com/docs/guides/fine-tuning#which-models-can-be-fine-tuned). + */ + model: (string & {}) | 'babbage-002' | 'davinci-002' | 'gpt-3.5-turbo' | 'gpt-4o-mini'; + /** + * The ID of an uploaded file that contains training data. + * + * See [upload file](https://platform.openai.com/docs/api-reference/files/create) + * for how to upload a file. + * + * Your dataset must be formatted as a JSONL file. Additionally, you must upload + * your file with the purpose `fine-tune`. + * + * The contents of the file should differ depending on if the model uses the + * [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input), + * [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) + * format, or if the fine-tuning method uses the + * [preference](https://platform.openai.com/docs/api-reference/fine-tuning/preference-input) + * format. + * + * See the + * [fine-tuning guide](https://platform.openai.com/docs/guides/model-optimization) + * for more details. + */ + training_file: string; + /** + * @deprecated The hyperparameters used for the fine-tuning job. This value is now + * deprecated in favor of `method`, and should be passed in under the `method` + * parameter. + */ + hyperparameters?: JobCreateParams.Hyperparameters; + /** + * A list of integrations to enable for your fine-tuning job. + */ + integrations?: Array | null; + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; + /** + * The method used for fine-tuning. + */ + method?: JobCreateParams.Method; + /** + * The seed controls the reproducibility of the job. Passing in the same seed and + * job parameters should produce the same results, but may differ in rare cases. If + * a seed is not specified, one will be generated for you. + */ + seed?: number | null; + /** + * A string of up to 64 characters that will be added to your fine-tuned model + * name. + * + * For example, a `suffix` of "custom-model-name" would produce a model name like + * `ft:gpt-4o-mini:openai:custom-model-name:7p4lURel`. + */ + suffix?: string | null; + /** + * The ID of an uploaded file that contains validation data. + * + * If you provide this file, the data is used to generate validation metrics + * periodically during fine-tuning. These metrics can be viewed in the fine-tuning + * results file. The same data should not be present in both train and validation + * files. + * + * Your dataset must be formatted as a JSONL file. You must upload your file with + * the purpose `fine-tune`. + * + * See the + * [fine-tuning guide](https://platform.openai.com/docs/guides/model-optimization) + * for more details. + */ + validation_file?: string | null; +} +export declare namespace JobCreateParams { + /** + * @deprecated The hyperparameters used for the fine-tuning job. This value is now + * deprecated in favor of `method`, and should be passed in under the `method` + * parameter. + */ + interface Hyperparameters { + /** + * Number of examples in each batch. A larger batch size means that model + * parameters are updated less frequently, but with lower variance. + */ + batch_size?: 'auto' | number; + /** + * Scaling factor for the learning rate. A smaller learning rate may be useful to + * avoid overfitting. + */ + learning_rate_multiplier?: 'auto' | number; + /** + * The number of epochs to train the model for. An epoch refers to one full cycle + * through the training dataset. + */ + n_epochs?: 'auto' | number; + } + interface Integration { + /** + * The type of integration to enable. Currently, only "wandb" (Weights and Biases) + * is supported. + */ + type: 'wandb'; + /** + * The settings for your integration with Weights and Biases. This payload + * specifies the project that metrics will be sent to. Optionally, you can set an + * explicit display name for your run, add tags to your run, and set a default + * entity (team, username, etc) to be associated with your run. + */ + wandb: Integration.Wandb; + } + namespace Integration { + /** + * The settings for your integration with Weights and Biases. This payload + * specifies the project that metrics will be sent to. Optionally, you can set an + * explicit display name for your run, add tags to your run, and set a default + * entity (team, username, etc) to be associated with your run. + */ + interface Wandb { + /** + * The name of the project that the new run will be created under. + */ + project: string; + /** + * The entity to use for the run. This allows you to set the team or username of + * the WandB user that you would like associated with the run. If not set, the + * default entity for the registered WandB API key is used. + */ + entity?: string | null; + /** + * A display name to set for the run. If not set, we will use the Job ID as the + * name. + */ + name?: string | null; + /** + * A list of tags to be attached to the newly created run. These tags are passed + * through directly to WandB. Some default tags are generated by OpenAI: + * "openai/finetune", "openai/{base-model}", "openai/{ftjob-abcdef}". + */ + tags?: Array; + } + } + /** + * The method used for fine-tuning. + */ + interface Method { + /** + * The type of method. Is either `supervised`, `dpo`, or `reinforcement`. + */ + type: 'supervised' | 'dpo' | 'reinforcement'; + /** + * Configuration for the DPO fine-tuning method. + */ + dpo?: MethodsAPI.DpoMethod; + /** + * Configuration for the reinforcement fine-tuning method. + */ + reinforcement?: MethodsAPI.ReinforcementMethod; + /** + * Configuration for the supervised fine-tuning method. + */ + supervised?: MethodsAPI.SupervisedMethod; + } +} +export interface JobListParams extends CursorPageParams { + /** + * Optional metadata filter. To filter, use the syntax `metadata[k]=v`. + * Alternatively, set `metadata=null` to indicate no metadata. + */ + metadata?: { + [key: string]: string; + } | null; +} +export interface JobListEventsParams extends CursorPageParams { +} +export declare namespace Jobs { + export { type FineTuningJob as FineTuningJob, type FineTuningJobEvent as FineTuningJobEvent, type FineTuningJobWandbIntegration as FineTuningJobWandbIntegration, type FineTuningJobWandbIntegrationObject as FineTuningJobWandbIntegrationObject, type FineTuningJobIntegration as FineTuningJobIntegration, type FineTuningJobsPage as FineTuningJobsPage, type FineTuningJobEventsPage as FineTuningJobEventsPage, type JobCreateParams as JobCreateParams, type JobListParams as JobListParams, type JobListEventsParams as JobListEventsParams, }; + export { Checkpoints as Checkpoints, type FineTuningJobCheckpoint as FineTuningJobCheckpoint, type FineTuningJobCheckpointsPage as FineTuningJobCheckpointsPage, type CheckpointListParams as CheckpointListParams, }; +} +//# sourceMappingURL=jobs.d.ts.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/jobs.d.ts.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/jobs.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..511e837d97ebc16a88f0a38f498ab07cf5abc1c8 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/jobs.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"jobs.d.ts","sourceRoot":"","sources":["../../../src/resources/fine-tuning/jobs/jobs.ts"],"names":[],"mappings":"OAEO,EAAE,WAAW,EAAE;OACf,KAAK,MAAM;OACX,KAAK,UAAU;OACf,KAAK,cAAc;OACnB,EACL,oBAAoB,EACpB,WAAW,EACX,uBAAuB,EACvB,4BAA4B,EAC7B;OACM,EAAE,UAAU,EAAE;OACd,EAAE,UAAU,EAAE,KAAK,gBAAgB,EAAE,WAAW,EAAE;OAClD,EAAE,cAAc,EAAE;AAGzB,qBAAa,IAAK,SAAQ,WAAW;IACnC,WAAW,EAAE,cAAc,CAAC,WAAW,CAAgD;IAEvF;;;;;;;;;;;;;;;;OAgBG;IACH,MAAM,CAAC,IAAI,EAAE,eAAe,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,UAAU,CAAC,aAAa,CAAC;IAIlF;;;;;;;;;;;OAWG;IACH,QAAQ,CAAC,eAAe,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,UAAU,CAAC,aAAa,CAAC;IAItF;;;;;;;;;;OAUG;IACH,IAAI,CACF,KAAK,GAAE,aAAa,GAAG,IAAI,GAAG,SAAc,EAC5C,OAAO,CAAC,EAAE,cAAc,GACvB,WAAW,CAAC,kBAAkB,EAAE,aAAa,CAAC;IAIjD;;;;;;;;;OASG;IACH,MAAM,CAAC,eAAe,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,UAAU,CAAC,aAAa,CAAC;IAIpF;;;;;;;;;;;;OAYG;IACH,UAAU,CACR,eAAe,EAA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U,CAAC,gBAAgB,CAAC;KAC1C;CACF;AAED,MAAM,WAAW,aAAc,SAAQ,gBAAgB;IACrD;;;OAGG;IACH,QAAQ,CAAC,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC;CAC7C;AAED,MAAM,WAAW,mBAAoB,SAAQ,gBAAgB;CAAG;AAIhE,MAAM,CAAC,OAAO,WAAW,IAAI,CAAC;IAC5B,OAAO,EACL,KAAK,aAAa,IAAI,aAAa,EACnC,KAAK,kBAAkB,IAAI,kBAAkB,EAC7C,KAAK,6BAA6B,IAAI,6BAA6B,EACnE,KAAK,mCAAmC,IAAI,mCAAmC,EAC/E,KAAK,wBAAwB,IAAI,wBAAwB,EACzD,KAAK,kBAAkB,IAAI,kBAAkB,EAC7C,KAAK,uBAAuB,IAAI,uBAAuB,EACvD,KAAK,eAAe,IAAI,eAAe,EACvC,KAAK,aAAa,IAAI,aAAa,EACnC,KAAK,mBAAmB,IAAI,mBAAmB,GAChD,CAAC;IAEF,OAAO,EACL,WAAW,IAAI,WAAW,EAC1B,KAAK,uBAAuB,IAAI,uBAAuB,EACvD,KAAK,4BAA4B,IAAI,4BAA4B,EACjE,KAAK,oBAAoB,IAAI,oBAAoB,GAClD,CAAC;CACH"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/jobs.js b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/jobs.js new file mode 100644 index 0000000000000000000000000000000000000000..e5d6808d4377c0adecdb4479c45ebfb38232ad74 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/jobs.js @@ -0,0 +1,123 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Jobs = void 0; +const tslib_1 = require("../../../internal/tslib.js"); +const resource_1 = require("../../../core/resource.js"); +const CheckpointsAPI = tslib_1.__importStar(require("./checkpoints.js")); +const checkpoints_1 = require("./checkpoints.js"); +const pagination_1 = require("../../../core/pagination.js"); +const path_1 = require("../../../internal/utils/path.js"); +class Jobs extends resource_1.APIResource { + constructor() { + super(...arguments); + this.checkpoints = new CheckpointsAPI.Checkpoints(this._client); + } + /** + * Creates a fine-tuning job which begins the process of creating a new model from + * a given dataset. + * + * Response includes details of the enqueued job including job status and the name + * of the fine-tuned models once complete. + * + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization) + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.create({ + * model: 'gpt-4o-mini', + * training_file: 'file-abc123', + * }); + * ``` + */ + create(body, options) { + return this._client.post('/fine_tuning/jobs', { body, ...options }); + } + /** + * Get info about a fine-tuning job. + * + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization) + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.retrieve( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + retrieve(fineTuningJobID, options) { + return this._client.get((0, path_1.path) `/fine_tuning/jobs/${fineTuningJobID}`, options); + } + /** + * List your organization's fine-tuning jobs + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const fineTuningJob of client.fineTuning.jobs.list()) { + * // ... + * } + * ``` + */ + list(query = {}, options) { + return this._client.getAPIList('/fine_tuning/jobs', (pagination_1.CursorPage), { query, ...options }); + } + /** + * Immediately cancel a fine-tune job. + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.cancel( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + cancel(fineTuningJobID, options) { + return this._client.post((0, path_1.path) `/fine_tuning/jobs/${fineTuningJobID}/cancel`, options); + } + /** + * Get status updates for a fine-tuning job. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const fineTuningJobEvent of client.fineTuning.jobs.listEvents( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * )) { + * // ... + * } + * ``` + */ + listEvents(fineTuningJobID, query = {}, options) { + return this._client.getAPIList((0, path_1.path) `/fine_tuning/jobs/${fineTuningJobID}/events`, (pagination_1.CursorPage), { query, ...options }); + } + /** + * Pause a fine-tune job. + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.pause( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + pause(fineTuningJobID, options) { + return this._client.post((0, path_1.path) `/fine_tuning/jobs/${fineTuningJobID}/pause`, options); + } + /** + * Resume a fine-tune job. + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.resume( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + resume(fineTuningJobID, options) { + return this._client.post((0, path_1.path) `/fine_tuning/jobs/${fineTuningJobID}/resume`, options); + } +} +exports.Jobs = Jobs; +Jobs.Checkpoints = checkpoints_1.Checkpoints; +//# sourceMappingURL=jobs.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/jobs.js.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/jobs.js.map new file mode 100644 index 0000000000000000000000000000000000000000..0f8c229f77f6e34e85ca95ad697f06664004089c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/jobs.js.map @@ -0,0 +1 @@ +{"version":3,"file":"jobs.js","sourceRoot":"","sources":["../../../src/resources/fine-tuning/jobs/jobs.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;;AAEtF,wDAAqD;AAGrD,yEAAgD;AAChD,kDAKuB;AAEvB,4DAA0F;AAE1F,0DAAoD;AAEpD,MAAa,IAAK,SAAQ,sBAAW;IAArC;;QACE,gBAAW,GAA+B,IAAI,cAAc,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IA2HzF,CAAC;IA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H,MAAM,CAAC,eAAuB,EAAE,OAAwB;QACtD,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAA,WAAI,EAAA,qBAAqB,eAAe,SAAS,EAAE,OAAO,CAAC,CAAC;IACvF,CAAC;CACF;AA5HD,oBA4HC;AA0eD,IAAI,CAAC,WAAW,GAAG,yBAAW,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/jobs.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/jobs.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6d7581dfcbdf805468911ec1ed965febc366d7b2 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/jobs.mjs @@ -0,0 +1,118 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import { APIResource } from "../../../core/resource.mjs"; +import * as CheckpointsAPI from "./checkpoints.mjs"; +import { Checkpoints, } from "./checkpoints.mjs"; +import { CursorPage } from "../../../core/pagination.mjs"; +import { path } from "../../../internal/utils/path.mjs"; +export class Jobs extends APIResource { + constructor() { + super(...arguments); + this.checkpoints = new CheckpointsAPI.Checkpoints(this._client); + } + /** + * Creates a fine-tuning job which begins the process of creating a new model from + * a given dataset. + * + * Response includes details of the enqueued job including job status and the name + * of the fine-tuned models once complete. + * + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization) + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.create({ + * model: 'gpt-4o-mini', + * training_file: 'file-abc123', + * }); + * ``` + */ + create(body, options) { + return this._client.post('/fine_tuning/jobs', { body, ...options }); + } + /** + * Get info about a fine-tuning job. + * + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization) + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.retrieve( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + retrieve(fineTuningJobID, options) { + return this._client.get(path `/fine_tuning/jobs/${fineTuningJobID}`, options); + } + /** + * List your organization's fine-tuning jobs + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const fineTuningJob of client.fineTuning.jobs.list()) { + * // ... + * } + * ``` + */ + list(query = {}, options) { + return this._client.getAPIList('/fine_tuning/jobs', (CursorPage), { query, ...options }); + } + /** + * Immediately cancel a fine-tune job. + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.cancel( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + cancel(fineTuningJobID, options) { + return this._client.post(path `/fine_tuning/jobs/${fineTuningJobID}/cancel`, options); + } + /** + * Get status updates for a fine-tuning job. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const fineTuningJobEvent of client.fineTuning.jobs.listEvents( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * )) { + * // ... + * } + * ``` + */ + listEvents(fineTuningJobID, query = {}, options) { + return this._client.getAPIList(path `/fine_tuning/jobs/${fineTuningJobID}/events`, (CursorPage), { query, ...options }); + } + /** + * Pause a fine-tune job. + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.pause( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + pause(fineTuningJobID, options) { + return this._client.post(path `/fine_tuning/jobs/${fineTuningJobID}/pause`, options); + } + /** + * Resume a fine-tune job. + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.resume( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + resume(fineTuningJobID, options) { + return this._client.post(path `/fine_tuning/jobs/${fineTuningJobID}/resume`, options); + } +} +Jobs.Checkpoints = Checkpoints; +//# sourceMappingURL=jobs.mjs.map \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/jobs.mjs.map b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/jobs.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..3f2d2c8ed9a644e5e0f1d336dde9cc9ad0496a4c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/resources/fine-tuning/jobs/jobs.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"jobs.mjs","sourceRoot":"","sources":["../../../src/resources/fine-tuning/jobs/jobs.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAE/E,EAAE,WAAW,EAAE;OAGf,KAAK,cAAc;OACnB,EAEL,WAAW,GAGZ;OAEM,EAAE,UAAU,EAAsC;OAElD,EAAE,IAAI,EAAE;AAEf,MAAM,OAAO,IAAK,SAAQ,WAAW;IAArC;;QACE,gBAAW,GAA+B,IAAI,cAAc,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IA2HzF,CAAC;IAzHC;;;;;;;;;;;;;;;;OAgBG;IACH,MAAM,CAAC,IAAqB,EAAE,OAAwB;QACpD,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,mBAAmB,EAAE,EAAE,IAAI,EAAE,GAAG,OAAO,EAAE,CAAC,CAAC;IACtE,CAAC;IAED;;;;;;;;;;;OAWG;IACH,QAAQ,CAAC,eAAuB,EAAE,OAAwB;QACxD,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAA,qBAAqB,eAAe,EAAE,EAAE,OAAO,CAAC,CAAC;IAC/E,CAAC;IAED;;;;;;;;;;OAUG;IACH,IAAI,CACF,QAA0C,EAAE,EAC5C,OAAwB;QAExB,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,mBAAmB,EAAE,CAAA,UAAyB,CAAA,EAAE,EAAE,KAAK,EAAE,GAAG,OAAO,EAAE,CAAC,CAAC;IACxG,CAAC;IAED;;;;;;;;;OASG;IACH,MAAM,CAAC,eAAuB,EAAE,OAAwB;QACtD,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAA,qBAAqB,eAAe,SAAS,EAAE,OAAO,CAAC,CAAC;IACvF,CAAC;IAED;;;;;;;;;;;;OAYG;IACH,UAAU,CACR,eAAuB,EACvB,QAAgD,EAAE,EAClD,OAAwB;QAExB,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,CAC5B,IAAI,CAAA,qBAAqB,eAAe,SAAS,EACjD,CAAA,UAA8B,CAAA,EAC9B,EAAE,KAAK,EAAE,GAAG,OAAO,EAAE,CACtB,CAAC;IACJ,CAAC;IAED;;;;;;;;;OASG;IACH,KAAK,CAAC,eAAuB,EAAE,OAAwB;QACrD,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAA,qBAAqB,eAAe,QAAQ,EAAE,OAAO,CAAC,CAAC;IACtF,CAAC;IAED;;;;;;;;;OASG;IACH,MAAM,CAAC,eAAuB,EAAE,OAAwB;QACtD,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAA,qBAAqB,eAAe,SAAS,EAAE,OAAO,CAAC,CAAC;IACvF,CAAC;CACF;AA0eD,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/partial-json-parser/README.md b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/partial-json-parser/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d4e1c85d68ef842ce11f4db4f67569d44b302a0c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/partial-json-parser/README.md @@ -0,0 +1,3 @@ +# Partial JSON Parser + +Vendored from https://www.npmjs.com/package/partial-json with some modifications diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/partial-json-parser/parser.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/partial-json-parser/parser.ts new file mode 100644 index 0000000000000000000000000000000000000000..5ee62b76bc3dd28c68189d1c647295ee216d3634 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/partial-json-parser/parser.ts @@ -0,0 +1,247 @@ +const STR = 0b000000001; +const NUM = 0b000000010; +const ARR = 0b000000100; +const OBJ = 0b000001000; +const NULL = 0b000010000; +const BOOL = 0b000100000; +const NAN = 0b001000000; +const INFINITY = 0b010000000; +const MINUS_INFINITY = 0b100000000; + +const INF = INFINITY | MINUS_INFINITY; +const SPECIAL = NULL | BOOL | INF | NAN; +const ATOM = STR | NUM | SPECIAL; +const COLLECTION = ARR | OBJ; +const ALL = ATOM | COLLECTION; + +const Allow = { + STR, + NUM, + ARR, + OBJ, + NULL, + BOOL, + NAN, + INFINITY, + MINUS_INFINITY, + INF, + SPECIAL, + ATOM, + COLLECTION, + ALL, +}; + +// The JSON string segment was unable to be parsed completely +class PartialJSON extends Error {} + +class MalformedJSON extends Error {} + +/** + * Parse incomplete JSON + * @param {string} jsonString Partial JSON to be parsed + * @param {number} allowPartial Specify what types are allowed to be partial, see {@link Allow} for details + * @returns The parsed JSON + * @throws {PartialJSON} If the JSON is incomplete (related to the `allow` parameter) + * @throws {MalformedJSON} If the JSON is malformed + */ +function parseJSON(jsonString: string, allowPartial: number = Allow.ALL): any { + if (typeof jsonString !== 'string') { + throw new TypeError(`expecting str, got ${typeof jsonString}`); + } + if (!jsonString.trim()) { + throw new Error(`${jsonString} is empty`); + } + return _parseJSON(jsonString.trim(), allowPartial); +} + +const _parseJSON = (jsonString: string, allow: number) => { + const length = jsonString.length; + let index = 0; + + const markPartialJSON = (msg: string) => { + throw new PartialJSON(`${msg} at position ${index}`); + }; + + const throwMalformedError = (msg: string) => { + throw new MalformedJSON(`${msg} at position ${index}`); + }; + + const parseAny: () => any = () => { + skipBlank(); + if (index >= length) markPartialJSON('Unexpected end of input'); + if (jsonString[index] === '"') return parseStr(); + if (jsonString[index] === '{') return parseObj(); + if (jsonString[index] === '[') return parseArr(); + if ( + jsonString.substring(index, index + 4) === 'null' || + (Allow.NULL & allow && length - index < 4 && 'null'.startsWith(jsonString.substring(index))) + ) { + index += 4; + return null; + } + if ( + jsonString.substring(index, index + 4) === 'true' || + (Allow.BOOL & allow && length - index < 4 && 'true'.startsWith(jsonString.substring(index))) + ) { + index += 4; + return true; + } + if ( + jsonString.substring(index, index + 5) === 'false' || + (Allow.BOOL & allow && length - index < 5 && 'false'.startsWith(jsonString.substring(index))) + ) { + index += 5; + return false; + } + if ( + jsonString.substring(index, index + 8) === 'Infinity' || + (Allow.INFINITY & allow && length - index < 8 && 'Infinity'.startsWith(jsonString.substring(index))) + ) { + index += 8; + return Infinity; + } + if ( + jsonString.substring(index, index + 9) === '-Infinity' || + (Allow.MINUS_INFINITY & allow && + 1 < length - index && + length - index < 9 && + '-Infinity'.startsWith(jsonString.substring(index))) + ) { + index += 9; + return -Infinity; + } + if ( + jsonString.substring(index, index + 3) === 'NaN' || + (Allow.NAN & allow && length - index < 3 && 'NaN'.startsWith(jsonString.substring(index))) + ) { + index += 3; + return NaN; + } + return parseNum(); + }; + + const parseStr: () => string = () => { + const start = index; + let escape = false; + index++; // skip initial quote + while (index < length && (jsonString[index] !== '"' || (escape && jsonString[index - 1] === '\\'))) { + escape = jsonString[index] === '\\' ? !escape : false; + index++; + } + if (jsonString.charAt(index) == '"') { + try { + return JSON.parse(jsonString.substring(start, ++index - Number(escape))); + } catch (e) { + throwMalformedError(String(e)); + } + } else if (Allow.STR & allow) { + try { + return JSON.parse(jsonString.substring(start, index - Number(escape)) + '"'); + } catch (e) { + // SyntaxError: Invalid escape sequence + return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf('\\')) + '"'); + } + } + markPartialJSON('Unterminated string literal'); + }; + + const parseObj = () => { + index++; // skip initial brace + skipBlank(); + const obj: Record = {}; + try { + while (jsonString[index] !== '}') { + skipBlank(); + if (index >= length && Allow.OBJ & allow) return obj; + const key = parseStr(); + skipBlank(); + index++; // skip colon + try { + const value = parseAny(); + Object.defineProperty(obj, key, { value, writable: true, enumerable: true, configurable: true }); + } catch (e) { + if (Allow.OBJ & allow) return obj; + else throw e; + } + skipBlank(); + if (jsonString[index] === ',') index++; // skip comma + } + } catch (e) { + if (Allow.OBJ & allow) return obj; + else markPartialJSON("Expected '}' at end of object"); + } + index++; // skip final brace + return obj; + }; + + const parseArr = () => { + index++; // skip initial bracket + const arr = []; + try { + while (jsonString[index] !== ']') { + arr.push(parseAny()); + skipBlank(); + if (jsonString[index] === ',') { + index++; // skip comma + } + } + } catch (e) { + if (Allow.ARR & allow) { + return arr; + } + markPartialJSON("Expected ']' at end of array"); + } + index++; // skip final bracket + return arr; + }; + + const parseNum = () => { + if (index === 0) { + if (jsonString === '-' && Allow.NUM & allow) markPartialJSON("Not sure what '-' is"); + try { + return JSON.parse(jsonString); + } catch (e) { + if (Allow.NUM & allow) { + try { + if ('.' === jsonString[jsonString.length - 1]) + return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf('.'))); + return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf('e'))); + } catch (e) {} + } + throwMalformedError(String(e)); + } + } + + const start = index; + + if (jsonString[index] === '-') index++; + while (jsonString[index] && !',]}'.includes(jsonString[index]!)) index++; + + if (index == length && !(Allow.NUM & allow)) markPartialJSON('Unterminated number literal'); + + try { + return JSON.parse(jsonString.substring(start, index)); + } catch (e) { + if (jsonString.substring(start, index) === '-' && Allow.NUM & allow) + markPartialJSON("Not sure what '-' is"); + try { + return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf('e'))); + } catch (e) { + throwMalformedError(String(e)); + } + } + }; + + const skipBlank = () => { + while (index < length && ' \n\r\t'.includes(jsonString[index]!)) { + index++; + } + }; + + return parseAny(); +}; + +// using this function with malformed JSON is undefined behavior +const partialParse = (input: string) => parseJSON(input, Allow.ALL ^ Allow.NUM); + +export { partialParse, PartialJSON, MalformedJSON }; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/LICENSE b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a4690a1b6b6203ff63495243164edd0b17269d32 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/LICENSE @@ -0,0 +1,15 @@ +ISC License + +Copyright (c) 2020, Stefan Terdell + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/Options.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/Options.ts new file mode 100644 index 0000000000000000000000000000000000000000..a9abfc0e2b406b08ad366e45064589b7dc9c53ab --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/Options.ts @@ -0,0 +1,80 @@ +import { ZodSchema, ZodTypeDef } from 'zod'; +import { Refs, Seen } from './Refs'; +import { JsonSchema7Type } from './parseDef'; + +export type Targets = 'jsonSchema7' | 'jsonSchema2019-09' | 'openApi3'; + +export type DateStrategy = 'format:date-time' | 'format:date' | 'string' | 'integer'; + +export const ignoreOverride = Symbol('Let zodToJsonSchema decide on which parser to use'); + +export type Options = { + name: string | undefined; + $refStrategy: 'root' | 'relative' | 'none' | 'seen' | 'extract-to-root'; + basePath: string[]; + effectStrategy: 'input' | 'any'; + pipeStrategy: 'input' | 'output' | 'all'; + dateStrategy: DateStrategy | DateStrategy[]; + mapStrategy: 'entries' | 'record'; + removeAdditionalStrategy: 'passthrough' | 'strict'; + nullableStrategy: 'from-target' | 'property'; + target: Target; + strictUnions: boolean; + definitionPath: string; + definitions: Record; + errorMessages: boolean; + markdownDescription: boolean; + patternStrategy: 'escape' | 'preserve'; + applyRegexFlags: boolean; + emailStrategy: 'format:email' | 'format:idn-email' | 'pattern:zod'; + base64Strategy: 'format:binary' | 'contentEncoding:base64' | 'pattern:zod'; + nameStrategy: 'ref' | 'duplicate-ref' | 'title'; + override?: ( + def: ZodTypeDef, + refs: Refs, + seen: Seen | undefined, + forceResolution?: boolean, + ) => JsonSchema7Type | undefined | typeof ignoreOverride; + openaiStrictMode?: boolean; +}; + +const defaultOptions: Omit = { + name: undefined, + $refStrategy: 'root', + effectStrategy: 'input', + pipeStrategy: 'all', + dateStrategy: 'format:date-time', + mapStrategy: 'entries', + nullableStrategy: 'from-target', + removeAdditionalStrategy: 'passthrough', + definitionPath: 'definitions', + target: 'jsonSchema7', + strictUnions: false, + errorMessages: false, + markdownDescription: false, + patternStrategy: 'escape', + applyRegexFlags: false, + emailStrategy: 'format:email', + base64Strategy: 'contentEncoding:base64', + nameStrategy: 'ref', +}; + +export const getDefaultOptions = ( + options: Partial> | string | undefined, +) => { + // We need to add `definitions` here as we may mutate it + return ( + typeof options === 'string' ? + { + ...defaultOptions, + basePath: ['#'], + definitions: {}, + name: options, + } + : { + ...defaultOptions, + basePath: ['#'], + definitions: {}, + ...options, + }) as Options; +}; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/README.md b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ffb351242823a317aad335407c3851e6bb23f90b --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/README.md @@ -0,0 +1,3 @@ +# Zod to Json Schema + +Vendored version of https://github.com/StefanTerdell/zod-to-json-schema that has been updated to generate JSON Schemas that are compatible with OpenAI's [strict mode](https://platform.openai.com/docs/guides/structured-outputs/supported-schemas) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/Refs.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/Refs.ts new file mode 100644 index 0000000000000000000000000000000000000000..ea63c076aefe7ca20a517eed50cf3e45f9ec6671 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/Refs.ts @@ -0,0 +1,47 @@ +import type { ZodTypeDef } from 'zod'; +import { getDefaultOptions, Options, Targets } from './Options'; +import { JsonSchema7Type } from './parseDef'; +import { zodDef } from './util'; + +export type Refs = { + seen: Map; + /** + * Set of all the `$ref`s we created, e.g. `Set(['#/$defs/ui'])` + * this notable does not include any `definitions` that were + * explicitly given as an option. + */ + seenRefs: Set; + currentPath: string[]; + propertyPath: string[] | undefined; +} & Options; + +export type Seen = { + def: ZodTypeDef; + path: string[]; + jsonSchema: JsonSchema7Type | undefined; +}; + +export const getRefs = (options?: string | Partial>): Refs => { + const _options = getDefaultOptions(options); + const currentPath = + _options.name !== undefined ? + [..._options.basePath, _options.definitionPath, _options.name] + : _options.basePath; + return { + ..._options, + currentPath: currentPath, + propertyPath: undefined, + seenRefs: new Set(), + seen: new Map( + Object.entries(_options.definitions).map(([name, def]) => [ + zodDef(def), + { + def: zodDef(def), + path: [..._options.basePath, _options.definitionPath, name], + // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now. + jsonSchema: undefined, + }, + ]), + ), + }; +}; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/errorMessages.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/errorMessages.ts new file mode 100644 index 0000000000000000000000000000000000000000..ceb0e8b73e297e4b416f88c057ad4203888ac296 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/errorMessages.ts @@ -0,0 +1,31 @@ +import { JsonSchema7TypeUnion } from './parseDef'; +import { Refs } from './Refs'; + +export type ErrorMessages = Partial< + Omit<{ [key in keyof T]: string }, OmitProperties | 'type' | 'errorMessages'> +>; + +export function addErrorMessage }>( + res: T, + key: keyof T, + errorMessage: string | undefined, + refs: Refs, +) { + if (!refs?.errorMessages) return; + if (errorMessage) { + res.errorMessage = { + ...res.errorMessage, + [key]: errorMessage, + }; + } +} + +export function setResponseValueAndErrors< + Json7Type extends JsonSchema7TypeUnion & { + errorMessage?: ErrorMessages; + }, + Key extends keyof Omit, +>(res: Json7Type, key: Key, value: Json7Type[Key], errorMessage: string | undefined, refs: Refs) { + res[key] = value; + addErrorMessage(res, key, errorMessage, refs); +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/index.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..5808bc280e0f878befc9ccd96795c924a4f04922 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/index.ts @@ -0,0 +1,37 @@ +export * from './Options'; +export * from './Refs'; +export * from './errorMessages'; +export * from './parseDef'; +export * from './parsers/any'; +export * from './parsers/array'; +export * from './parsers/bigint'; +export * from './parsers/boolean'; +export * from './parsers/branded'; +export * from './parsers/catch'; +export * from './parsers/date'; +export * from './parsers/default'; +export * from './parsers/effects'; +export * from './parsers/enum'; +export * from './parsers/intersection'; +export * from './parsers/literal'; +export * from './parsers/map'; +export * from './parsers/nativeEnum'; +export * from './parsers/never'; +export * from './parsers/null'; +export * from './parsers/nullable'; +export * from './parsers/number'; +export * from './parsers/object'; +export * from './parsers/optional'; +export * from './parsers/pipeline'; +export * from './parsers/promise'; +export * from './parsers/readonly'; +export * from './parsers/record'; +export * from './parsers/set'; +export * from './parsers/string'; +export * from './parsers/tuple'; +export * from './parsers/undefined'; +export * from './parsers/union'; +export * from './parsers/unknown'; +export * from './zodToJsonSchema'; +import { zodToJsonSchema } from './zodToJsonSchema'; +export default zodToJsonSchema; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parseDef.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parseDef.ts new file mode 100644 index 0000000000000000000000000000000000000000..8af5ce4be9c4ae2ca275a9ee29dff65575750210 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parseDef.ts @@ -0,0 +1,258 @@ +import { ZodFirstPartyTypeKind, ZodTypeDef } from 'zod'; +import { JsonSchema7AnyType, parseAnyDef } from './parsers/any'; +import { JsonSchema7ArrayType, parseArrayDef } from './parsers/array'; +import { JsonSchema7BigintType, parseBigintDef } from './parsers/bigint'; +import { JsonSchema7BooleanType, parseBooleanDef } from './parsers/boolean'; +import { parseBrandedDef } from './parsers/branded'; +import { parseCatchDef } from './parsers/catch'; +import { JsonSchema7DateType, parseDateDef } from './parsers/date'; +import { parseDefaultDef } from './parsers/default'; +import { parseEffectsDef } from './parsers/effects'; +import { JsonSchema7EnumType, parseEnumDef } from './parsers/enum'; +import { JsonSchema7AllOfType, parseIntersectionDef } from './parsers/intersection'; +import { JsonSchema7LiteralType, parseLiteralDef } from './parsers/literal'; +import { JsonSchema7MapType, parseMapDef } from './parsers/map'; +import { JsonSchema7NativeEnumType, parseNativeEnumDef } from './parsers/nativeEnum'; +import { JsonSchema7NeverType, parseNeverDef } from './parsers/never'; +import { JsonSchema7NullType, parseNullDef } from './parsers/null'; +import { JsonSchema7NullableType, parseNullableDef } from './parsers/nullable'; +import { JsonSchema7NumberType, parseNumberDef } from './parsers/number'; +import { JsonSchema7ObjectType, parseObjectDef } from './parsers/object'; +import { parseOptionalDef } from './parsers/optional'; +import { parsePipelineDef } from './parsers/pipeline'; +import { parsePromiseDef } from './parsers/promise'; +import { JsonSchema7RecordType, parseRecordDef } from './parsers/record'; +import { JsonSchema7SetType, parseSetDef } from './parsers/set'; +import { JsonSchema7StringType, parseStringDef } from './parsers/string'; +import { JsonSchema7TupleType, parseTupleDef } from './parsers/tuple'; +import { JsonSchema7UndefinedType, parseUndefinedDef } from './parsers/undefined'; +import { JsonSchema7UnionType, parseUnionDef } from './parsers/union'; +import { JsonSchema7UnknownType, parseUnknownDef } from './parsers/unknown'; +import { Refs, Seen } from './Refs'; +import { parseReadonlyDef } from './parsers/readonly'; +import { ignoreOverride } from './Options'; + +type JsonSchema7RefType = { $ref: string }; +type JsonSchema7Meta = { + title?: string; + default?: any; + description?: string; + markdownDescription?: string; +}; + +export type JsonSchema7TypeUnion = + | JsonSchema7StringType + | JsonSchema7ArrayType + | JsonSchema7NumberType + | JsonSchema7BigintType + | JsonSchema7BooleanType + | JsonSchema7DateType + | JsonSchema7EnumType + | JsonSchema7LiteralType + | JsonSchema7NativeEnumType + | JsonSchema7NullType + | JsonSchema7NumberType + | JsonSchema7ObjectType + | JsonSchema7RecordType + | JsonSchema7TupleType + | JsonSchema7UnionType + | JsonSchema7UndefinedType + | JsonSchema7RefType + | JsonSchema7NeverType + | JsonSchema7MapType + | JsonSchema7AnyType + | JsonSchema7NullableType + | JsonSchema7AllOfType + | JsonSchema7UnknownType + | JsonSchema7SetType; + +export type JsonSchema7Type = JsonSchema7TypeUnion & JsonSchema7Meta; + +export function parseDef( + def: ZodTypeDef, + refs: Refs, + forceResolution = false, // Forces a new schema to be instantiated even though its def has been seen. Used for improving refs in definitions. See https://github.com/StefanTerdell/zod-to-json-schema/pull/61. +): JsonSchema7Type | undefined { + const seenItem = refs.seen.get(def); + + if (refs.override) { + const overrideResult = refs.override?.(def, refs, seenItem, forceResolution); + + if (overrideResult !== ignoreOverride) { + return overrideResult; + } + } + + if (seenItem && !forceResolution) { + const seenSchema = get$ref(seenItem, refs); + + if (seenSchema !== undefined) { + if ('$ref' in seenSchema) { + refs.seenRefs.add(seenSchema.$ref); + } + + return seenSchema; + } + } + + const newItem: Seen = { def, path: refs.currentPath, jsonSchema: undefined }; + + refs.seen.set(def, newItem); + + const jsonSchema = selectParser(def, (def as any).typeName, refs, forceResolution); + + if (jsonSchema) { + addMeta(def, refs, jsonSchema); + } + + newItem.jsonSchema = jsonSchema; + + return jsonSchema; +} + +const get$ref = ( + item: Seen, + refs: Refs, +): + | { + $ref: string; + } + | {} + | undefined => { + switch (refs.$refStrategy) { + case 'root': + return { $ref: item.path.join('/') }; + // this case is needed as OpenAI strict mode doesn't support top-level `$ref`s, i.e. + // the top-level schema *must* be `{"type": "object", "properties": {...}}` but if we ever + // need to define a `$ref`, relative `$ref`s aren't supported, so we need to extract + // the schema to `#/definitions/` and reference that. + // + // e.g. if we need to reference a schema at + // `["#","definitions","contactPerson","properties","person1","properties","name"]` + // then we'll extract it out to `contactPerson_properties_person1_properties_name` + case 'extract-to-root': + const name = item.path.slice(refs.basePath.length + 1).join('_'); + + // we don't need to extract the root schema in this case, as it's already + // been added to the definitions + if (name !== refs.name && refs.nameStrategy === 'duplicate-ref') { + refs.definitions[name] = item.def; + } + + return { $ref: [...refs.basePath, refs.definitionPath, name].join('/') }; + case 'relative': + return { $ref: getRelativePath(refs.currentPath, item.path) }; + case 'none': + case 'seen': { + if ( + item.path.length < refs.currentPath.length && + item.path.every((value, index) => refs.currentPath[index] === value) + ) { + console.warn(`Recursive reference detected at ${refs.currentPath.join('/')}! Defaulting to any`); + + return {}; + } + + return refs.$refStrategy === 'seen' ? {} : undefined; + } + } +}; + +const getRelativePath = (pathA: string[], pathB: string[]) => { + let i = 0; + for (; i < pathA.length && i < pathB.length; i++) { + if (pathA[i] !== pathB[i]) break; + } + return [(pathA.length - i).toString(), ...pathB.slice(i)].join('/'); +}; + +const selectParser = ( + def: any, + typeName: ZodFirstPartyTypeKind, + refs: Refs, + forceResolution: boolean, +): JsonSchema7Type | undefined => { + switch (typeName) { + case ZodFirstPartyTypeKind.ZodString: + return parseStringDef(def, refs); + case ZodFirstPartyTypeKind.ZodNumber: + return parseNumberDef(def, refs); + case ZodFirstPartyTypeKind.ZodObject: + return parseObjectDef(def, refs); + case ZodFirstPartyTypeKind.ZodBigInt: + return parseBigintDef(def, refs); + case ZodFirstPartyTypeKind.ZodBoolean: + return parseBooleanDef(); + case ZodFirstPartyTypeKind.ZodDate: + return parseDateDef(def, refs); + case ZodFirstPartyTypeKind.ZodUndefined: + return parseUndefinedDef(); + case ZodFirstPartyTypeKind.ZodNull: + return parseNullDef(refs); + case ZodFirstPartyTypeKind.ZodArray: + return parseArrayDef(def, refs); + case ZodFirstPartyTypeKind.ZodUnion: + case ZodFirstPartyTypeKind.ZodDiscriminatedUnion: + return parseUnionDef(def, refs); + case ZodFirstPartyTypeKind.ZodIntersection: + return parseIntersectionDef(def, refs); + case ZodFirstPartyTypeKind.ZodTuple: + return parseTupleDef(def, refs); + case ZodFirstPartyTypeKind.ZodRecord: + return parseRecordDef(def, refs); + case ZodFirstPartyTypeKind.ZodLiteral: + return parseLiteralDef(def, refs); + case ZodFirstPartyTypeKind.ZodEnum: + return parseEnumDef(def); + case ZodFirstPartyTypeKind.ZodNativeEnum: + return parseNativeEnumDef(def); + case ZodFirstPartyTypeKind.ZodNullable: + return parseNullableDef(def, refs); + case ZodFirstPartyTypeKind.ZodOptional: + return parseOptionalDef(def, refs); + case ZodFirstPartyTypeKind.ZodMap: + return parseMapDef(def, refs); + case ZodFirstPartyTypeKind.ZodSet: + return parseSetDef(def, refs); + case ZodFirstPartyTypeKind.ZodLazy: + return parseDef(def.getter()._def, refs); + case ZodFirstPartyTypeKind.ZodPromise: + return parsePromiseDef(def, refs); + case ZodFirstPartyTypeKind.ZodNaN: + case ZodFirstPartyTypeKind.ZodNever: + return parseNeverDef(); + case ZodFirstPartyTypeKind.ZodEffects: + return parseEffectsDef(def, refs, forceResolution); + case ZodFirstPartyTypeKind.ZodAny: + return parseAnyDef(); + case ZodFirstPartyTypeKind.ZodUnknown: + return parseUnknownDef(); + case ZodFirstPartyTypeKind.ZodDefault: + return parseDefaultDef(def, refs); + case ZodFirstPartyTypeKind.ZodBranded: + return parseBrandedDef(def, refs); + case ZodFirstPartyTypeKind.ZodReadonly: + return parseReadonlyDef(def, refs); + case ZodFirstPartyTypeKind.ZodCatch: + return parseCatchDef(def, refs); + case ZodFirstPartyTypeKind.ZodPipeline: + return parsePipelineDef(def, refs); + case ZodFirstPartyTypeKind.ZodFunction: + case ZodFirstPartyTypeKind.ZodVoid: + case ZodFirstPartyTypeKind.ZodSymbol: + return undefined; + default: + return ((_: never) => undefined)(typeName); + } +}; + +const addMeta = (def: ZodTypeDef, refs: Refs, jsonSchema: JsonSchema7Type): JsonSchema7Type => { + if (def.description) { + jsonSchema.description = def.description; + + if (refs.markdownDescription) { + jsonSchema.markdownDescription = def.description; + } + } + return jsonSchema; +}; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/any.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/any.ts new file mode 100644 index 0000000000000000000000000000000000000000..68c2921da7e0c0fec19bcc0785240c8cd50337b7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/any.ts @@ -0,0 +1,5 @@ +export type JsonSchema7AnyType = {}; + +export function parseAnyDef(): JsonSchema7AnyType { + return {}; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/array.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/array.ts new file mode 100644 index 0000000000000000000000000000000000000000..3e8578f8b08e1973bb9b08151e53a14de8e962ea --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/array.ts @@ -0,0 +1,36 @@ +import { ZodArrayDef, ZodFirstPartyTypeKind } from 'zod'; +import { ErrorMessages, setResponseValueAndErrors } from '../errorMessages'; +import { JsonSchema7Type, parseDef } from '../parseDef'; +import { Refs } from '../Refs'; + +export type JsonSchema7ArrayType = { + type: 'array'; + items?: JsonSchema7Type | undefined; + minItems?: number; + maxItems?: number; + errorMessages?: ErrorMessages; +}; + +export function parseArrayDef(def: ZodArrayDef, refs: Refs) { + const res: JsonSchema7ArrayType = { + type: 'array', + }; + if (def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) { + res.items = parseDef(def.type._def, { + ...refs, + currentPath: [...refs.currentPath, 'items'], + }); + } + + if (def.minLength) { + setResponseValueAndErrors(res, 'minItems', def.minLength.value, def.minLength.message, refs); + } + if (def.maxLength) { + setResponseValueAndErrors(res, 'maxItems', def.maxLength.value, def.maxLength.message, refs); + } + if (def.exactLength) { + setResponseValueAndErrors(res, 'minItems', def.exactLength.value, def.exactLength.message, refs); + setResponseValueAndErrors(res, 'maxItems', def.exactLength.value, def.exactLength.message, refs); + } + return res; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/bigint.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/bigint.ts new file mode 100644 index 0000000000000000000000000000000000000000..f46784184ecd0794fc8aeefb182cb94ad639e2a8 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/bigint.ts @@ -0,0 +1,60 @@ +import { ZodBigIntDef } from 'zod'; +import { Refs } from '../Refs'; +import { ErrorMessages, setResponseValueAndErrors } from '../errorMessages'; + +export type JsonSchema7BigintType = { + type: 'integer'; + format: 'int64'; + minimum?: BigInt; + exclusiveMinimum?: BigInt; + maximum?: BigInt; + exclusiveMaximum?: BigInt; + multipleOf?: BigInt; + errorMessage?: ErrorMessages; +}; + +export function parseBigintDef(def: ZodBigIntDef, refs: Refs): JsonSchema7BigintType { + const res: JsonSchema7BigintType = { + type: 'integer', + format: 'int64', + }; + + if (!def.checks) return res; + + for (const check of def.checks) { + switch (check.kind) { + case 'min': + if (refs.target === 'jsonSchema7') { + if (check.inclusive) { + setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs); + } else { + setResponseValueAndErrors(res, 'exclusiveMinimum', check.value, check.message, refs); + } + } else { + if (!check.inclusive) { + res.exclusiveMinimum = true as any; + } + setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs); + } + break; + case 'max': + if (refs.target === 'jsonSchema7') { + if (check.inclusive) { + setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs); + } else { + setResponseValueAndErrors(res, 'exclusiveMaximum', check.value, check.message, refs); + } + } else { + if (!check.inclusive) { + res.exclusiveMaximum = true as any; + } + setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs); + } + break; + case 'multipleOf': + setResponseValueAndErrors(res, 'multipleOf', check.value, check.message, refs); + break; + } + } + return res; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/boolean.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/boolean.ts new file mode 100644 index 0000000000000000000000000000000000000000..715e41acc3c2775c208a0bddbc7429abbf92c1b4 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/boolean.ts @@ -0,0 +1,9 @@ +export type JsonSchema7BooleanType = { + type: 'boolean'; +}; + +export function parseBooleanDef(): JsonSchema7BooleanType { + return { + type: 'boolean', + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/branded.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/branded.ts new file mode 100644 index 0000000000000000000000000000000000000000..2242580a59dcacf95810a4c8f43d6430b14245e1 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/branded.ts @@ -0,0 +1,7 @@ +import { ZodBrandedDef } from 'zod'; +import { parseDef } from '../parseDef'; +import { Refs } from '../Refs'; + +export function parseBrandedDef(_def: ZodBrandedDef, refs: Refs) { + return parseDef(_def.type._def, refs); +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/catch.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/catch.ts new file mode 100644 index 0000000000000000000000000000000000000000..5cce3afa1feff36e2463a779e610ae443f993eea --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/catch.ts @@ -0,0 +1,7 @@ +import { ZodCatchDef } from 'zod'; +import { parseDef } from '../parseDef'; +import { Refs } from '../Refs'; + +export const parseCatchDef = (def: ZodCatchDef, refs: Refs) => { + return parseDef(def.innerType._def, refs); +}; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/date.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/date.ts new file mode 100644 index 0000000000000000000000000000000000000000..4afc4e8dcb958b9ff01908823cd4b79e270f2924 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/date.ts @@ -0,0 +1,83 @@ +import { ZodDateDef } from 'zod'; +import { Refs } from '../Refs'; +import { ErrorMessages, setResponseValueAndErrors } from '../errorMessages'; +import { JsonSchema7NumberType } from './number'; +import { DateStrategy } from '../Options'; + +export type JsonSchema7DateType = + | { + type: 'integer' | 'string'; + format: 'unix-time' | 'date-time' | 'date'; + minimum?: number; + maximum?: number; + errorMessage?: ErrorMessages; + } + | { + anyOf: JsonSchema7DateType[]; + }; + +export function parseDateDef( + def: ZodDateDef, + refs: Refs, + overrideDateStrategy?: DateStrategy, +): JsonSchema7DateType { + const strategy = overrideDateStrategy ?? refs.dateStrategy; + + if (Array.isArray(strategy)) { + return { + anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)), + }; + } + + switch (strategy) { + case 'string': + case 'format:date-time': + return { + type: 'string', + format: 'date-time', + }; + case 'format:date': + return { + type: 'string', + format: 'date', + }; + case 'integer': + return integerDateParser(def, refs); + } +} + +const integerDateParser = (def: ZodDateDef, refs: Refs) => { + const res: JsonSchema7DateType = { + type: 'integer', + format: 'unix-time', + }; + + if (refs.target === 'openApi3') { + return res; + } + + for (const check of def.checks) { + switch (check.kind) { + case 'min': + setResponseValueAndErrors( + res, + 'minimum', + check.value, // This is in milliseconds + check.message, + refs, + ); + break; + case 'max': + setResponseValueAndErrors( + res, + 'maximum', + check.value, // This is in milliseconds + check.message, + refs, + ); + break; + } + } + + return res; +}; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/default.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/default.ts new file mode 100644 index 0000000000000000000000000000000000000000..f71726075a3a3abe34c2cea5ed933898840b21b0 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/default.ts @@ -0,0 +1,10 @@ +import { ZodDefaultDef } from 'zod'; +import { JsonSchema7Type, parseDef } from '../parseDef'; +import { Refs } from '../Refs'; + +export function parseDefaultDef(_def: ZodDefaultDef, refs: Refs): JsonSchema7Type & { default: any } { + return { + ...parseDef(_def.innerType._def, refs), + default: _def.defaultValue(), + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/effects.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/effects.ts new file mode 100644 index 0000000000000000000000000000000000000000..b010d5c4724b2d1ec3aef6a8492bda646020f560 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/effects.ts @@ -0,0 +1,11 @@ +import { ZodEffectsDef } from 'zod'; +import { JsonSchema7Type, parseDef } from '../parseDef'; +import { Refs } from '../Refs'; + +export function parseEffectsDef( + _def: ZodEffectsDef, + refs: Refs, + forceResolution: boolean, +): JsonSchema7Type | undefined { + return refs.effectStrategy === 'input' ? parseDef(_def.schema._def, refs, forceResolution) : {}; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/enum.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/enum.ts new file mode 100644 index 0000000000000000000000000000000000000000..d6f5ceb24075676d03f17f5ee2855e4e2d225e06 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/enum.ts @@ -0,0 +1,13 @@ +import { ZodEnumDef } from 'zod'; + +export type JsonSchema7EnumType = { + type: 'string'; + enum: string[]; +}; + +export function parseEnumDef(def: ZodEnumDef): JsonSchema7EnumType { + return { + type: 'string', + enum: [...def.values], + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/intersection.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/intersection.ts new file mode 100644 index 0000000000000000000000000000000000000000..af5f0421d98d9d0081da366a7f7dd0a49d134471 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/intersection.ts @@ -0,0 +1,64 @@ +import { ZodIntersectionDef } from 'zod'; +import { JsonSchema7Type, parseDef } from '../parseDef'; +import { Refs } from '../Refs'; +import { JsonSchema7StringType } from './string'; + +export type JsonSchema7AllOfType = { + allOf: JsonSchema7Type[]; + unevaluatedProperties?: boolean; +}; + +const isJsonSchema7AllOfType = ( + type: JsonSchema7Type | JsonSchema7StringType, +): type is JsonSchema7AllOfType => { + if ('type' in type && type.type === 'string') return false; + return 'allOf' in type; +}; + +export function parseIntersectionDef( + def: ZodIntersectionDef, + refs: Refs, +): JsonSchema7AllOfType | JsonSchema7Type | undefined { + const allOf = [ + parseDef(def.left._def, { + ...refs, + currentPath: [...refs.currentPath, 'allOf', '0'], + }), + parseDef(def.right._def, { + ...refs, + currentPath: [...refs.currentPath, 'allOf', '1'], + }), + ].filter((x): x is JsonSchema7Type => !!x); + + let unevaluatedProperties: Pick | undefined = + refs.target === 'jsonSchema2019-09' ? { unevaluatedProperties: false } : undefined; + + const mergedAllOf: JsonSchema7Type[] = []; + // If either of the schemas is an allOf, merge them into a single allOf + allOf.forEach((schema) => { + if (isJsonSchema7AllOfType(schema)) { + mergedAllOf.push(...schema.allOf); + if (schema.unevaluatedProperties === undefined) { + // If one of the schemas has no unevaluatedProperties set, + // the merged schema should also have no unevaluatedProperties set + unevaluatedProperties = undefined; + } + } else { + let nestedSchema: JsonSchema7Type = schema; + if ('additionalProperties' in schema && schema.additionalProperties === false) { + const { additionalProperties, ...rest } = schema; + nestedSchema = rest; + } else { + // As soon as one of the schemas has additionalProperties set not to false, we allow unevaluatedProperties + unevaluatedProperties = undefined; + } + mergedAllOf.push(nestedSchema); + } + }); + return mergedAllOf.length ? + { + allOf: mergedAllOf, + ...unevaluatedProperties, + } + : undefined; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/literal.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/literal.ts new file mode 100644 index 0000000000000000000000000000000000000000..a35625cfcab419428f9ff0f7c54bb13dbaf8fced --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/literal.ts @@ -0,0 +1,37 @@ +import { ZodLiteralDef } from 'zod'; +import { Refs } from '../Refs'; + +export type JsonSchema7LiteralType = + | { + type: 'string' | 'number' | 'integer' | 'boolean'; + const: string | number | boolean; + } + | { + type: 'object' | 'array'; + }; + +export function parseLiteralDef(def: ZodLiteralDef, refs: Refs): JsonSchema7LiteralType { + const parsedType = typeof def.value; + if ( + parsedType !== 'bigint' && + parsedType !== 'number' && + parsedType !== 'boolean' && + parsedType !== 'string' + ) { + return { + type: Array.isArray(def.value) ? 'array' : 'object', + }; + } + + if (refs.target === 'openApi3') { + return { + type: parsedType === 'bigint' ? 'integer' : parsedType, + enum: [def.value], + } as any; + } + + return { + type: parsedType === 'bigint' ? 'integer' : parsedType, + const: def.value, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/map.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/map.ts new file mode 100644 index 0000000000000000000000000000000000000000..5084ccd68936d4f5f71e98e35e79b02e852894ae --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/map.ts @@ -0,0 +1,42 @@ +import { ZodMapDef } from 'zod'; +import { JsonSchema7Type, parseDef } from '../parseDef'; +import { Refs } from '../Refs'; +import { JsonSchema7RecordType, parseRecordDef } from './record'; + +export type JsonSchema7MapType = { + type: 'array'; + maxItems: 125; + items: { + type: 'array'; + items: [JsonSchema7Type, JsonSchema7Type]; + minItems: 2; + maxItems: 2; + }; +}; + +export function parseMapDef(def: ZodMapDef, refs: Refs): JsonSchema7MapType | JsonSchema7RecordType { + if (refs.mapStrategy === 'record') { + return parseRecordDef(def, refs); + } + + const keys = + parseDef(def.keyType._def, { + ...refs, + currentPath: [...refs.currentPath, 'items', 'items', '0'], + }) || {}; + const values = + parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, 'items', 'items', '1'], + }) || {}; + return { + type: 'array', + maxItems: 125, + items: { + type: 'array', + items: [keys, values], + minItems: 2, + maxItems: 2, + }, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/nativeEnum.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/nativeEnum.ts new file mode 100644 index 0000000000000000000000000000000000000000..a2ed901bbbc69499e524c133940b8721b274c46b --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/nativeEnum.ts @@ -0,0 +1,27 @@ +import { ZodNativeEnumDef } from 'zod'; + +export type JsonSchema7NativeEnumType = { + type: 'string' | 'number' | ['string', 'number']; + enum: (string | number)[]; +}; + +export function parseNativeEnumDef(def: ZodNativeEnumDef): JsonSchema7NativeEnumType { + const object = def.values; + const actualKeys = Object.keys(def.values).filter((key: string) => { + return typeof object[object[key]!] !== 'number'; + }); + + const actualValues = actualKeys.map((key: string) => object[key]!); + + const parsedTypes = Array.from(new Set(actualValues.map((values: string | number) => typeof values))); + + return { + type: + parsedTypes.length === 1 ? + parsedTypes[0] === 'string' ? + 'string' + : 'number' + : ['string', 'number'], + enum: actualValues, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/never.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/never.ts new file mode 100644 index 0000000000000000000000000000000000000000..a5c7383d7309cb3907cbd4872ea85fbafdcc2e8e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/never.ts @@ -0,0 +1,9 @@ +export type JsonSchema7NeverType = { + not: {}; +}; + +export function parseNeverDef(): JsonSchema7NeverType { + return { + not: {}, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/null.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/null.ts new file mode 100644 index 0000000000000000000000000000000000000000..e1fe11362bd29273f8e3a7d50a12920f0fe58165 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/null.ts @@ -0,0 +1,16 @@ +import { Refs } from '../Refs'; + +export type JsonSchema7NullType = { + type: 'null'; +}; + +export function parseNullDef(refs: Refs): JsonSchema7NullType { + return refs.target === 'openApi3' ? + ({ + enum: ['null'], + nullable: true, + } as any) + : { + type: 'null', + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/nullable.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/nullable.ts new file mode 100644 index 0000000000000000000000000000000000000000..0d70636109b3d8d204a8275c516915a58de184a2 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/nullable.ts @@ -0,0 +1,49 @@ +import { ZodNullableDef } from 'zod'; +import { JsonSchema7Type, parseDef } from '../parseDef'; +import { Refs } from '../Refs'; +import { JsonSchema7NullType } from './null'; +import { primitiveMappings } from './union'; + +export type JsonSchema7NullableType = + | { + anyOf: [JsonSchema7Type, JsonSchema7NullType]; + } + | { + type: [string, 'null']; + }; + +export function parseNullableDef(def: ZodNullableDef, refs: Refs): JsonSchema7NullableType | undefined { + if ( + ['ZodString', 'ZodNumber', 'ZodBigInt', 'ZodBoolean', 'ZodNull'].includes(def.innerType._def.typeName) && + (!def.innerType._def.checks || !def.innerType._def.checks.length) + ) { + if (refs.target === 'openApi3' || refs.nullableStrategy === 'property') { + return { + type: primitiveMappings[def.innerType._def.typeName as keyof typeof primitiveMappings], + nullable: true, + } as any; + } + + return { + type: [primitiveMappings[def.innerType._def.typeName as keyof typeof primitiveMappings], 'null'], + }; + } + + if (refs.target === 'openApi3') { + const base = parseDef(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath], + }); + + if (base && '$ref' in base) return { allOf: [base], nullable: true } as any; + + return base && ({ ...base, nullable: true } as any); + } + + const base = parseDef(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath, 'anyOf', '0'], + }); + + return base && { anyOf: [base, { type: 'null' }] }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/number.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/number.ts new file mode 100644 index 0000000000000000000000000000000000000000..45a1f3c0291b335e99dd20823f013883a5e0f29a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/number.ts @@ -0,0 +1,62 @@ +import { ZodNumberDef } from 'zod'; +import { addErrorMessage, ErrorMessages, setResponseValueAndErrors } from '../errorMessages'; +import { Refs } from '../Refs'; + +export type JsonSchema7NumberType = { + type: 'number' | 'integer'; + minimum?: number; + exclusiveMinimum?: number; + maximum?: number; + exclusiveMaximum?: number; + multipleOf?: number; + errorMessage?: ErrorMessages; +}; + +export function parseNumberDef(def: ZodNumberDef, refs: Refs): JsonSchema7NumberType { + const res: JsonSchema7NumberType = { + type: 'number', + }; + + if (!def.checks) return res; + + for (const check of def.checks) { + switch (check.kind) { + case 'int': + res.type = 'integer'; + addErrorMessage(res, 'type', check.message, refs); + break; + case 'min': + if (refs.target === 'jsonSchema7') { + if (check.inclusive) { + setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs); + } else { + setResponseValueAndErrors(res, 'exclusiveMinimum', check.value, check.message, refs); + } + } else { + if (!check.inclusive) { + res.exclusiveMinimum = true as any; + } + setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs); + } + break; + case 'max': + if (refs.target === 'jsonSchema7') { + if (check.inclusive) { + setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs); + } else { + setResponseValueAndErrors(res, 'exclusiveMaximum', check.value, check.message, refs); + } + } else { + if (!check.inclusive) { + res.exclusiveMaximum = true as any; + } + setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs); + } + break; + case 'multipleOf': + setResponseValueAndErrors(res, 'multipleOf', check.value, check.message, refs); + break; + } + } + return res; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/object.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/object.ts new file mode 100644 index 0000000000000000000000000000000000000000..1335c6dd04d5e8554cd06962ffc23cb109e87262 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/object.ts @@ -0,0 +1,76 @@ +import { ZodObjectDef } from 'zod'; +import { JsonSchema7Type, parseDef } from '../parseDef'; +import { Refs } from '../Refs'; + +function decideAdditionalProperties(def: ZodObjectDef, refs: Refs) { + if (refs.removeAdditionalStrategy === 'strict') { + return def.catchall._def.typeName === 'ZodNever' ? + def.unknownKeys !== 'strict' + : parseDef(def.catchall._def, { + ...refs, + currentPath: [...refs.currentPath, 'additionalProperties'], + }) ?? true; + } else { + return def.catchall._def.typeName === 'ZodNever' ? + def.unknownKeys === 'passthrough' + : parseDef(def.catchall._def, { + ...refs, + currentPath: [...refs.currentPath, 'additionalProperties'], + }) ?? true; + } +} + +export type JsonSchema7ObjectType = { + type: 'object'; + properties: Record; + additionalProperties: boolean | JsonSchema7Type; + required?: string[]; +}; + +export function parseObjectDef(def: ZodObjectDef, refs: Refs) { + const result: JsonSchema7ObjectType = { + type: 'object', + ...Object.entries(def.shape()).reduce( + ( + acc: { + properties: Record; + required: string[]; + }, + [propName, propDef], + ) => { + if (propDef === undefined || propDef._def === undefined) return acc; + const propertyPath = [...refs.currentPath, 'properties', propName]; + const parsedDef = parseDef(propDef._def, { + ...refs, + currentPath: propertyPath, + propertyPath, + }); + if (parsedDef === undefined) return acc; + if ( + refs.openaiStrictMode && + propDef.isOptional() && + !propDef.isNullable() && + typeof propDef._def?.defaultValue === 'undefined' + ) { + throw new Error( + `Zod field at \`${propertyPath.join( + '/', + )}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`, + ); + } + return { + properties: { + ...acc.properties, + [propName]: parsedDef, + }, + required: + propDef.isOptional() && !refs.openaiStrictMode ? acc.required : [...acc.required, propName], + }; + }, + { properties: {}, required: [] }, + ), + additionalProperties: decideAdditionalProperties(def, refs), + }; + if (!result.required!.length) delete result.required; + return result; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/optional.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/optional.ts new file mode 100644 index 0000000000000000000000000000000000000000..6948d7c51b8eb8dd8870961298094c8091ae26aa --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/optional.ts @@ -0,0 +1,28 @@ +import { ZodOptionalDef } from 'zod'; +import { JsonSchema7Type, parseDef } from '../parseDef'; +import { Refs } from '../Refs'; + +export const parseOptionalDef = (def: ZodOptionalDef, refs: Refs): JsonSchema7Type | undefined => { + if ( + refs.propertyPath && + refs.currentPath.slice(0, refs.propertyPath.length).toString() === refs.propertyPath.toString() + ) { + return parseDef(def.innerType._def, { ...refs, currentPath: refs.currentPath }); + } + + const innerSchema = parseDef(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath, 'anyOf', '1'], + }); + + return innerSchema ? + { + anyOf: [ + { + not: {}, + }, + innerSchema, + ], + } + : {}; +}; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/pipeline.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/pipeline.ts new file mode 100644 index 0000000000000000000000000000000000000000..7fdcbae02cdb4ed746ff9bd16ccb3ca96d734fca --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/pipeline.ts @@ -0,0 +1,28 @@ +import { ZodPipelineDef } from 'zod'; +import { JsonSchema7Type, parseDef } from '../parseDef'; +import { Refs } from '../Refs'; +import { JsonSchema7AllOfType } from './intersection'; + +export const parsePipelineDef = ( + def: ZodPipelineDef, + refs: Refs, +): JsonSchema7AllOfType | JsonSchema7Type | undefined => { + if (refs.pipeStrategy === 'input') { + return parseDef(def.in._def, refs); + } else if (refs.pipeStrategy === 'output') { + return parseDef(def.out._def, refs); + } + + const a = parseDef(def.in._def, { + ...refs, + currentPath: [...refs.currentPath, 'allOf', '0'], + }); + const b = parseDef(def.out._def, { + ...refs, + currentPath: [...refs.currentPath, 'allOf', a ? '1' : '0'], + }); + + return { + allOf: [a, b].filter((x): x is JsonSchema7Type => x !== undefined), + }; +}; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/promise.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/promise.ts new file mode 100644 index 0000000000000000000000000000000000000000..f586d11390acf8a919f0026ba9ade32eb6dc84c9 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/promise.ts @@ -0,0 +1,7 @@ +import { ZodPromiseDef } from 'zod'; +import { JsonSchema7Type, parseDef } from '../parseDef'; +import { Refs } from '../Refs'; + +export function parsePromiseDef(def: ZodPromiseDef, refs: Refs): JsonSchema7Type | undefined { + return parseDef(def.type._def, refs); +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/readonly.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/readonly.ts new file mode 100644 index 0000000000000000000000000000000000000000..cecb937d3312bb0e0c791825a6c82656d3083112 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/readonly.ts @@ -0,0 +1,7 @@ +import { ZodReadonlyDef } from 'zod'; +import { parseDef } from '../parseDef'; +import { Refs } from '../Refs'; + +export const parseReadonlyDef = (def: ZodReadonlyDef, refs: Refs) => { + return parseDef(def.innerType._def, refs); +}; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/record.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/record.ts new file mode 100644 index 0000000000000000000000000000000000000000..7eff507fbd2354a6636f3d2104363285466973b4 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/record.ts @@ -0,0 +1,73 @@ +import { ZodFirstPartyTypeKind, ZodMapDef, ZodRecordDef, ZodTypeAny } from 'zod'; +import { JsonSchema7Type, parseDef } from '../parseDef'; +import { Refs } from '../Refs'; +import { JsonSchema7EnumType } from './enum'; +import { JsonSchema7ObjectType } from './object'; +import { JsonSchema7StringType, parseStringDef } from './string'; + +type JsonSchema7RecordPropertyNamesType = + | Omit + | Omit; + +export type JsonSchema7RecordType = { + type: 'object'; + additionalProperties: JsonSchema7Type; + propertyNames?: JsonSchema7RecordPropertyNamesType; +}; + +export function parseRecordDef( + def: ZodRecordDef | ZodMapDef, + refs: Refs, +): JsonSchema7RecordType { + if (refs.target === 'openApi3' && def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) { + return { + type: 'object', + required: def.keyType._def.values, + properties: def.keyType._def.values.reduce( + (acc: Record, key: string) => ({ + ...acc, + [key]: + parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, 'properties', key], + }) ?? {}, + }), + {}, + ), + additionalProperties: false, + } satisfies JsonSchema7ObjectType as any; + } + + const schema: JsonSchema7RecordType = { + type: 'object', + additionalProperties: + parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, 'additionalProperties'], + }) ?? {}, + }; + + if (refs.target === 'openApi3') { + return schema; + } + + if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) { + const keyType: JsonSchema7RecordPropertyNamesType = Object.entries( + parseStringDef(def.keyType._def, refs), + ).reduce((acc, [key, value]) => (key === 'type' ? acc : { ...acc, [key]: value }), {}); + + return { + ...schema, + propertyNames: keyType, + }; + } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) { + return { + ...schema, + propertyNames: { + enum: def.keyType._def.values, + }, + }; + } + + return schema; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/set.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/set.ts new file mode 100644 index 0000000000000000000000000000000000000000..05fa9ed7989dac801e23b59297a5aa98c7724533 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/set.ts @@ -0,0 +1,36 @@ +import { ZodSetDef } from 'zod'; +import { ErrorMessages, setResponseValueAndErrors } from '../errorMessages'; +import { JsonSchema7Type, parseDef } from '../parseDef'; +import { Refs } from '../Refs'; + +export type JsonSchema7SetType = { + type: 'array'; + uniqueItems: true; + items?: JsonSchema7Type | undefined; + minItems?: number; + maxItems?: number; + errorMessage?: ErrorMessages; +}; + +export function parseSetDef(def: ZodSetDef, refs: Refs): JsonSchema7SetType { + const items = parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, 'items'], + }); + + const schema: JsonSchema7SetType = { + type: 'array', + uniqueItems: true, + items, + }; + + if (def.minSize) { + setResponseValueAndErrors(schema, 'minItems', def.minSize.value, def.minSize.message, refs); + } + + if (def.maxSize) { + setResponseValueAndErrors(schema, 'maxItems', def.maxSize.value, def.maxSize.message, refs); + } + + return schema; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/string.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/string.ts new file mode 100644 index 0000000000000000000000000000000000000000..daa1a954aa41f218ff8d805ac6444fa0d5fe8022 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/string.ts @@ -0,0 +1,400 @@ +// @ts-nocheck +import { ZodStringDef } from 'zod'; +import { ErrorMessages, setResponseValueAndErrors } from '../errorMessages'; +import { Refs } from '../Refs'; + +let emojiRegex: RegExp | undefined; + +/** + * Generated from the regular expressions found here as of 2024-05-22: + * https://github.com/colinhacks/zod/blob/master/src/types.ts. + * + * Expressions with /i flag have been changed accordingly. + */ +export const zodPatterns = { + /** + * `c` was changed to `[cC]` to replicate /i flag + */ + cuid: /^[cC][^\s-]{8,}$/, + cuid2: /^[0-9a-z]+$/, + ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/, + /** + * `a-z` was added to replicate /i flag + */ + email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/, + /** + * Constructed a valid Unicode RegExp + * + * Lazily instantiate since this type of regex isn't supported + * in all envs (e.g. React Native). + * + * See: + * https://github.com/colinhacks/zod/issues/2433 + * Fix in Zod: + * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b + */ + emoji: () => { + if (emojiRegex === undefined) { + emojiRegex = RegExp('^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$', 'u'); + } + return emojiRegex; + }, + /** + * Unused + */ + uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/, + /** + * Unused + */ + ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/, + /** + * Unused + */ + ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, + base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, + nanoid: /^[a-zA-Z0-9_-]{21}$/, +} as const; + +export type JsonSchema7StringType = { + type: 'string'; + minLength?: number; + maxLength?: number; + format?: + | 'email' + | 'idn-email' + | 'uri' + | 'uuid' + | 'date-time' + | 'ipv4' + | 'ipv6' + | 'date' + | 'time' + | 'duration'; + pattern?: string; + allOf?: { + pattern: string; + errorMessage?: ErrorMessages<{ pattern: string }>; + }[]; + anyOf?: { + format: string; + errorMessage?: ErrorMessages<{ format: string }>; + }[]; + errorMessage?: ErrorMessages; + contentEncoding?: string; +}; + +export function parseStringDef(def: ZodStringDef, refs: Refs): JsonSchema7StringType { + const res: JsonSchema7StringType = { + type: 'string', + }; + + function processPattern(value: string): string { + return refs.patternStrategy === 'escape' ? escapeNonAlphaNumeric(value) : value; + } + + if (def.checks) { + for (const check of def.checks) { + switch (check.kind) { + case 'min': + setResponseValueAndErrors( + res, + 'minLength', + typeof res.minLength === 'number' ? Math.max(res.minLength, check.value) : check.value, + check.message, + refs, + ); + break; + case 'max': + setResponseValueAndErrors( + res, + 'maxLength', + typeof res.maxLength === 'number' ? Math.min(res.maxLength, check.value) : check.value, + check.message, + refs, + ); + + break; + case 'email': + switch (refs.emailStrategy) { + case 'format:email': + addFormat(res, 'email', check.message, refs); + break; + case 'format:idn-email': + addFormat(res, 'idn-email', check.message, refs); + break; + case 'pattern:zod': + addPattern(res, zodPatterns.email, check.message, refs); + break; + } + + break; + case 'url': + addFormat(res, 'uri', check.message, refs); + break; + case 'uuid': + addFormat(res, 'uuid', check.message, refs); + break; + case 'regex': + addPattern(res, check.regex, check.message, refs); + break; + case 'cuid': + addPattern(res, zodPatterns.cuid, check.message, refs); + break; + case 'cuid2': + addPattern(res, zodPatterns.cuid2, check.message, refs); + break; + case 'startsWith': + addPattern(res, RegExp(`^${processPattern(check.value)}`), check.message, refs); + break; + case 'endsWith': + addPattern(res, RegExp(`${processPattern(check.value)}$`), check.message, refs); + break; + + case 'datetime': + addFormat(res, 'date-time', check.message, refs); + break; + case 'date': + addFormat(res, 'date', check.message, refs); + break; + case 'time': + addFormat(res, 'time', check.message, refs); + break; + case 'duration': + addFormat(res, 'duration', check.message, refs); + break; + case 'length': + setResponseValueAndErrors( + res, + 'minLength', + typeof res.minLength === 'number' ? Math.max(res.minLength, check.value) : check.value, + check.message, + refs, + ); + setResponseValueAndErrors( + res, + 'maxLength', + typeof res.maxLength === 'number' ? Math.min(res.maxLength, check.value) : check.value, + check.message, + refs, + ); + break; + case 'includes': { + addPattern(res, RegExp(processPattern(check.value)), check.message, refs); + break; + } + case 'ip': { + if (check.version !== 'v6') { + addFormat(res, 'ipv4', check.message, refs); + } + if (check.version !== 'v4') { + addFormat(res, 'ipv6', check.message, refs); + } + break; + } + case 'emoji': + addPattern(res, zodPatterns.emoji, check.message, refs); + break; + case 'ulid': { + addPattern(res, zodPatterns.ulid, check.message, refs); + break; + } + case 'base64': { + switch (refs.base64Strategy) { + case 'format:binary': { + addFormat(res, 'binary' as any, check.message, refs); + break; + } + + case 'contentEncoding:base64': { + setResponseValueAndErrors(res, 'contentEncoding', 'base64', check.message, refs); + break; + } + + case 'pattern:zod': { + addPattern(res, zodPatterns.base64, check.message, refs); + break; + } + } + break; + } + case 'nanoid': { + addPattern(res, zodPatterns.nanoid, check.message, refs); + } + case 'toLowerCase': + case 'toUpperCase': + case 'trim': + break; + default: + ((_: never) => {})(check); + } + } + } + + return res; +} + +const escapeNonAlphaNumeric = (value: string) => + Array.from(value) + .map((c) => (/[a-zA-Z0-9]/.test(c) ? c : `\\${c}`)) + .join(''); + +const addFormat = ( + schema: JsonSchema7StringType, + value: Required['format'], + message: string | undefined, + refs: Refs, +) => { + if (schema.format || schema.anyOf?.some((x) => x.format)) { + if (!schema.anyOf) { + schema.anyOf = []; + } + + if (schema.format) { + schema.anyOf!.push({ + format: schema.format, + ...(schema.errorMessage && + refs.errorMessages && { + errorMessage: { format: schema.errorMessage.format }, + }), + }); + delete schema.format; + if (schema.errorMessage) { + delete schema.errorMessage.format; + if (Object.keys(schema.errorMessage).length === 0) { + delete schema.errorMessage; + } + } + } + + schema.anyOf!.push({ + format: value, + ...(message && refs.errorMessages && { errorMessage: { format: message } }), + }); + } else { + setResponseValueAndErrors(schema, 'format', value, message, refs); + } +}; + +const addPattern = ( + schema: JsonSchema7StringType, + regex: RegExp | (() => RegExp), + message: string | undefined, + refs: Refs, +) => { + if (schema.pattern || schema.allOf?.some((x) => x.pattern)) { + if (!schema.allOf) { + schema.allOf = []; + } + + if (schema.pattern) { + schema.allOf!.push({ + pattern: schema.pattern, + ...(schema.errorMessage && + refs.errorMessages && { + errorMessage: { pattern: schema.errorMessage.pattern }, + }), + }); + delete schema.pattern; + if (schema.errorMessage) { + delete schema.errorMessage.pattern; + if (Object.keys(schema.errorMessage).length === 0) { + delete schema.errorMessage; + } + } + } + + schema.allOf!.push({ + pattern: processRegExp(regex, refs), + ...(message && refs.errorMessages && { errorMessage: { pattern: message } }), + }); + } else { + setResponseValueAndErrors(schema, 'pattern', processRegExp(regex, refs), message, refs); + } +}; + +// Mutate z.string.regex() in a best attempt to accommodate for regex flags when applyRegexFlags is true +const processRegExp = (regexOrFunction: RegExp | (() => RegExp), refs: Refs): string => { + const regex = typeof regexOrFunction === 'function' ? regexOrFunction() : regexOrFunction; + if (!refs.applyRegexFlags || !regex.flags) return regex.source; + + // Currently handled flags + const flags = { + i: regex.flags.includes('i'), // Case-insensitive + m: regex.flags.includes('m'), // `^` and `$` matches adjacent to newline characters + s: regex.flags.includes('s'), // `.` matches newlines + }; + + // The general principle here is to step through each character, one at a time, applying mutations as flags require. We keep track when the current character is escaped, and when it's inside a group /like [this]/ or (also) a range like /[a-z]/. The following is fairly brittle imperative code; edit at your peril! + + const source = flags.i ? regex.source.toLowerCase() : regex.source; + let pattern = ''; + let isEscaped = false; + let inCharGroup = false; + let inCharRange = false; + + for (let i = 0; i < source.length; i++) { + if (isEscaped) { + pattern += source[i]; + isEscaped = false; + continue; + } + + if (flags.i) { + if (inCharGroup) { + if (source[i].match(/[a-z]/)) { + if (inCharRange) { + pattern += source[i]; + pattern += `${source[i - 2]}-${source[i]}`.toUpperCase(); + inCharRange = false; + } else if (source[i + 1] === '-' && source[i + 2]?.match(/[a-z]/)) { + pattern += source[i]; + inCharRange = true; + } else { + pattern += `${source[i]}${source[i].toUpperCase()}`; + } + continue; + } + } else if (source[i].match(/[a-z]/)) { + pattern += `[${source[i]}${source[i].toUpperCase()}]`; + continue; + } + } + + if (flags.m) { + if (source[i] === '^') { + pattern += `(^|(?<=[\r\n]))`; + continue; + } else if (source[i] === '$') { + pattern += `($|(?=[\r\n]))`; + continue; + } + } + + if (flags.s && source[i] === '.') { + pattern += inCharGroup ? `${source[i]}\r\n` : `[${source[i]}\r\n]`; + continue; + } + + pattern += source[i]; + if (source[i] === '\\') { + isEscaped = true; + } else if (inCharGroup && source[i] === ']') { + inCharGroup = false; + } else if (!inCharGroup && source[i] === '[') { + inCharGroup = true; + } + } + + try { + const regexTest = new RegExp(pattern); + } catch { + console.warn( + `Could not convert regex pattern at ${refs.currentPath.join( + '/', + )} to a flag-independent form! Falling back to the flag-ignorant source`, + ); + return regex.source; + } + + return pattern; +}; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/tuple.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/tuple.ts new file mode 100644 index 0000000000000000000000000000000000000000..b2a8240062d42192e7157d703886261e8102a121 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/tuple.ts @@ -0,0 +1,54 @@ +import { ZodTupleDef, ZodTupleItems, ZodTypeAny } from 'zod'; +import { JsonSchema7Type, parseDef } from '../parseDef'; +import { Refs } from '../Refs'; + +export type JsonSchema7TupleType = { + type: 'array'; + minItems: number; + items: JsonSchema7Type[]; +} & ( + | { + maxItems: number; + } + | { + additionalItems?: JsonSchema7Type | undefined; + } +); + +export function parseTupleDef( + def: ZodTupleDef, + refs: Refs, +): JsonSchema7TupleType { + if (def.rest) { + return { + type: 'array', + minItems: def.items.length, + items: def.items + .map((x, i) => + parseDef(x._def, { + ...refs, + currentPath: [...refs.currentPath, 'items', `${i}`], + }), + ) + .reduce((acc: JsonSchema7Type[], x) => (x === undefined ? acc : [...acc, x]), []), + additionalItems: parseDef(def.rest._def, { + ...refs, + currentPath: [...refs.currentPath, 'additionalItems'], + }), + }; + } else { + return { + type: 'array', + minItems: def.items.length, + maxItems: def.items.length, + items: def.items + .map((x, i) => + parseDef(x._def, { + ...refs, + currentPath: [...refs.currentPath, 'items', `${i}`], + }), + ) + .reduce((acc: JsonSchema7Type[], x) => (x === undefined ? acc : [...acc, x]), []), + }; + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/undefined.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/undefined.ts new file mode 100644 index 0000000000000000000000000000000000000000..6864d8138f41f3c60628348fd1978efe6990eb3c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/undefined.ts @@ -0,0 +1,9 @@ +export type JsonSchema7UndefinedType = { + not: {}; +}; + +export function parseUndefinedDef(): JsonSchema7UndefinedType { + return { + not: {}, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/union.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/union.ts new file mode 100644 index 0000000000000000000000000000000000000000..1daf149085ca4392e4a7f5c4dfc1900467792d7e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/union.ts @@ -0,0 +1,119 @@ +import { ZodDiscriminatedUnionDef, ZodLiteralDef, ZodTypeAny, ZodUnionDef } from 'zod'; +import { JsonSchema7Type, parseDef } from '../parseDef'; +import { Refs } from '../Refs'; + +export const primitiveMappings = { + ZodString: 'string', + ZodNumber: 'number', + ZodBigInt: 'integer', + ZodBoolean: 'boolean', + ZodNull: 'null', +} as const; +type ZodPrimitive = keyof typeof primitiveMappings; +type JsonSchema7Primitive = (typeof primitiveMappings)[keyof typeof primitiveMappings]; + +export type JsonSchema7UnionType = JsonSchema7PrimitiveUnionType | JsonSchema7AnyOfType; + +type JsonSchema7PrimitiveUnionType = + | { + type: JsonSchema7Primitive | JsonSchema7Primitive[]; + } + | { + type: JsonSchema7Primitive | JsonSchema7Primitive[]; + enum: (string | number | bigint | boolean | null)[]; + }; + +type JsonSchema7AnyOfType = { + anyOf: JsonSchema7Type[]; +}; + +export function parseUnionDef( + def: ZodUnionDef | ZodDiscriminatedUnionDef, + refs: Refs, +): JsonSchema7PrimitiveUnionType | JsonSchema7AnyOfType | undefined { + if (refs.target === 'openApi3') return asAnyOf(def, refs); + + const options: readonly ZodTypeAny[] = + def.options instanceof Map ? Array.from(def.options.values()) : def.options; + + // This blocks tries to look ahead a bit to produce nicer looking schemas with type array instead of anyOf. + if ( + options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length)) + ) { + // all types in union are primitive and lack checks, so might as well squash into {type: [...]} + + const types = options.reduce((types: JsonSchema7Primitive[], x) => { + const type = primitiveMappings[x._def.typeName as ZodPrimitive]; //Can be safely casted due to row 43 + return type && !types.includes(type) ? [...types, type] : types; + }, []); + + return { + type: types.length > 1 ? types : types[0]!, + }; + } else if (options.every((x) => x._def.typeName === 'ZodLiteral' && !x.description)) { + // all options literals + + const types = options.reduce((acc: JsonSchema7Primitive[], x: { _def: ZodLiteralDef }) => { + const type = typeof x._def.value; + switch (type) { + case 'string': + case 'number': + case 'boolean': + return [...acc, type]; + case 'bigint': + return [...acc, 'integer' as const]; + case 'object': + if (x._def.value === null) return [...acc, 'null' as const]; + case 'symbol': + case 'undefined': + case 'function': + default: + return acc; + } + }, []); + + if (types.length === options.length) { + // all the literals are primitive, as far as null can be considered primitive + + const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i); + return { + type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0]!, + enum: options.reduce( + (acc, x) => { + return acc.includes(x._def.value) ? acc : [...acc, x._def.value]; + }, + [] as (string | number | bigint | boolean | null)[], + ), + }; + } + } else if (options.every((x) => x._def.typeName === 'ZodEnum')) { + return { + type: 'string', + enum: options.reduce( + (acc: string[], x) => [...acc, ...x._def.values.filter((x: string) => !acc.includes(x))], + [], + ), + }; + } + + return asAnyOf(def, refs); +} + +const asAnyOf = ( + def: ZodUnionDef | ZodDiscriminatedUnionDef, + refs: Refs, +): JsonSchema7PrimitiveUnionType | JsonSchema7AnyOfType | undefined => { + const anyOf = ((def.options instanceof Map ? Array.from(def.options.values()) : def.options) as any[]) + .map((x, i) => + parseDef(x._def, { + ...refs, + currentPath: [...refs.currentPath, 'anyOf', `${i}`], + }), + ) + .filter( + (x): x is JsonSchema7Type => + !!x && (!refs.strictUnions || (typeof x === 'object' && Object.keys(x).length > 0)), + ); + + return anyOf.length ? { anyOf } : undefined; +}; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/unknown.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/unknown.ts new file mode 100644 index 0000000000000000000000000000000000000000..a3c8d1d96dbc003145e8eefd65b11e11b54dc95d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/parsers/unknown.ts @@ -0,0 +1,5 @@ +export type JsonSchema7UnknownType = {}; + +export function parseUnknownDef(): JsonSchema7UnknownType { + return {}; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/util.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/util.ts new file mode 100644 index 0000000000000000000000000000000000000000..870ab47a288909a9dad2ada8199e36efe9934711 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/util.ts @@ -0,0 +1,11 @@ +import type { ZodSchema, ZodTypeDef } from 'zod'; + +export const zodDef = (zodSchema: ZodSchema | ZodTypeDef): ZodTypeDef => { + return '_def' in zodSchema ? zodSchema._def : zodSchema; +}; + +export function isEmptyObj(obj: Object | null | undefined): boolean { + if (!obj) return true; + for (const _k in obj) return false; + return true; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/zodToJsonSchema.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/zodToJsonSchema.ts new file mode 100644 index 0000000000000000000000000000000000000000..e0d63d5257da369362d68fb53e40c6ee0a0b195e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/_vendor/zod-to-json-schema/zodToJsonSchema.ts @@ -0,0 +1,120 @@ +import { ZodSchema } from 'zod'; +import { Options, Targets } from './Options'; +import { JsonSchema7Type, parseDef } from './parseDef'; +import { getRefs } from './Refs'; +import { zodDef, isEmptyObj } from './util'; + +const zodToJsonSchema = ( + schema: ZodSchema, + options?: Partial> | string, +): (Target extends 'jsonSchema7' ? JsonSchema7Type : object) & { + $schema?: string; + definitions?: { + [key: string]: Target extends 'jsonSchema7' ? JsonSchema7Type + : Target extends 'jsonSchema2019-09' ? JsonSchema7Type + : object; + }; +} => { + const refs = getRefs(options); + + const name = + typeof options === 'string' ? options + : options?.nameStrategy === 'title' ? undefined + : options?.name; + + const main = + parseDef( + schema._def, + name === undefined ? refs : ( + { + ...refs, + currentPath: [...refs.basePath, refs.definitionPath, name], + } + ), + false, + ) ?? {}; + + const title = + typeof options === 'object' && options.name !== undefined && options.nameStrategy === 'title' ? + options.name + : undefined; + + if (title !== undefined) { + main.title = title; + } + + const definitions = (() => { + if (isEmptyObj(refs.definitions)) { + return undefined; + } + + const definitions: Record = {}; + const processedDefinitions = new Set(); + + // the call to `parseDef()` here might itself add more entries to `.definitions` + // so we need to continually evaluate definitions until we've resolved all of them + // + // we have a generous iteration limit here to avoid blowing up the stack if there + // are any bugs that would otherwise result in us iterating indefinitely + for (let i = 0; i < 500; i++) { + const newDefinitions = Object.entries(refs.definitions).filter( + ([key]) => !processedDefinitions.has(key), + ); + if (newDefinitions.length === 0) break; + + for (const [key, schema] of newDefinitions) { + definitions[key] = + parseDef( + zodDef(schema), + { ...refs, currentPath: [...refs.basePath, refs.definitionPath, key] }, + true, + ) ?? {}; + processedDefinitions.add(key); + } + } + + return definitions; + })(); + + const combined: ReturnType> = + name === undefined ? + definitions ? + { + ...main, + [refs.definitionPath]: definitions, + } + : main + : refs.nameStrategy === 'duplicate-ref' ? + { + ...main, + ...(definitions || refs.seenRefs.size ? + { + [refs.definitionPath]: { + ...definitions, + // only actually duplicate the schema definition if it was ever referenced + // otherwise the duplication is completely pointless + ...(refs.seenRefs.size ? { [name]: main } : undefined), + }, + } + : undefined), + } + : { + $ref: [...(refs.$refStrategy === 'relative' ? [] : refs.basePath), refs.definitionPath, name].join( + '/', + ), + [refs.definitionPath]: { + ...definitions, + [name]: main, + }, + }; + + if (refs.target === 'jsonSchema7') { + combined.$schema = 'http://json-schema.org/draft-07/schema#'; + } else if (refs.target === 'jsonSchema2019-09') { + combined.$schema = 'https://json-schema.org/draft/2019-09/schema#'; + } + + return combined; +}; + +export { zodToJsonSchema }; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/beta/realtime/index.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/beta/realtime/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..75f0f30882b8096a3bd102f0665fb7eae250a819 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/beta/realtime/index.ts @@ -0,0 +1 @@ +export { OpenAIRealtimeError } from './internal-base'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/beta/realtime/internal-base.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/beta/realtime/internal-base.ts new file mode 100644 index 0000000000000000000000000000000000000000..b704812ee7ac4f128ea6d4eae2e470ff044587d7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/beta/realtime/internal-base.ts @@ -0,0 +1,93 @@ +import { RealtimeClientEvent, RealtimeServerEvent, ErrorEvent } from '../../resources/beta/realtime/realtime'; +import { EventEmitter } from '../../lib/EventEmitter'; +import { OpenAIError } from '../../error'; +import OpenAI, { AzureOpenAI } from '../../index'; + +export class OpenAIRealtimeError extends OpenAIError { + /** + * The error data that the API sent back in an `error` event. + */ + error?: ErrorEvent.Error | undefined; + + /** + * The unique ID of the server event. + */ + event_id?: string | undefined; + + constructor(message: string, event: ErrorEvent | null) { + super(message); + + this.error = event?.error; + this.event_id = event?.event_id; + } +} + +type Simplify = { [KeyType in keyof T]: T[KeyType] } & {}; + +type RealtimeEvents = Simplify< + { + event: (event: RealtimeServerEvent) => void; + error: (error: OpenAIRealtimeError) => void; + } & { + [EventType in Exclude]: ( + event: Extract, + ) => unknown; + } +>; + +export abstract class OpenAIRealtimeEmitter extends EventEmitter { + /** + * Send an event to the API. + */ + abstract send(event: RealtimeClientEvent): void; + + /** + * Close the websocket connection. + */ + abstract close(props?: { code: number; reason: string }): void; + + protected _onError(event: null, message: string, cause: any): void; + protected _onError(event: ErrorEvent, message?: string | undefined): void; + protected _onError(event: ErrorEvent | null, message?: string | undefined, cause?: any): void { + message = + event?.error ? + `${event.error.message} code=${event.error.code} param=${event.error.param} type=${event.error.type} event_id=${event.error.event_id}` + : message ?? 'unknown error'; + + if (!this._hasListener('error')) { + const error = new OpenAIRealtimeError( + message + + `\n\nTo resolve these unhandled rejection errors you should bind an \`error\` callback, e.g. \`rt.on('error', (error) => ...)\` `, + event, + ); + // @ts-ignore + error.cause = cause; + Promise.reject(error); + return; + } + + const error = new OpenAIRealtimeError(message, event); + // @ts-ignore + error.cause = cause; + + this._emit('error', error); + } +} + +export function isAzure(client: Pick): client is AzureOpenAI { + return client instanceof AzureOpenAI; +} + +export function buildRealtimeURL(client: Pick, model: string): URL { + const path = '/realtime'; + const baseURL = client.baseURL; + const url = new URL(baseURL + (baseURL.endsWith('/') ? path.slice(1) : path)); + url.protocol = 'wss'; + if (isAzure(client)) { + url.searchParams.set('api-version', client.apiVersion); + url.searchParams.set('deployment', model); + } else { + url.searchParams.set('model', model); + } + return url; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/beta/realtime/websocket.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/beta/realtime/websocket.ts new file mode 100644 index 0000000000000000000000000000000000000000..2bf0b75d54b4f459a08e64ef06b800358a49e703 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/beta/realtime/websocket.ts @@ -0,0 +1,143 @@ +import { AzureOpenAI, OpenAI } from '../../index'; +import { OpenAIError } from '../../error'; +import type { RealtimeClientEvent, RealtimeServerEvent } from '../../resources/beta/realtime/realtime'; +import { OpenAIRealtimeEmitter, buildRealtimeURL, isAzure } from './internal-base'; +import { isRunningInBrowser } from '../../internal/detect-platform'; + +interface MessageEvent { + data: string; +} + +type _WebSocket = + typeof globalThis extends ( + { + WebSocket: infer ws extends abstract new (...args: any) => any; + } + ) ? + // @ts-ignore + InstanceType + : any; + +export class OpenAIRealtimeWebSocket extends OpenAIRealtimeEmitter { + url: URL; + socket: _WebSocket; + + constructor( + props: { + model: string; + dangerouslyAllowBrowser?: boolean; + /** + * Callback to mutate the URL, needed for Azure. + * @internal + */ + onURL?: (url: URL) => void; + }, + client?: Pick, + ) { + super(); + + const dangerouslyAllowBrowser = + props.dangerouslyAllowBrowser ?? + (client as any)?._options?.dangerouslyAllowBrowser ?? + (client?.apiKey.startsWith('ek_') ? true : null); + + if (!dangerouslyAllowBrowser && isRunningInBrowser()) { + throw new OpenAIError( + "It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\n\nYou can avoid this error by creating an ephemeral session token:\nhttps://platform.openai.com/docs/api-reference/realtime-sessions\n", + ); + } + + client ??= new OpenAI({ dangerouslyAllowBrowser }); + + this.url = buildRealtimeURL(client, props.model); + props.onURL?.(this.url); + + // @ts-ignore + this.socket = new WebSocket(this.url.toString(), [ + 'realtime', + ...(isAzure(client) ? [] : [`openai-insecure-api-key.${client.apiKey}`]), + 'openai-beta.realtime-v1', + ]); + + this.socket.addEventListener('message', (websocketEvent: MessageEvent) => { + const event = (() => { + try { + return JSON.parse(websocketEvent.data.toString()) as RealtimeServerEvent; + } catch (err) { + this._onError(null, 'could not parse websocket event', err); + return null; + } + })(); + + if (event) { + this._emit('event', event); + + if (event.type === 'error') { + this._onError(event); + } else { + // @ts-expect-error TS isn't smart enough to get the relationship right here + this._emit(event.type, event); + } + } + }); + + this.socket.addEventListener('error', (event: any) => { + this._onError(null, event.message, null); + }); + + if (isAzure(client)) { + if (this.url.searchParams.get('Authorization') !== null) { + this.url.searchParams.set('Authorization', ''); + } else { + this.url.searchParams.set('api-key', ''); + } + } + } + + static async azure( + client: Pick, + options: { deploymentName?: string; dangerouslyAllowBrowser?: boolean } = {}, + ): Promise { + const token = await client._getAzureADToken(); + function onURL(url: URL) { + if (client.apiKey !== '') { + url.searchParams.set('api-key', client.apiKey); + } else { + if (token) { + url.searchParams.set('Authorization', `Bearer ${token}`); + } else { + throw new Error('AzureOpenAI is not instantiated correctly. No API key or token provided.'); + } + } + } + const deploymentName = options.deploymentName ?? client.deploymentName; + if (!deploymentName) { + throw new Error('No deployment name provided'); + } + const { dangerouslyAllowBrowser } = options; + return new OpenAIRealtimeWebSocket( + { + model: deploymentName, + onURL, + ...(dangerouslyAllowBrowser ? { dangerouslyAllowBrowser } : {}), + }, + client, + ); + } + + send(event: RealtimeClientEvent) { + try { + this.socket.send(JSON.stringify(event)); + } catch (err) { + this._onError(null, 'could not send data', err); + } + } + + close(props?: { code: number; reason: string }) { + try { + this.socket.close(props?.code ?? 1000, props?.reason ?? 'OK'); + } catch (err) { + this._onError(null, 'could not close the connection', err); + } + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/beta/realtime/ws.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/beta/realtime/ws.ts new file mode 100644 index 0000000000000000000000000000000000000000..3f51dfc4bdbef657049523336edb732710266745 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/beta/realtime/ws.ts @@ -0,0 +1,96 @@ +import * as WS from 'ws'; +import { AzureOpenAI, OpenAI } from '../../index'; +import type { RealtimeClientEvent, RealtimeServerEvent } from '../../resources/beta/realtime/realtime'; +import { OpenAIRealtimeEmitter, buildRealtimeURL, isAzure } from './internal-base'; + +export class OpenAIRealtimeWS extends OpenAIRealtimeEmitter { + url: URL; + socket: WS.WebSocket; + + constructor( + props: { model: string; options?: WS.ClientOptions | undefined }, + client?: Pick, + ) { + super(); + client ??= new OpenAI(); + + this.url = buildRealtimeURL(client, props.model); + this.socket = new WS.WebSocket(this.url, { + ...props.options, + headers: { + ...props.options?.headers, + ...(isAzure(client) ? {} : { Authorization: `Bearer ${client.apiKey}` }), + 'OpenAI-Beta': 'realtime=v1', + }, + }); + + this.socket.on('message', (wsEvent) => { + const event = (() => { + try { + return JSON.parse(wsEvent.toString()) as RealtimeServerEvent; + } catch (err) { + this._onError(null, 'could not parse websocket event', err); + return null; + } + })(); + + if (event) { + this._emit('event', event); + + if (event.type === 'error') { + this._onError(event); + } else { + // @ts-expect-error TS isn't smart enough to get the relationship right here + this._emit(event.type, event); + } + } + }); + + this.socket.on('error', (err) => { + this._onError(null, err.message, err); + }); + } + + static async azure( + client: Pick, + options: { deploymentName?: string; options?: WS.ClientOptions | undefined } = {}, + ): Promise { + const deploymentName = options.deploymentName ?? client.deploymentName; + if (!deploymentName) { + throw new Error('No deployment name provided'); + } + return new OpenAIRealtimeWS( + { model: deploymentName, options: { headers: await getAzureHeaders(client) } }, + client, + ); + } + + send(event: RealtimeClientEvent) { + try { + this.socket.send(JSON.stringify(event)); + } catch (err) { + this._onError(null, 'could not send data', err); + } + } + + close(props?: { code: number; reason: string }) { + try { + this.socket.close(props?.code ?? 1000, props?.reason ?? 'OK'); + } catch (err) { + this._onError(null, 'could not close the connection', err); + } + } +} + +async function getAzureHeaders(client: Pick) { + if (client.apiKey !== '') { + return { 'api-key': client.apiKey }; + } else { + const token = await client._getAzureADToken(); + if (token) { + return { Authorization: `Bearer ${token}` }; + } else { + throw new Error('AzureOpenAI is not instantiated correctly. No API key or token provided.'); + } + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/core/README.md b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/core/README.md new file mode 100644 index 0000000000000000000000000000000000000000..485fce8617c9df053f0bed2dd56873df0371b0d0 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/core/README.md @@ -0,0 +1,3 @@ +# `core` + +This directory holds public modules implementing non-resource-specific SDK functionality. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/core/api-promise.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/core/api-promise.ts new file mode 100644 index 0000000000000000000000000000000000000000..9e6c756c817d2fd6ab9ea9e8a3fa30867298022e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/core/api-promise.ts @@ -0,0 +1,101 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { type OpenAI } from '../client'; + +import { type PromiseOrValue } from '../internal/types'; +import { + type APIResponseProps, + defaultParseResponse, + type WithRequestID, + addRequestID, +} from '../internal/parse'; + +/** + * A subclass of `Promise` providing additional helper methods + * for interacting with the SDK. + */ +export class APIPromise extends Promise> { + private parsedPromise: Promise> | undefined; + #client: OpenAI; + + constructor( + client: OpenAI, + private responsePromise: Promise, + private parseResponse: ( + client: OpenAI, + props: APIResponseProps, + ) => PromiseOrValue> = 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 as any); + }); + this.#client = client; + } + + _thenUnwrap(transform: (data: T, props: APIResponseProps) => U): APIPromise { + return new APIPromise(this.#client, 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(): Promise { + return this.responsePromise.then((p) => p.response); + } + + /** + * Gets the parsed response data, the raw `Response` instance and the ID of the request, + * returned via the X-Request-ID header which is useful for debugging requests and reporting + * issues to OpenAI. + * + * If you just want to get the raw `Response` instance without parsing it, + * you can use {@link asResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + async withResponse(): Promise<{ data: T; response: Response; request_id: string | null }> { + const [data, response] = await Promise.all([this.parse(), this.asResponse()]); + return { data, response, request_id: response.headers.get('x-request-id') }; + } + + private parse(): Promise> { + if (!this.parsedPromise) { + this.parsedPromise = this.responsePromise.then((data) => + this.parseResponse(this.#client, data), + ) as any as Promise>; + } + return this.parsedPromise; + } + + override then, TResult2 = never>( + onfulfilled?: ((value: WithRequestID) => TResult1 | PromiseLike) | undefined | null, + onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null, + ): Promise { + return this.parse().then(onfulfilled, onrejected); + } + + override catch( + onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null, + ): Promise | TResult> { + return this.parse().catch(onrejected); + } + + override finally(onfinally?: (() => void) | undefined | null): Promise> { + return this.parse().finally(onfinally); + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/core/error.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/core/error.ts new file mode 100644 index 0000000000000000000000000000000000000000..723a15dd1734a1a1de97ba87ffcdbea29252ee65 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/core/error.ts @@ -0,0 +1,160 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { castToError } from '../internal/errors'; + +export class OpenAIError extends Error {} + +export class APIError< + TStatus extends number | undefined = number | undefined, + THeaders extends Headers | undefined = Headers | undefined, + TError extends Object | undefined = Object | undefined, +> extends OpenAIError { + /** HTTP status for the response that caused the error */ + readonly status: TStatus; + /** HTTP headers for the response that caused the error */ + readonly headers: THeaders; + /** JSON body of the response that caused the error */ + readonly error: TError; + + readonly code: string | null | undefined; + readonly param: string | null | undefined; + readonly type: string | undefined; + + readonly requestID: string | null | undefined; + + constructor(status: TStatus, error: TError, message: string | undefined, headers: THeaders) { + super(`${APIError.makeMessage(status, error, message)}`); + this.status = status; + this.headers = headers; + this.requestID = headers?.get('x-request-id'); + this.error = error; + + const data = error as Record; + this.code = data?.['code']; + this.param = data?.['param']; + this.type = data?.['type']; + } + + private static makeMessage(status: number | undefined, error: any, message: string | undefined) { + 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: number | undefined, + errorResponse: Object | undefined, + message: string | undefined, + headers: Headers | undefined, + ): APIError { + if (!status || !headers) { + return new APIConnectionError({ message, cause: castToError(errorResponse) }); + } + + const error = (errorResponse as Record)?.['error']; + + if (status === 400) { + return new BadRequestError(status, error, message, headers); + } + + if (status === 401) { + return new AuthenticationError(status, error, message, headers); + } + + if (status === 403) { + return new PermissionDeniedError(status, error, message, headers); + } + + if (status === 404) { + return new NotFoundError(status, error, message, headers); + } + + if (status === 409) { + return new ConflictError(status, error, message, headers); + } + + if (status === 422) { + return new UnprocessableEntityError(status, error, message, headers); + } + + if (status === 429) { + return new RateLimitError(status, error, message, headers); + } + + if (status >= 500) { + return new InternalServerError(status, error, message, headers); + } + + return new APIError(status, error, message, headers); + } +} + +export class APIUserAbortError extends APIError { + constructor({ message }: { message?: string } = {}) { + super(undefined, undefined, message || 'Request was aborted.', undefined); + } +} + +export class APIConnectionError extends APIError { + constructor({ message, cause }: { message?: string | undefined; cause?: Error | undefined }) { + 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 }: { message?: string } = {}) { + super({ message: message ?? 'Request timed out.' }); + } +} + +export class BadRequestError extends APIError<400, Headers> {} + +export class AuthenticationError extends APIError<401, Headers> {} + +export class PermissionDeniedError extends APIError<403, Headers> {} + +export class NotFoundError extends APIError<404, Headers> {} + +export class ConflictError extends APIError<409, Headers> {} + +export class UnprocessableEntityError extends APIError<422, Headers> {} + +export class RateLimitError extends APIError<429, Headers> {} + +export class InternalServerError extends APIError {} + +export class LengthFinishReasonError extends OpenAIError { + constructor() { + super(`Could not parse response content as the length limit was reached`); + } +} + +export class ContentFilterFinishReasonError extends OpenAIError { + constructor() { + super(`Could not parse response content as the request was rejected by the content filter`); + } +} + +export class InvalidWebhookSignatureError extends Error { + constructor(message: string) { + super(message); + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/core/pagination.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/core/pagination.ts new file mode 100644 index 0000000000000000000000000000000000000000..9bef26447bd132891ff40d05962b7afd1e465194 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/core/pagination.ts @@ -0,0 +1,269 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { OpenAIError } from './error'; +import { FinalRequestOptions } from '../internal/request-options'; +import { defaultParseResponse, WithRequestID } from '../internal/parse'; +import { APIPromise } from './api-promise'; +import { type OpenAI } from '../client'; +import { type APIResponseProps } from '../internal/parse'; +import { maybeObj } from '../internal/utils/values'; + +export type PageRequestOptions = Pick; + +export abstract class AbstractPage implements AsyncIterable { + #client: OpenAI; + protected options: FinalRequestOptions; + + protected response: Response; + protected body: unknown; + + constructor(client: OpenAI, response: Response, body: unknown, options: FinalRequestOptions) { + this.#client = client; + this.options = options; + this.response = response; + this.body = body; + } + + abstract nextPageRequestOptions(): PageRequestOptions | null; + + abstract getPaginatedItems(): Item[]; + + hasNextPage(): boolean { + const items = this.getPaginatedItems(); + if (!items.length) return false; + return this.nextPageRequestOptions() != null; + } + + async getNextPage(): Promise { + const nextOptions = this.nextPageRequestOptions(); + if (!nextOptions) { + throw new OpenAIError( + 'No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.', + ); + } + + return await this.#client.requestAPIList(this.constructor as any, nextOptions); + } + + async *iterPages(): AsyncGenerator { + let page: this = this; + yield page; + while (page.hasNextPage()) { + page = await page.getNextPage(); + yield page; + } + } + + async *[Symbol.asyncIterator](): AsyncGenerator { + 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< + PageClass extends AbstractPage, + Item = ReturnType[number], + > + extends APIPromise + implements AsyncIterable +{ + constructor( + client: OpenAI, + request: Promise, + Page: new (...args: ConstructorParameters) => PageClass, + ) { + super( + client, + request, + async (client, props) => + new Page( + client, + props.response, + await defaultParseResponse(client, props), + props.options, + ) as WithRequestID, + ); + } + + /** + * Allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ + async *[Symbol.asyncIterator](): AsyncGenerator { + const page = await this; + for await (const item of page) { + yield item; + } + } +} + +export interface PageResponse { + data: Array; + + object: string; +} + +/** + * Note: no pagination actually occurs yet, this is for forwards-compatibility. + */ +export class Page extends AbstractPage implements PageResponse { + data: Array; + + object: string; + + constructor(client: OpenAI, response: Response, body: PageResponse, options: FinalRequestOptions) { + super(client, response, body, options); + + this.data = body.data || []; + this.object = body.object; + } + + getPaginatedItems(): Item[] { + return this.data ?? []; + } + + nextPageRequestOptions(): PageRequestOptions | null { + return null; + } +} + +export interface CursorPageResponse { + data: Array; + + has_more: boolean; +} + +export interface CursorPageParams { + after?: string; + + limit?: number; +} + +export class CursorPage + extends AbstractPage + implements CursorPageResponse +{ + data: Array; + + has_more: boolean; + + constructor( + client: OpenAI, + response: Response, + body: CursorPageResponse, + options: FinalRequestOptions, + ) { + super(client, response, body, options); + + this.data = body.data || []; + this.has_more = body.has_more || false; + } + + getPaginatedItems(): Item[] { + return this.data ?? []; + } + + override hasNextPage(): boolean { + if (this.has_more === false) { + return false; + } + + return super.hasNextPage(); + } + + nextPageRequestOptions(): PageRequestOptions | null { + const data = this.getPaginatedItems(); + const id = data[data.length - 1]?.id; + if (!id) { + return null; + } + + return { + ...this.options, + query: { + ...maybeObj(this.options.query), + after: id, + }, + }; + } +} + +export interface ConversationCursorPageResponse { + data: Array; + + has_more: boolean; + + last_id: string; +} + +export interface ConversationCursorPageParams { + after?: string; + + limit?: number; +} + +export class ConversationCursorPage + extends AbstractPage + implements ConversationCursorPageResponse +{ + data: Array; + + has_more: boolean; + + last_id: string; + + constructor( + client: OpenAI, + response: Response, + body: ConversationCursorPageResponse, + options: FinalRequestOptions, + ) { + super(client, response, body, options); + + this.data = body.data || []; + this.has_more = body.has_more || false; + this.last_id = body.last_id || ''; + } + + getPaginatedItems(): Item[] { + return this.data ?? []; + } + + override hasNextPage(): boolean { + if (this.has_more === false) { + return false; + } + + return super.hasNextPage(); + } + + nextPageRequestOptions(): PageRequestOptions | null { + const cursor = this.last_id; + if (!cursor) { + return null; + } + + return { + ...this.options, + query: { + ...maybeObj(this.options.query), + after: cursor, + }, + }; + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/core/resource.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/core/resource.ts new file mode 100644 index 0000000000000000000000000000000000000000..d9a191e58a23efeae8bd5858632de083f223f64b --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/core/resource.ts @@ -0,0 +1,11 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import type { OpenAI } from '../client'; + +export abstract class APIResource { + protected _client: OpenAI; + + constructor(client: OpenAI) { + this._client = client; + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/core/streaming.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/core/streaming.ts new file mode 100644 index 0000000000000000000000000000000000000000..efd85404622967e0f57fc76f43bae7c9108021bc --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/core/streaming.ts @@ -0,0 +1,348 @@ +import { OpenAIError } from './error'; +import { type ReadableStream } from '../internal/shim-types'; +import { makeReadableStream } from '../internal/shims'; +import { findDoubleNewlineIndex, LineDecoder } from '../internal/decoders/line'; +import { ReadableStreamToAsyncIterable } from '../internal/shims'; +import { isAbortError } from '../internal/errors'; +import { encodeUTF8 } from '../internal/utils/bytes'; +import { loggerFor } from '../internal/utils/log'; +import type { OpenAI } from '../client'; + +import { APIError } from './error'; + +type Bytes = string | ArrayBuffer | Uint8Array | null | undefined; + +export type ServerSentEvent = { + event: string | null; + data: string; + raw: string[]; +}; + +export class Stream implements AsyncIterable { + controller: AbortController; + #client: OpenAI | undefined; + + constructor( + private iterator: () => AsyncIterator, + controller: AbortController, + client?: OpenAI, + ) { + this.controller = controller; + this.#client = client; + } + + static fromSSEResponse( + response: Response, + controller: AbortController, + client?: OpenAI, + ): Stream { + let consumed = false; + const logger = client ? loggerFor(client) : console; + + async function* iterator(): AsyncIterator { + if (consumed) { + throw new OpenAIError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); + } + consumed = true; + let done = false; + try { + for await (const sse of _iterSSEMessages(response, controller)) { + if (done) continue; + + if (sse.data.startsWith('[DONE]')) { + done = true; + continue; + } + + if (sse.event === null || !sse.event.startsWith('thread.')) { + let data; + + try { + data = 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 (data && data.error) { + throw new APIError(undefined, data.error, undefined, response.headers); + } + + yield data; + } else { + let data; + try { + data = JSON.parse(sse.data); + } catch (e) { + console.error(`Could not parse message into JSON:`, sse.data); + console.error(`From chunk:`, sse.raw); + throw e; + } + // TODO: Is this where the error should be thrown? + if (sse.event == 'error') { + throw new APIError(undefined, data.error, data.message, undefined); + } + yield { event: sse.event, data: data } as any; + } + } + 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: ReadableStream, + controller: AbortController, + client?: OpenAI, + ): Stream { + let consumed = false; + + async function* iterLines(): AsyncGenerator { + 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(): AsyncIterator { + if (consumed) { + throw new OpenAIError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); + } + consumed = true; + let done = false; + try { + for await (const line of iterLines()) { + if (done) continue; + if (line) yield JSON.parse(line); + } + done = true; + } catch (e) { + // If the user calls `stream.controller.abort()`, we should exit without throwing. + if (isAbortError(e)) return; + throw e; + } finally { + // If the user `break`s, abort the ongoing request. + if (!done) controller.abort(); + } + } + + return new Stream(iterator, controller, client); + } + + [Symbol.asyncIterator](): AsyncIterator { + return this.iterator(); + } + + /** + * Splits the stream into two streams which can be + * independently read from at different speeds. + */ + tee(): [Stream, Stream] { + const left: Array>> = []; + const right: Array>> = []; + const iterator = this.iterator(); + + const teeIterator = (queue: Array>>): AsyncIterator => { + 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, this.#client), + new Stream(() => teeIterator(right), this.controller, this.#client), + ]; + } + + /** + * 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(): ReadableStream { + const self = this; + let iter: AsyncIterator; + + return makeReadableStream({ + async start() { + iter = self[Symbol.asyncIterator](); + }, + async pull(ctrl: any) { + 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: Response, + controller: AbortController, +): AsyncGenerator { + if (!response.body) { + controller.abort(); + if ( + typeof (globalThis as any).navigator !== 'undefined' && + (globalThis as any).navigator.product === 'ReactNative' + ) { + throw new OpenAIError( + `The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`, + ); + } + throw new OpenAIError(`Attempted to iterate over a response with no body`); + } + + const sseDecoder = new SSEDecoder(); + const lineDecoder = new LineDecoder(); + + const iter = ReadableStreamToAsyncIterable(response.body); + for await (const sseChunk of iterSSEChunks(iter)) { + for (const line of lineDecoder.decode(sseChunk)) { + const sse = sseDecoder.decode(line); + if (sse) yield sse; + } + } + + for (const line of lineDecoder.flush()) { + const sse = sseDecoder.decode(line); + if (sse) yield sse; + } +} + +/** + * Given an async iterable iterator, iterates over it and yields full + * SSE chunks, i.e. yields when a double new-line is encountered. + */ +async function* iterSSEChunks(iterator: AsyncIterableIterator): AsyncGenerator { + 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 { + private data: string[]; + private event: string | null; + private chunks: string[]; + + constructor() { + this.event = null; + this.data = []; + this.chunks = []; + } + + decode(line: string) { + 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: ServerSentEvent = { + 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: string, delimiter: string): [string, string, string] { + const index = str.indexOf(delimiter); + if (index !== -1) { + return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)]; + } + + return [str, '', '']; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/core/uploads.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/core/uploads.ts new file mode 100644 index 0000000000000000000000000000000000000000..2882ca6d18167e95dc8f204846ee798db6b131f1 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/core/uploads.ts @@ -0,0 +1,2 @@ +export { type Uploadable } from '../internal/uploads'; +export { toFile, type ToFileInput } from '../internal/to-file'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/helpers/audio.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/helpers/audio.ts new file mode 100644 index 0000000000000000000000000000000000000000..ecb6d74814bd3bc193c14ae117ce0e7922562f1a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/helpers/audio.ts @@ -0,0 +1,146 @@ +import { spawn } from 'node:child_process'; +import { Readable } from 'node:stream'; +import { platform, versions } from 'node:process'; +import { checkFileSupport } from '../internal/uploads'; + +const DEFAULT_SAMPLE_RATE = 24000; +const DEFAULT_CHANNELS = 1; + +const isNode = Boolean(versions?.node); + +const recordingProviders: Record = { + win32: 'dshow', + darwin: 'avfoundation', + linux: 'alsa', + aix: 'alsa', + android: 'alsa', + freebsd: 'alsa', + haiku: 'alsa', + sunos: 'alsa', + netbsd: 'alsa', + openbsd: 'alsa', + cygwin: 'dshow', +}; + +function isResponse(stream: NodeJS.ReadableStream | Response | File): stream is Response { + return typeof (stream as any).body !== 'undefined'; +} + +function isFile(stream: NodeJS.ReadableStream | Response | File): stream is File { + checkFileSupport(); + return stream instanceof File; +} + +async function nodejsPlayAudio(stream: NodeJS.ReadableStream | Response | File): Promise { + return new Promise((resolve, reject) => { + try { + const ffplay = spawn('ffplay', ['-autoexit', '-nodisp', '-i', 'pipe:0']); + + if (isResponse(stream)) { + (stream.body! as any).pipe(ffplay.stdin); + } else if (isFile(stream)) { + Readable.from(stream.stream()).pipe(ffplay.stdin); + } else { + stream.pipe(ffplay.stdin); + } + + ffplay.on('close', (code: number) => { + if (code !== 0) { + reject(new Error(`ffplay process exited with code ${code}`)); + } + resolve(); + }); + } catch (error) { + reject(error); + } + }); +} + +export async function playAudio(input: NodeJS.ReadableStream | Response | File): Promise { + if (isNode) { + return nodejsPlayAudio(input); + } + + throw new Error( + 'Play audio is not supported in the browser yet. Check out https://npm.im/wavtools as an alternative.', + ); +} + +type RecordAudioOptions = { + signal?: AbortSignal; + device?: number; + timeout?: number; +}; + +function nodejsRecordAudio({ signal, device, timeout }: RecordAudioOptions = {}): Promise { + checkFileSupport(); + return new Promise((resolve, reject) => { + const data: any[] = []; + const provider = recordingProviders[platform]; + try { + const ffmpeg = spawn( + 'ffmpeg', + [ + '-f', + provider, + '-i', + `:${device ?? 0}`, // default audio input device; adjust as needed + '-ar', + DEFAULT_SAMPLE_RATE.toString(), + '-ac', + DEFAULT_CHANNELS.toString(), + '-f', + 'wav', + 'pipe:1', + ], + { + stdio: ['ignore', 'pipe', 'pipe'], + }, + ); + + ffmpeg.stdout.on('data', (chunk) => { + data.push(chunk); + }); + + ffmpeg.on('error', (error) => { + console.error(error); + reject(error); + }); + + ffmpeg.on('close', (code) => { + returnData(); + }); + + function returnData() { + const audioBuffer = Buffer.concat(data); + const audioFile = new File([audioBuffer], 'audio.wav', { type: 'audio/wav' }); + resolve(audioFile); + } + + if (typeof timeout === 'number' && timeout > 0) { + const internalSignal = AbortSignal.timeout(timeout); + internalSignal.addEventListener('abort', () => { + ffmpeg.kill('SIGTERM'); + }); + } + + if (signal) { + signal.addEventListener('abort', () => { + ffmpeg.kill('SIGTERM'); + }); + } + } catch (error) { + reject(error); + } + }); +} + +export async function recordAudio(options: RecordAudioOptions = {}) { + if (isNode) { + return nodejsRecordAudio(options); + } + + throw new Error( + 'Record audio is not supported in the browser. Check out https://npm.im/wavtools as an alternative.', + ); +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/helpers/zod.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/helpers/zod.ts new file mode 100644 index 0000000000000000000000000000000000000000..d12e7f3caacaa541e2b274f988d03f214b5a048d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/helpers/zod.ts @@ -0,0 +1,154 @@ +import { ResponseFormatJSONSchema } from '../resources/index'; +import type { infer as zodInfer, ZodType } from 'zod'; +import { + AutoParseableResponseFormat, + AutoParseableTextFormat, + AutoParseableTool, + makeParseableResponseFormat, + makeParseableTextFormat, + makeParseableTool, +} from '../lib/parser'; +import { zodToJsonSchema as _zodToJsonSchema } from '../_vendor/zod-to-json-schema'; +import { AutoParseableResponseTool, makeParseableResponseTool } from '../lib/ResponsesParser'; +import { type ResponseFormatTextJSONSchemaConfig } from '../resources/responses/responses'; + +function zodToJsonSchema(schema: ZodType, options: { name: string }): Record { + return _zodToJsonSchema(schema, { + openaiStrictMode: true, + name: options.name, + nameStrategy: 'duplicate-ref', + $refStrategy: 'extract-to-root', + nullableStrategy: 'property', + }); +} + +/** + * Creates a chat completion `JSONSchema` response format object from + * the given Zod schema. + * + * If this is passed to the `.parse()`, `.stream()` or `.runTools()` + * chat completion methods then the response message will contain a + * `.parsed` property that is the result of parsing the content with + * the given Zod object. + * + * ```ts + * const completion = await client.chat.completions.parse({ + * model: 'gpt-4o-2024-08-06', + * messages: [ + * { role: 'system', content: 'You are a helpful math tutor.' }, + * { role: 'user', content: 'solve 8x + 31 = 2' }, + * ], + * response_format: zodResponseFormat( + * z.object({ + * steps: z.array(z.object({ + * explanation: z.string(), + * answer: z.string(), + * })), + * final_answer: z.string(), + * }), + * 'math_answer', + * ), + * }); + * const message = completion.choices[0]?.message; + * if (message?.parsed) { + * console.log(message.parsed); + * console.log(message.parsed.final_answer); + * } + * ``` + * + * This can be passed directly to the `.create()` method but will not + * result in any automatic parsing, you'll have to parse the response yourself. + */ +export function zodResponseFormat( + zodObject: ZodInput, + name: string, + props?: Omit, +): AutoParseableResponseFormat> { + return makeParseableResponseFormat( + { + type: 'json_schema', + json_schema: { + ...props, + name, + strict: true, + schema: zodToJsonSchema(zodObject, { name }), + }, + }, + (content) => zodObject.parse(JSON.parse(content)), + ); +} + +export function zodTextFormat( + zodObject: ZodInput, + name: string, + props?: Omit, +): AutoParseableTextFormat> { + return makeParseableTextFormat( + { + type: 'json_schema', + ...props, + name, + strict: true, + schema: zodToJsonSchema(zodObject, { name }), + }, + (content) => zodObject.parse(JSON.parse(content)), + ); +} + +/** + * Creates a chat completion `function` tool that can be invoked + * automatically by the chat completion `.runTools()` method or automatically + * parsed by `.parse()` / `.stream()`. + */ +export function zodFunction(options: { + name: string; + parameters: Parameters; + function?: ((args: zodInfer) => unknown | Promise) | undefined; + description?: string | undefined; +}): AutoParseableTool<{ + arguments: Parameters; + name: string; + function: (args: zodInfer) => unknown; +}> { + // @ts-expect-error TODO + return makeParseableTool( + { + type: 'function', + function: { + name: options.name, + parameters: zodToJsonSchema(options.parameters, { name: options.name }), + strict: true, + ...(options.description ? { description: options.description } : undefined), + }, + }, + { + callback: options.function, + parser: (args) => options.parameters.parse(JSON.parse(args)), + }, + ); +} + +export function zodResponsesFunction(options: { + name: string; + parameters: Parameters; + function?: ((args: zodInfer) => unknown | Promise) | undefined; + description?: string | undefined; +}): AutoParseableResponseTool<{ + arguments: Parameters; + name: string; + function: (args: zodInfer) => unknown; +}> { + return makeParseableResponseTool( + { + type: 'function', + name: options.name, + parameters: zodToJsonSchema(options.parameters, { name: options.name }), + strict: true, + ...(options.description ? { description: options.description } : undefined), + }, + { + callback: options.function, + parser: (args) => options.parameters.parse(JSON.parse(args)), + }, + ); +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/README.md b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3ef5a25bac10eec3925c29eacbfa68a84517c726 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/README.md @@ -0,0 +1,3 @@ +# `internal` + +The modules in this directory are not importable outside this package and will change between releases. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/builtin-types.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/builtin-types.ts new file mode 100644 index 0000000000000000000000000000000000000000..c23d3bdedc13683a2ad7defc1515539ae2f1b32e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/builtin-types.ts @@ -0,0 +1,93 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export type Fetch = (input: string | URL | Request, init?: RequestInit) => Promise; + +/** + * An alias to the builtin `RequestInit` type so we can + * easily alias it in import statements if there are name clashes. + * + * https://developer.mozilla.org/docs/Web/API/RequestInit + */ +type _RequestInit = RequestInit; + +/** + * An alias to the builtin `Response` type so we can + * easily alias it in import statements if there are name clashes. + * + * https://developer.mozilla.org/docs/Web/API/Response + */ +type _Response = Response; + +/** + * The type for the first argument to `fetch`. + * + * https://developer.mozilla.org/docs/Web/API/Window/fetch#resource + */ +type _RequestInfo = Request | URL | string; + +/** + * The type for constructing `RequestInit` Headers. + * + * https://developer.mozilla.org/docs/Web/API/RequestInit#setting_headers + */ +type _HeadersInit = RequestInit['headers']; + +/** + * The type for constructing `RequestInit` body. + * + * https://developer.mozilla.org/docs/Web/API/RequestInit#body + */ +type _BodyInit = RequestInit['body']; + +/** + * An alias to the builtin `Array` type so we can + * easily alias it in import statements if there are name clashes. + */ +type _Array = Array; + +/** + * An alias to the builtin `Record` type so we can + * easily alias it in import statements if there are name clashes. + */ +type _Record = Record; + +export type { + _Array as Array, + _BodyInit as BodyInit, + _HeadersInit as HeadersInit, + _Record as Record, + _RequestInfo as RequestInfo, + _RequestInit as RequestInit, + _Response as Response, +}; + +/** + * A copy of the builtin `EndingType` type as it isn't fully supported in certain + * environments and attempting to reference the global version will error. + * + * https://github.com/microsoft/TypeScript/blob/49ad1a3917a0ea57f5ff248159256e12bb1cb705/src/lib/dom.generated.d.ts#L27941 + */ +type EndingType = 'native' | 'transparent'; + +/** + * A copy of the builtin `BlobPropertyBag` type as it isn't fully supported in certain + * environments and attempting to reference the global version will error. + * + * https://github.com/microsoft/TypeScript/blob/49ad1a3917a0ea57f5ff248159256e12bb1cb705/src/lib/dom.generated.d.ts#L154 + * https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob#options + */ +export interface BlobPropertyBag { + endings?: EndingType; + type?: string; +} + +/** + * A copy of the builtin `FilePropertyBag` type as it isn't fully supported in certain + * environments and attempting to reference the global version will error. + * + * https://github.com/microsoft/TypeScript/blob/49ad1a3917a0ea57f5ff248159256e12bb1cb705/src/lib/dom.generated.d.ts#L503 + * https://developer.mozilla.org/en-US/docs/Web/API/File/File#options + */ +export interface FilePropertyBag extends BlobPropertyBag { + lastModified?: number; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/decoders/line.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/decoders/line.ts new file mode 100644 index 0000000000000000000000000000000000000000..b3bfa97cdfd4723a61c56281af4818dbeedafa22 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/decoders/line.ts @@ -0,0 +1,135 @@ +import { concatBytes, decodeUTF8, encodeUTF8 } from '../utils/bytes'; + +export type Bytes = string | ArrayBuffer | Uint8Array | null | undefined; + +/** + * 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 { + // prettier-ignore + static NEWLINE_CHARS = new Set(['\n', '\r']); + static NEWLINE_REGEXP = /\r\n|[\n\r]/g; + + #buffer: Uint8Array; + #carriageReturnIndex: number | null; + + constructor() { + this.#buffer = new Uint8Array(); + this.#carriageReturnIndex = null; + } + + decode(chunk: Bytes): string[] { + if (chunk == null) { + return []; + } + + const binaryChunk = + chunk instanceof ArrayBuffer ? new Uint8Array(chunk) + : typeof chunk === 'string' ? encodeUTF8(chunk) + : chunk; + + this.#buffer = concatBytes([this.#buffer, binaryChunk]); + + const lines: string[] = []; + let patternIndex; + while ((patternIndex = findNewlineIndex(this.#buffer, this.#carriageReturnIndex)) != null) { + if (patternIndex.carriage && this.#carriageReturnIndex == null) { + // skip until we either get a corresponding `\n`, a new `\r` or nothing + this.#carriageReturnIndex = patternIndex.index; + continue; + } + + // we got double \r or \rtext\n + if ( + this.#carriageReturnIndex != null && + (patternIndex.index !== this.#carriageReturnIndex + 1 || patternIndex.carriage) + ) { + lines.push(decodeUTF8(this.#buffer.subarray(0, this.#carriageReturnIndex - 1))); + this.#buffer = this.#buffer.subarray(this.#carriageReturnIndex); + this.#carriageReturnIndex = null; + continue; + } + + const endIndex = + this.#carriageReturnIndex !== null ? patternIndex.preceding - 1 : patternIndex.preceding; + + const line = decodeUTF8(this.#buffer.subarray(0, endIndex)); + lines.push(line); + + this.#buffer = this.#buffer.subarray(patternIndex.index); + this.#carriageReturnIndex = null; + } + + return lines; + } + + flush(): string[] { + if (!this.#buffer.length) { + return []; + } + return this.decode('\n'); + } +} + +/** + * 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: Uint8Array, + startIndex: number | null, +): { preceding: number; index: number; carriage: boolean } | null { + 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: Uint8Array): number { + // 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; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/detect-platform.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/detect-platform.ts new file mode 100644 index 0000000000000000000000000000000000000000..e82d95c92f05cdc6a167aea50becedff88116adc --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/detect-platform.ts @@ -0,0 +1,196 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { VERSION } from '../version'; + +export const isRunningInBrowser = () => { + return ( + // @ts-ignore + typeof window !== 'undefined' && + // @ts-ignore + typeof window.document !== 'undefined' && + // @ts-ignore + typeof navigator !== 'undefined' + ); +}; + +type DetectedPlatform = 'deno' | 'node' | 'edge' | 'unknown'; + +/** + * Note this does not detect 'browser'; for that, use getBrowserInfo(). + */ +function getDetectedPlatform(): DetectedPlatform { + if (typeof Deno !== 'undefined' && Deno.build != null) { + return 'deno'; + } + if (typeof EdgeRuntime !== 'undefined') { + return 'edge'; + } + if ( + Object.prototype.toString.call( + typeof (globalThis as any).process !== 'undefined' ? (globalThis as any).process : 0, + ) === '[object process]' + ) { + return 'node'; + } + return 'unknown'; +} + +declare const Deno: any; +declare const EdgeRuntime: any; +type Arch = 'x32' | 'x64' | 'arm' | 'arm64' | `other:${string}` | 'unknown'; +type PlatformName = + | 'MacOS' + | 'Linux' + | 'Windows' + | 'FreeBSD' + | 'OpenBSD' + | 'iOS' + | 'Android' + | `Other:${string}` + | 'Unknown'; +type Browser = 'ie' | 'edge' | 'chrome' | 'firefox' | 'safari'; +type PlatformProperties = { + 'X-Stainless-Lang': 'js'; + 'X-Stainless-Package-Version': string; + 'X-Stainless-OS': PlatformName; + 'X-Stainless-Arch': Arch; + 'X-Stainless-Runtime': 'node' | 'deno' | 'edge' | `browser:${Browser}` | 'unknown'; + 'X-Stainless-Runtime-Version': string; +}; +const getPlatformProperties = (): PlatformProperties => { + 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 as any).process.version, + }; + } + // Check if Node.js + if (detectedPlatform === 'node') { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': VERSION, + 'X-Stainless-OS': normalizePlatform((globalThis as any).process.platform ?? 'unknown'), + 'X-Stainless-Arch': normalizeArch((globalThis as any).process.arch ?? 'unknown'), + 'X-Stainless-Runtime': 'node', + 'X-Stainless-Runtime-Version': (globalThis as any).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', + }; +}; + +type BrowserInfo = { + browser: Browser; + version: string; +}; + +declare const navigator: { userAgent: string } | undefined; + +// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts +function getBrowserInfo(): BrowserInfo | null { + if (typeof navigator === 'undefined' || !navigator) { + return null; + } + + // NOTE: The order matters here! + const browserPatterns = [ + { key: 'edge' as const, pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'ie' as const, pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'ie' as const, pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'chrome' as const, pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'firefox' as const, pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'safari' as const, 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: string): 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: string): PlatformName => { + // 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: PlatformProperties; +export const getPlatformHeaders = () => { + return (_platformHeaders ??= getPlatformProperties()); +}; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/errors.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/errors.ts new file mode 100644 index 0000000000000000000000000000000000000000..82c7b14d577cccf53e1719ea34c11d47351c5a63 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/errors.ts @@ -0,0 +1,33 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export function isAbortError(err: unknown) { + return ( + typeof err === 'object' && + err !== null && + // Spec-compliant fetch implementations + (('name' in err && (err as any).name === 'AbortError') || + // Expo fetch + ('message' in err && String((err as any).message).includes('FetchRequestCanceledException'))) + ); +} + +export const castToError = (err: any): Error => { + 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); +}; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/headers.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/headers.ts new file mode 100644 index 0000000000000000000000000000000000000000..c724a9d22507fd04ddc290f78b9fb80754773621 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/headers.ts @@ -0,0 +1,97 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { isReadonlyArray } from './utils/values'; + +type HeaderValue = string | undefined | null; +export type HeadersLike = + | Headers + | readonly HeaderValue[][] + | Record + | undefined + | null + | NullableHeaders; + +const brand_privateNullableHeaders = /* @__PURE__ */ Symbol('brand.privateNullableHeaders'); + +/** + * @internal + * Users can pass explicit nulls to unset default headers. When we parse them + * into a standard headers type we need to preserve that information. + */ +export type NullableHeaders = { + /** Brand check, prevent users from creating a NullableHeaders. */ + [brand_privateNullableHeaders]: true; + /** Parsed headers. */ + values: Headers; + /** Set of lowercase header names explicitly set to null. */ + nulls: Set; +}; + +function* iterateHeaders(headers: HeadersLike): IterableIterator { + 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: Iterable; + 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: HeadersLike[]): NullableHeaders => { + 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: HeadersLike) => { + for (const _ of iterateHeaders(headers)) return false; + return true; +}; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/parse.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/parse.ts new file mode 100644 index 0000000000000000000000000000000000000000..dbda173113c6447ef1c87342a849e22aaf22960c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/parse.ts @@ -0,0 +1,84 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import type { FinalRequestOptions } from './request-options'; +import { Stream } from '../core/streaming'; +import { type OpenAI } from '../client'; +import { formatRequestDetails, loggerFor } from './utils/log'; +import type { AbstractPage } from '../pagination'; + +export type APIResponseProps = { + response: Response; + options: FinalRequestOptions; + controller: AbortController; + requestLogID: string; + retryOfRequestLogID: string | undefined; + startTime: number; +}; + +export async function defaultParseResponse( + client: OpenAI, + props: APIResponseProps, +): Promise> { + 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, client) as any; + } + + return Stream.fromSSEResponse(response, props.controller, client) as any; + } + + // fetch refuses to read the body when the status code is 204. + if (response.status === 204) { + return null as T; + } + + if (props.options.__binaryResponse) { + return response as unknown as T; + } + + const contentType = response.headers.get('content-type'); + const mediaType = contentType?.split(';')[0]?.trim(); + const isJSON = mediaType?.includes('application/json') || mediaType?.endsWith('+json'); + if (isJSON) { + const json = await response.json(); + return addRequestID(json as T, response); + } + + const text = await response.text(); + return text as unknown as T; + })(); + loggerFor(client).debug( + `[${requestLogID}] response parsed`, + formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + body, + durationMs: Date.now() - startTime, + }), + ); + return body; +} + +export type WithRequestID = + T extends Array | Response | AbstractPage ? T + : T extends Record ? T & { _request_id?: string | null } + : T; + +export function addRequestID(value: T, response: Response): WithRequestID { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + return value as WithRequestID; + } + + return Object.defineProperty(value, '_request_id', { + value: response.headers.get('x-request-id'), + enumerable: false, + }) as WithRequestID; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/qs/LICENSE.md b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/qs/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..3fda1573bb074f9a510f8864a4dfe84499dc79a1 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/qs/LICENSE.md @@ -0,0 +1,13 @@ +BSD 3-Clause License + +Copyright (c) 2014, Nathan LaFreniere and other [contributors](https://github.com/puruvj/neoqs/graphs/contributors) All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/qs/README.md b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/qs/README.md new file mode 100644 index 0000000000000000000000000000000000000000..67ae04ecd52f7839c7a02a4a01b7ba239e62a545 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/qs/README.md @@ -0,0 +1,3 @@ +# qs + +This is a vendored version of [neoqs](https://github.com/PuruVJ/neoqs) which is a TypeScript rewrite of [qs](https://github.com/ljharb/qs), a query string library. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/qs/formats.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/qs/formats.ts new file mode 100644 index 0000000000000000000000000000000000000000..e76a742f3823339e0d90cbd785afb9141d57968c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/qs/formats.ts @@ -0,0 +1,10 @@ +import type { Format } from './types'; + +export const default_format: Format = 'RFC3986'; +export const default_formatter = (v: PropertyKey) => String(v); +export const formatters: Record string> = { + RFC1738: (v: PropertyKey) => String(v).replace(/%20/g, '+'), + RFC3986: default_formatter, +}; +export const RFC1738 = 'RFC1738'; +export const RFC3986 = 'RFC3986'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/qs/index.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/qs/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..c3a3620d01fb152d8d5a1a45a793aa1f60c01030 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/qs/index.ts @@ -0,0 +1,13 @@ +import { default_format, formatters, RFC1738, RFC3986 } from './formats'; + +const formats = { + formatters, + RFC1738, + RFC3986, + default: default_format, +}; + +export { stringify } from './stringify'; +export { formats }; + +export type { DefaultDecoder, DefaultEncoder, Format, ParseOptions, StringifyOptions } from './types'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/qs/stringify.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/qs/stringify.ts new file mode 100644 index 0000000000000000000000000000000000000000..7e71387f5fcdc47d20de9ec1b32abd376f7733f8 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/qs/stringify.ts @@ -0,0 +1,385 @@ +import { encode, is_buffer, maybe_map, has } from './utils'; +import { default_format, default_formatter, formatters } from './formats'; +import type { NonNullableProperties, StringifyOptions } from './types'; +import { isArray } from '../utils/values'; + +const array_prefix_generators = { + brackets(prefix: PropertyKey) { + return String(prefix) + '[]'; + }, + comma: 'comma', + indices(prefix: PropertyKey, key: string) { + return String(prefix) + '[' + key + ']'; + }, + repeat(prefix: PropertyKey) { + return String(prefix); + }, +}; + +const push_to_array = function (arr: any[], value_or_array: any) { + Array.prototype.push.apply(arr, isArray(value_or_array) ? value_or_array : [value_or_array]); +}; + +let toISOString; + +const defaults = { + addQueryPrefix: false, + allowDots: false, + allowEmptyArrays: false, + arrayFormat: 'indices', + charset: 'utf-8', + charsetSentinel: false, + delimiter: '&', + encode: true, + encodeDotInKeys: false, + encoder: encode, + encodeValuesOnly: false, + format: default_format, + formatter: default_formatter, + /** @deprecated */ + indices: false, + serializeDate(date) { + return (toISOString ??= Function.prototype.call.bind(Date.prototype.toISOString))(date); + }, + skipNulls: false, + strictNullHandling: false, +} as NonNullableProperties; + +function is_non_nullish_primitive(v: unknown): v is string | number | boolean | symbol | bigint { + return ( + typeof v === 'string' || + typeof v === 'number' || + typeof v === 'boolean' || + typeof v === 'symbol' || + typeof v === 'bigint' + ); +} + +const sentinel = {}; + +function inner_stringify( + object: any, + prefix: PropertyKey, + generateArrayPrefix: StringifyOptions['arrayFormat'] | ((prefix: string, key: string) => string), + commaRoundTrip: boolean, + allowEmptyArrays: boolean, + strictNullHandling: boolean, + skipNulls: boolean, + encodeDotInKeys: boolean, + encoder: StringifyOptions['encoder'], + filter: StringifyOptions['filter'], + sort: StringifyOptions['sort'], + allowDots: StringifyOptions['allowDots'], + serializeDate: StringifyOptions['serializeDate'], + format: StringifyOptions['format'], + formatter: StringifyOptions['formatter'], + encodeValuesOnly: boolean, + charset: StringifyOptions['charset'], + sideChannel: WeakMap, +) { + let obj = object; + + let tmp_sc = sideChannel; + let step = 0; + let find_flag = false; + while ((tmp_sc = tmp_sc.get(sentinel)) !== void undefined && !find_flag) { + // Where object last appeared in the ref tree + const pos = tmp_sc.get(object); + step += 1; + if (typeof pos !== 'undefined') { + if (pos === step) { + throw new RangeError('Cyclic object value'); + } else { + find_flag = true; // Break while + } + } + if (typeof tmp_sc.get(sentinel) === 'undefined') { + step = 0; + } + } + + if (typeof filter === 'function') { + obj = filter(prefix, obj); + } else if (obj instanceof Date) { + obj = serializeDate?.(obj); + } else if (generateArrayPrefix === 'comma' && isArray(obj)) { + obj = maybe_map(obj, function (value) { + if (value instanceof Date) { + return serializeDate?.(value); + } + return value; + }); + } + + if (obj === null) { + if (strictNullHandling) { + return encoder && !encodeValuesOnly ? + // @ts-expect-error + encoder(prefix, defaults.encoder, charset, 'key', format) + : prefix; + } + + obj = ''; + } + + if (is_non_nullish_primitive(obj) || is_buffer(obj)) { + if (encoder) { + const key_value = + encodeValuesOnly ? prefix + // @ts-expect-error + : encoder(prefix, defaults.encoder, charset, 'key', format); + return [ + formatter?.(key_value) + + '=' + + // @ts-expect-error + formatter?.(encoder(obj, defaults.encoder, charset, 'value', format)), + ]; + } + return [formatter?.(prefix) + '=' + formatter?.(String(obj))]; + } + + const values: string[] = []; + + if (typeof obj === 'undefined') { + return values; + } + + let obj_keys; + if (generateArrayPrefix === 'comma' && isArray(obj)) { + // we need to join elements in + if (encodeValuesOnly && encoder) { + // @ts-expect-error values only + obj = maybe_map(obj, encoder); + } + obj_keys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }]; + } else if (isArray(filter)) { + obj_keys = filter; + } else { + const keys = Object.keys(obj); + obj_keys = sort ? keys.sort(sort) : keys; + } + + const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, '%2E') : String(prefix); + + const adjusted_prefix = + commaRoundTrip && isArray(obj) && obj.length === 1 ? encoded_prefix + '[]' : encoded_prefix; + + if (allowEmptyArrays && isArray(obj) && obj.length === 0) { + return adjusted_prefix + '[]'; + } + + for (let j = 0; j < obj_keys.length; ++j) { + const key = obj_keys[j]; + const value = + // @ts-ignore + typeof key === 'object' && typeof key.value !== 'undefined' ? key.value : obj[key as any]; + + if (skipNulls && value === null) { + continue; + } + + // @ts-ignore + const encoded_key = allowDots && encodeDotInKeys ? (key as any).replace(/\./g, '%2E') : key; + const key_prefix = + isArray(obj) ? + typeof generateArrayPrefix === 'function' ? + generateArrayPrefix(adjusted_prefix, encoded_key) + : adjusted_prefix + : adjusted_prefix + (allowDots ? '.' + encoded_key : '[' + encoded_key + ']'); + + sideChannel.set(object, step); + const valueSideChannel = new WeakMap(); + valueSideChannel.set(sentinel, sideChannel); + push_to_array( + values, + inner_stringify( + value, + key_prefix, + generateArrayPrefix, + commaRoundTrip, + allowEmptyArrays, + strictNullHandling, + skipNulls, + encodeDotInKeys, + // @ts-ignore + generateArrayPrefix === 'comma' && encodeValuesOnly && isArray(obj) ? null : encoder, + filter, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + valueSideChannel, + ), + ); + } + + return values; +} + +function normalize_stringify_options( + opts: StringifyOptions = defaults, +): NonNullableProperties> & { indices?: boolean } { + if (typeof opts.allowEmptyArrays !== 'undefined' && typeof opts.allowEmptyArrays !== 'boolean') { + throw new TypeError('`allowEmptyArrays` option can only be `true` or `false`, when provided'); + } + + if (typeof opts.encodeDotInKeys !== 'undefined' && typeof opts.encodeDotInKeys !== 'boolean') { + throw new TypeError('`encodeDotInKeys` option can only be `true` or `false`, when provided'); + } + + if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') { + throw new TypeError('Encoder has to be a function.'); + } + + const charset = opts.charset || defaults.charset; + if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { + throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); + } + + let format = default_format; + if (typeof opts.format !== 'undefined') { + if (!has(formatters, opts.format)) { + throw new TypeError('Unknown format option provided.'); + } + format = opts.format; + } + const formatter = formatters[format]; + + let filter = defaults.filter; + if (typeof opts.filter === 'function' || isArray(opts.filter)) { + filter = opts.filter; + } + + let arrayFormat: StringifyOptions['arrayFormat']; + if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators) { + arrayFormat = opts.arrayFormat; + } else if ('indices' in opts) { + arrayFormat = opts.indices ? 'indices' : 'repeat'; + } else { + arrayFormat = defaults.arrayFormat; + } + + if ('commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') { + throw new TypeError('`commaRoundTrip` must be a boolean, or absent'); + } + + const allowDots = + typeof opts.allowDots === 'undefined' ? + !!opts.encodeDotInKeys === true ? + true + : defaults.allowDots + : !!opts.allowDots; + + return { + addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix, + // @ts-ignore + allowDots: allowDots, + allowEmptyArrays: + typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, + arrayFormat: arrayFormat, + charset: charset, + charsetSentinel: + typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, + commaRoundTrip: !!opts.commaRoundTrip, + delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter, + encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode, + encodeDotInKeys: + typeof opts.encodeDotInKeys === 'boolean' ? opts.encodeDotInKeys : defaults.encodeDotInKeys, + encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder, + encodeValuesOnly: + typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly, + filter: filter, + format: format, + formatter: formatter, + serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate, + skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls, + // @ts-ignore + sort: typeof opts.sort === 'function' ? opts.sort : null, + strictNullHandling: + typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling, + }; +} + +export function stringify(object: any, opts: StringifyOptions = {}) { + let obj = object; + const options = normalize_stringify_options(opts); + + let obj_keys: PropertyKey[] | undefined; + let filter; + + if (typeof options.filter === 'function') { + filter = options.filter; + obj = filter('', obj); + } else if (isArray(options.filter)) { + filter = options.filter; + obj_keys = filter; + } + + const keys: string[] = []; + + if (typeof obj !== 'object' || obj === null) { + return ''; + } + + const generateArrayPrefix = array_prefix_generators[options.arrayFormat]; + const commaRoundTrip = generateArrayPrefix === 'comma' && options.commaRoundTrip; + + if (!obj_keys) { + obj_keys = Object.keys(obj); + } + + if (options.sort) { + obj_keys.sort(options.sort); + } + + const sideChannel = new WeakMap(); + for (let i = 0; i < obj_keys.length; ++i) { + const key = obj_keys[i]!; + + if (options.skipNulls && obj[key] === null) { + continue; + } + push_to_array( + keys, + inner_stringify( + obj[key], + key, + // @ts-expect-error + generateArrayPrefix, + commaRoundTrip, + options.allowEmptyArrays, + options.strictNullHandling, + options.skipNulls, + options.encodeDotInKeys, + options.encode ? options.encoder : null, + options.filter, + options.sort, + options.allowDots, + options.serializeDate, + options.format, + options.formatter, + options.encodeValuesOnly, + options.charset, + sideChannel, + ), + ); + } + + const joined = keys.join(options.delimiter); + let prefix = options.addQueryPrefix === true ? '?' : ''; + + if (options.charsetSentinel) { + if (options.charset === 'iso-8859-1') { + // encodeURIComponent('✓'), the "numeric entity" representation of a checkmark + prefix += 'utf8=%26%2310003%3B&'; + } else { + // encodeURIComponent('✓') + prefix += 'utf8=%E2%9C%93&'; + } + } + + return joined.length > 0 ? prefix + joined : ''; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/qs/types.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/qs/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..7c28dbb46f16e1383d96eb52094aac65e02f9a33 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/qs/types.ts @@ -0,0 +1,71 @@ +export type Format = 'RFC1738' | 'RFC3986'; + +export type DefaultEncoder = (str: any, defaultEncoder?: any, charset?: string) => string; +export type DefaultDecoder = (str: string, decoder?: any, charset?: string) => string; + +export type BooleanOptional = boolean | undefined; + +export type StringifyBaseOptions = { + delimiter?: string; + allowDots?: boolean; + encodeDotInKeys?: boolean; + strictNullHandling?: boolean; + skipNulls?: boolean; + encode?: boolean; + encoder?: ( + str: any, + defaultEncoder: DefaultEncoder, + charset: string, + type: 'key' | 'value', + format?: Format, + ) => string; + filter?: Array | ((prefix: PropertyKey, value: any) => any); + arrayFormat?: 'indices' | 'brackets' | 'repeat' | 'comma'; + indices?: boolean; + sort?: ((a: PropertyKey, b: PropertyKey) => number) | null; + serializeDate?: (d: Date) => string; + format?: 'RFC1738' | 'RFC3986'; + formatter?: (str: PropertyKey) => string; + encodeValuesOnly?: boolean; + addQueryPrefix?: boolean; + charset?: 'utf-8' | 'iso-8859-1'; + charsetSentinel?: boolean; + allowEmptyArrays?: boolean; + commaRoundTrip?: boolean; +}; + +export type StringifyOptions = StringifyBaseOptions; + +export type ParseBaseOptions = { + comma?: boolean; + delimiter?: string | RegExp; + depth?: number | false; + decoder?: (str: string, defaultDecoder: DefaultDecoder, charset: string, type: 'key' | 'value') => any; + arrayLimit?: number; + parseArrays?: boolean; + plainObjects?: boolean; + allowPrototypes?: boolean; + allowSparse?: boolean; + parameterLimit?: number; + strictDepth?: boolean; + strictNullHandling?: boolean; + ignoreQueryPrefix?: boolean; + charset?: 'utf-8' | 'iso-8859-1'; + charsetSentinel?: boolean; + interpretNumericEntities?: boolean; + allowEmptyArrays?: boolean; + duplicates?: 'combine' | 'first' | 'last'; + allowDots?: boolean; + decodeDotInKeys?: boolean; +}; + +export type ParseOptions = ParseBaseOptions; + +export type ParsedQs = { + [key: string]: undefined | string | string[] | ParsedQs | ParsedQs[]; +}; + +// Type to remove null or undefined union from each property +export type NonNullableProperties = { + [K in keyof T]-?: Exclude; +}; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/qs/utils.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/qs/utils.ts new file mode 100644 index 0000000000000000000000000000000000000000..4cd56579c9bb117576b7cf854b6a635b98e9af23 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/qs/utils.ts @@ -0,0 +1,265 @@ +import { RFC1738 } from './formats'; +import type { DefaultEncoder, Format } from './types'; +import { isArray } from '../utils/values'; + +export let has = (obj: object, key: PropertyKey): boolean => ( + (has = (Object as any).hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty)), + has(obj, key) +); + +const hex_table = /* @__PURE__ */ (() => { + const array = []; + for (let i = 0; i < 256; ++i) { + array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); + } + + return array; +})(); + +function compact_queue>(queue: Array<{ obj: T; prop: string }>) { + while (queue.length > 1) { + const item = queue.pop(); + if (!item) continue; + + const obj = item.obj[item.prop]; + + if (isArray(obj)) { + const compacted: unknown[] = []; + + for (let j = 0; j < obj.length; ++j) { + if (typeof obj[j] !== 'undefined') { + compacted.push(obj[j]); + } + } + + // @ts-ignore + item.obj[item.prop] = compacted; + } + } +} + +function array_to_object(source: any[], options: { plainObjects: boolean }) { + const obj = options && options.plainObjects ? Object.create(null) : {}; + for (let i = 0; i < source.length; ++i) { + if (typeof source[i] !== 'undefined') { + obj[i] = source[i]; + } + } + + return obj; +} + +export function merge( + target: any, + source: any, + options: { plainObjects?: boolean; allowPrototypes?: boolean } = {}, +) { + if (!source) { + return target; + } + + if (typeof source !== 'object') { + if (isArray(target)) { + target.push(source); + } else if (target && typeof target === 'object') { + if ((options && (options.plainObjects || options.allowPrototypes)) || !has(Object.prototype, source)) { + target[source] = true; + } + } else { + return [target, source]; + } + + return target; + } + + if (!target || typeof target !== 'object') { + return [target].concat(source); + } + + let mergeTarget = target; + if (isArray(target) && !isArray(source)) { + // @ts-ignore + mergeTarget = array_to_object(target, options); + } + + if (isArray(target) && isArray(source)) { + source.forEach(function (item, i) { + if (has(target, i)) { + const targetItem = target[i]; + if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { + target[i] = merge(targetItem, item, options); + } else { + target.push(item); + } + } else { + target[i] = item; + } + }); + return target; + } + + return Object.keys(source).reduce(function (acc, key) { + const value = source[key]; + + if (has(acc, key)) { + acc[key] = merge(acc[key], value, options); + } else { + acc[key] = value; + } + return acc; + }, mergeTarget); +} + +export function assign_single_source(target: any, source: any) { + return Object.keys(source).reduce(function (acc, key) { + acc[key] = source[key]; + return acc; + }, target); +} + +export function decode(str: string, _: any, charset: string) { + const strWithoutPlus = str.replace(/\+/g, ' '); + if (charset === 'iso-8859-1') { + // unescape never throws, no try...catch needed: + return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); + } + // utf-8 + try { + return decodeURIComponent(strWithoutPlus); + } catch (e) { + return strWithoutPlus; + } +} + +const limit = 1024; + +export const encode: ( + str: any, + defaultEncoder: DefaultEncoder, + charset: string, + type: 'key' | 'value', + format: Format, +) => string = (str, _defaultEncoder, charset, _kind, format: Format) => { + // This code was originally written by Brian White for the io.js core querystring library. + // It has been adapted here for stricter adherence to RFC 3986 + if (str.length === 0) { + return str; + } + + let string = str; + if (typeof str === 'symbol') { + string = Symbol.prototype.toString.call(str); + } else if (typeof str !== 'string') { + string = String(str); + } + + if (charset === 'iso-8859-1') { + return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) { + return '%26%23' + parseInt($0.slice(2), 16) + '%3B'; + }); + } + + let out = ''; + for (let j = 0; j < string.length; j += limit) { + const segment = string.length >= limit ? string.slice(j, j + limit) : string; + const arr = []; + + for (let i = 0; i < segment.length; ++i) { + let c = segment.charCodeAt(i); + if ( + c === 0x2d || // - + c === 0x2e || // . + c === 0x5f || // _ + c === 0x7e || // ~ + (c >= 0x30 && c <= 0x39) || // 0-9 + (c >= 0x41 && c <= 0x5a) || // a-z + (c >= 0x61 && c <= 0x7a) || // A-Z + (format === RFC1738 && (c === 0x28 || c === 0x29)) // ( ) + ) { + arr[arr.length] = segment.charAt(i); + continue; + } + + if (c < 0x80) { + arr[arr.length] = hex_table[c]; + continue; + } + + if (c < 0x800) { + arr[arr.length] = hex_table[0xc0 | (c >> 6)]! + hex_table[0x80 | (c & 0x3f)]; + continue; + } + + if (c < 0xd800 || c >= 0xe000) { + arr[arr.length] = + hex_table[0xe0 | (c >> 12)]! + hex_table[0x80 | ((c >> 6) & 0x3f)] + hex_table[0x80 | (c & 0x3f)]; + continue; + } + + i += 1; + c = 0x10000 + (((c & 0x3ff) << 10) | (segment.charCodeAt(i) & 0x3ff)); + + arr[arr.length] = + hex_table[0xf0 | (c >> 18)]! + + hex_table[0x80 | ((c >> 12) & 0x3f)] + + hex_table[0x80 | ((c >> 6) & 0x3f)] + + hex_table[0x80 | (c & 0x3f)]; + } + + out += arr.join(''); + } + + return out; +}; + +export function compact(value: any) { + const queue = [{ obj: { o: value }, prop: 'o' }]; + const refs = []; + + for (let i = 0; i < queue.length; ++i) { + const item = queue[i]; + // @ts-ignore + const obj = item.obj[item.prop]; + + const keys = Object.keys(obj); + for (let j = 0; j < keys.length; ++j) { + const key = keys[j]!; + const val = obj[key]; + if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { + queue.push({ obj: obj, prop: key }); + refs.push(val); + } + } + } + + compact_queue(queue); + + return value; +} + +export function is_regexp(obj: any) { + return Object.prototype.toString.call(obj) === '[object RegExp]'; +} + +export function is_buffer(obj: any) { + if (!obj || typeof obj !== 'object') { + return false; + } + + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); +} + +export function combine(a: any, b: any) { + return [].concat(a, b); +} + +export function maybe_map(val: T[], fn: (v: T) => T) { + if (isArray(val)) { + const mapped = []; + for (let i = 0; i < val.length; i += 1) { + mapped.push(fn(val[i]!)); + } + return mapped; + } + return fn(val); +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/request-options.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/request-options.ts new file mode 100644 index 0000000000000000000000000000000000000000..3a0c3d87907d9eaa1d458841ffc1203b925de7a4 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/request-options.ts @@ -0,0 +1,94 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { NullableHeaders } from './headers'; + +import type { BodyInit } from './builtin-types'; +import { Stream } from '../core/streaming'; +import type { HTTPMethod, MergedRequestInit } from './types'; +import { type HeadersLike } from './headers'; + +export type FinalRequestOptions = RequestOptions & { method: HTTPMethod; path: string }; + +export type RequestOptions = { + /** + * The HTTP method for the request (e.g., 'get', 'post', 'put', 'delete'). + */ + method?: HTTPMethod; + + /** + * The URL path for the request. + * + * @example "/v1/foo" + */ + path?: string; + + /** + * Query parameters to include in the request URL. + */ + query?: object | undefined | null; + + /** + * The request body. Can be a string, JSON object, FormData, or other supported types. + */ + body?: unknown; + + /** + * HTTP headers to include with the request. Can be a Headers object, plain object, or array of tuples. + */ + headers?: HeadersLike; + + /** + * The maximum number of times that the client will retry a request in case of a + * temporary failure, like a network error or a 5XX error from the server. + * + * @default 2 + */ + maxRetries?: number; + + stream?: boolean | undefined; + + /** + * The maximum amount of time (in milliseconds) that the client should wait for a response + * from the server before timing out a single request. + * + * @unit milliseconds + */ + timeout?: number; + + /** + * Additional `RequestInit` options to be passed to the underlying `fetch` call. + * These options will be merged with the client's default fetch options. + */ + fetchOptions?: MergedRequestInit; + + /** + * An AbortSignal that can be used to cancel the request. + */ + signal?: AbortSignal | undefined | null; + + /** + * A unique key for this request to enable idempotency. + */ + idempotencyKey?: string; + + /** + * Override the default base URL for this specific request. + */ + defaultBaseURL?: string | undefined; + + __metadata?: Record; + __binaryResponse?: boolean | undefined; + __streamClass?: typeof Stream; +}; + +export type EncodedContent = { bodyHeaders: HeadersLike; body: BodyInit }; +export type RequestEncoder = (request: { headers: NullableHeaders; body: unknown }) => EncodedContent; + +export const FallbackEncoder: RequestEncoder = ({ headers, body }) => { + return { + bodyHeaders: { + 'content-type': 'application/json', + }, + body: JSON.stringify(body), + }; +}; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/shim-types.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/shim-types.ts new file mode 100644 index 0000000000000000000000000000000000000000..8ddf7b0ad14b80bc73317cf34beae74991f906bb --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/shim-types.ts @@ -0,0 +1,26 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +/** + * Shims for types that we can't always rely on being available globally. + * + * Note: these only exist at the type-level, there is no corresponding runtime + * version for any of these symbols. + */ + +type NeverToAny = T extends never ? any : T; + +/** @ts-ignore */ +type _DOMReadableStream = globalThis.ReadableStream; + +/** @ts-ignore */ +type _NodeReadableStream = import('stream/web').ReadableStream; + +type _ConditionalNodeReadableStream = + typeof globalThis extends { ReadableStream: any } ? never : _NodeReadableStream; + +type _ReadableStream = NeverToAny< + | ([0] extends [1 & _DOMReadableStream] ? never : _DOMReadableStream) + | ([0] extends [1 & _ConditionalNodeReadableStream] ? never : _ConditionalNodeReadableStream) +>; + +export type { _ReadableStream as ReadableStream }; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/shims.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/shims.ts new file mode 100644 index 0000000000000000000000000000000000000000..588ce43ab5bed3b66fcbffa098a5c275e85b4011 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/shims.ts @@ -0,0 +1,107 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +/** + * This module provides internal shims and utility functions for environments where certain Node.js or global types may not be available. + * + * These are used to ensure we can provide a consistent behaviour between different JavaScript environments and good error + * messages in cases where an environment isn't fully supported. + */ + +import type { Fetch } from './builtin-types'; +import type { ReadableStream } from './shim-types'; + +export function getDefaultFetch(): Fetch { + if (typeof fetch !== 'undefined') { + return fetch as any; + } + + throw new Error( + '`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`', + ); +} + +type ReadableStreamArgs = ConstructorParameters; + +export function makeReadableStream(...args: ReadableStreamArgs): ReadableStream { + const ReadableStream = (globalThis as any).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: Iterable | AsyncIterable): ReadableStream { + let iter: AsyncIterator | Iterator = + Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); + + return makeReadableStream({ + start() {}, + async pull(controller: any) { + 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: any): AsyncIterableIterator { + 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: any): Promise { + 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; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/stream-utils.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/stream-utils.ts new file mode 100644 index 0000000000000000000000000000000000000000..37f7793cffc8d65cc02ce1750f600e676ced481f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/stream-utils.ts @@ -0,0 +1,32 @@ +/** + * 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: any): AsyncIterableIterator { + 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; + }, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/to-file.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/to-file.ts new file mode 100644 index 0000000000000000000000000000000000000000..245e84933c554ff5f2bf24c5f83fa28a6a2db5e1 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/to-file.ts @@ -0,0 +1,154 @@ +import { BlobPart, getName, makeFile, isAsyncIterable } from './uploads'; +import type { FilePropertyBag } from './builtin-types'; +import { checkFileSupport } from './uploads'; + +type BlobLikePart = string | ArrayBuffer | ArrayBufferView | BlobLike | DataView; + +/** + * Intended to match DOM Blob, node-fetch Blob, node:buffer Blob, etc. + * Don't add arrayBuffer here, node-fetch doesn't have it + */ +interface BlobLike { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */ + readonly size: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */ + readonly type: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */ + text(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */ + slice(start?: number, end?: number): BlobLike; +} + +/** + * This check adds the arrayBuffer() method type because it is available and used at runtime + */ +const isBlobLike = (value: any): value is BlobLike & { arrayBuffer(): Promise } => + 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'; + +/** + * Intended to match DOM File, node:buffer File, undici File, etc. + */ +interface FileLike extends BlobLike { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */ + readonly lastModified: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */ + readonly name?: string | undefined; +} + +/** + * This check adds the arrayBuffer() method type because it is available and used at runtime + */ +const isFileLike = (value: any): value is FileLike & { arrayBuffer(): Promise } => + value != null && + typeof value === 'object' && + typeof value.name === 'string' && + typeof value.lastModified === 'number' && + isBlobLike(value); + +/** + * Intended to match DOM Response, node-fetch Response, undici Response, etc. + */ +export interface ResponseLike { + url: string; + blob(): Promise; +} + +const isResponseLike = (value: any): value is ResponseLike => + value != null && + typeof value === 'object' && + typeof value.url === 'string' && + typeof value.blob === 'function'; + +export type ToFileInput = + | FileLike + | ResponseLike + | Exclude + | AsyncIterable; + +/** + * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats + * @param value the raw content of the file. Can be an {@link Uploadable}, {@link BlobLikePart}, or {@link AsyncIterable} of {@link BlobLikePart}s + * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible + * @param {Object=} options additional properties + * @param {string=} options.type the MIME type of the content + * @param {number=} options.lastModified the last modified timestamp + * @returns a {@link File} with the given properties + */ +export async function toFile( + value: ToFileInput | PromiseLike, + name?: string | null | undefined, + options?: FilePropertyBag | undefined, +): Promise { + checkFileSupport(); + + // If it's a promise, resolve it. + value = await value; + + // If we've been given a `File` we don't need to do anything + if (isFileLike(value)) { + if (value instanceof File) { + return value; + } + return makeFile([await value.arrayBuffer()], value.name); + } + + if (isResponseLike(value)) { + const blob = await value.blob(); + name ||= new URL(value.url).pathname.split(/[\\/]/).pop(); + + return makeFile(await getBytes(blob), name, options); + } + + const parts = await getBytes(value); + + name ||= getName(value); + + if (!options?.type) { + const type = parts.find((part) => typeof part === 'object' && 'type' in part && part.type); + if (typeof type === 'string') { + options = { ...options, type }; + } + } + + return makeFile(parts, name, options); +} + +async function getBytes(value: BlobLikePart | AsyncIterable): Promise> { + let parts: Array = []; + 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 as BlobLikePart))); // 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: unknown): string { + if (typeof value !== 'object' || value === null) return ''; + const props = Object.getOwnPropertyNames(value); + return `; props: [${props.map((p) => `"${p}"`).join(', ')}]`; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/types.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..b668dfc0fe609e1f1c151104fab9c6bc39a7483e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/types.ts @@ -0,0 +1,95 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export type PromiseOrValue = T | Promise; +export type HTTPMethod = 'get' | 'post' | 'put' | 'patch' | 'delete'; + +export type KeysEnum = { [P in keyof Required]: true }; + +export type FinalizedRequestInit = RequestInit & { headers: Headers }; + +type NotAny = [0] extends [1 & T] ? never : T; + +/** + * Some environments overload the global fetch function, and Parameters only gets the last signature. + */ +type OverloadedParameters = + T extends ( + { + (...args: infer A): unknown; + (...args: infer B): unknown; + (...args: infer C): unknown; + (...args: infer D): unknown; + } + ) ? + A | B | C | D + : T extends ( + { + (...args: infer A): unknown; + (...args: infer B): unknown; + (...args: infer C): unknown; + } + ) ? + A | B | C + : T extends ( + { + (...args: infer A): unknown; + (...args: infer B): unknown; + } + ) ? + A | B + : T extends (...args: infer A) => unknown ? A + : never; + +/* eslint-disable */ +/** + * These imports attempt to get types from a parent package's dependencies. + * Unresolved bare specifiers can trigger [automatic type acquisition][1] in some projects, which + * would cause typescript to show types not present at runtime. To avoid this, we import + * directly from parent node_modules folders. + * + * We need to check multiple levels because we don't know what directory structure we'll be in. + * For example, pnpm generates directories like this: + * ``` + * node_modules + * ├── .pnpm + * │ └── pkg@1.0.0 + * │ └── node_modules + * │ └── pkg + * │ └── internal + * │ └── types.d.ts + * ├── pkg -> .pnpm/pkg@1.0.0/node_modules/pkg + * └── undici + * ``` + * + * [1]: https://www.typescriptlang.org/tsconfig/#typeAcquisition + */ +/** @ts-ignore For users with \@types/node */ +type UndiciTypesRequestInit = NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny; +/** @ts-ignore For users with undici */ +type UndiciRequestInit = NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny; +/** @ts-ignore For users with \@types/bun */ +type BunRequestInit = globalThis.FetchRequestInit; +/** @ts-ignore For users with node-fetch@2 */ +type NodeFetch2RequestInit = NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny; +/** @ts-ignore For users with node-fetch@3, doesn't need file extension because types are at ./@types/index.d.ts */ +type NodeFetch3RequestInit = NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny | NotAny; +/** @ts-ignore For users who use Deno */ +type FetchRequestInit = NonNullable[1]>; +/* eslint-enable */ + +type RequestInits = + | NotAny + | NotAny + | NotAny + | NotAny + | NotAny + | NotAny + | NotAny; + +/** + * This type contains `RequestInit` options that may be available on the current runtime, + * including per-platform extensions like `dispatcher`, `agent`, `client`, etc. + */ +export type MergedRequestInit = RequestInits & + /** We don't include these in the types as they'll be overridden for every request. */ + Partial>; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/uploads.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/uploads.ts new file mode 100644 index 0000000000000000000000000000000000000000..15073983b40a1719ee2ea041a4fc233f16b3e016 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/uploads.ts @@ -0,0 +1,187 @@ +import { type RequestOptions } from './request-options'; +import type { FilePropertyBag, Fetch } from './builtin-types'; +import type { OpenAI } from '../client'; +import { ReadableStreamFrom } from './shims'; + +export type BlobPart = string | ArrayBuffer | ArrayBufferView | Blob | DataView; +type FsReadStream = AsyncIterable & { path: string | { toString(): string } }; + +// https://github.com/oven-sh/bun/issues/5980 +interface BunFile extends Blob { + readonly name?: string | undefined; +} + +export const checkFileSupport = () => { + if (typeof File === 'undefined') { + const { process } = globalThis as any; + 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`." + : ''), + ); + } +}; + +/** + * Typically, this is a native "File" class. + * + * We provide the {@link toFile} utility to convert a variety of objects + * into the File class. + * + * For convenience, you can also pass a fetch Response, or in Node, + * the result of fs.createReadStream(). + */ +export type Uploadable = File | Response | FsReadStream | BunFile; + +/** + * 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: BlobPart[], + fileName: string | undefined, + options?: FilePropertyBag, +): File { + checkFileSupport(); + return new File(fileBits as any, fileName ?? 'unknown_file', options); +} + +export function getName(value: any): string | undefined { + return ( + ( + (typeof value === 'object' && + value !== null && + (('name' in value && value.name && String(value.name)) || + ('url' in value && value.url && String(value.url)) || + ('filename' in value && value.filename && String(value.filename)) || + ('path' in value && value.path && String(value.path)))) || + '' + ) + .split(/[\\/]/) + .pop() || undefined + ); +} + +export const isAsyncIterable = (value: any): value is AsyncIterable => + 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: RequestOptions, + fetch: OpenAI | Fetch, +): Promise => { + if (!hasUploadableValue(opts.body)) return opts; + + return { ...opts, body: await createForm(opts.body, fetch) }; +}; + +type MultipartFormRequestOptions = Omit & { body: unknown }; + +export const multipartFormRequestOptions = async ( + opts: MultipartFormRequestOptions, + fetch: OpenAI | Fetch, +): Promise => { + return { ...opts, body: await createForm(opts.body, fetch) }; +}; + +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: OpenAI | Fetch): Promise { + const fetch: Fetch = typeof fetchObject === 'function' ? fetchObject : (fetchObject as any).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) as typeof Response; + 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: T | undefined, + fetch: OpenAI | Fetch, +): Promise => { + 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))); + 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: unknown) => value instanceof Blob && 'name' in value; + +const isUploadable = (value: unknown) => + typeof value === 'object' && + value !== null && + (value instanceof Response || isAsyncIterable(value) || isNamedBlob(value)); + +const hasUploadableValue = (value: unknown): boolean => { + 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 as any)[k])) return true; + } + } + return false; +}; + +const addFormValue = async (form: FormData, key: string, value: unknown): Promise => { + 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) { + form.append(key, makeFile([await value.blob()], getName(value))); + } else if (isAsyncIterable(value)) { + form.append(key, makeFile([await new Response(ReadableStreamFrom(value)).blob()], getName(value))); + } else if (isNamedBlob(value)) { + form.append(key, value, getName(value)); + } else if (Array.isArray(value)) { + await Promise.all(value.map((entry) => addFormValue(form, key + '[]', entry))); + } else if (typeof value === 'object') { + await Promise.all( + Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop)), + ); + } else { + throw new TypeError( + `Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`, + ); + } +}; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/utils.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/utils.ts new file mode 100644 index 0000000000000000000000000000000000000000..3cbfacce29a05b720a183ce2c4680a40a8463fea --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/utils.ts @@ -0,0 +1,8 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export * from './utils/values'; +export * from './utils/base64'; +export * from './utils/env'; +export * from './utils/log'; +export * from './utils/uuid'; +export * from './utils/sleep'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/utils/base64.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/utils/base64.ts new file mode 100644 index 0000000000000000000000000000000000000000..f230cfe9abb35acebbcc257088db78638991a5aa --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/utils/base64.ts @@ -0,0 +1,64 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { OpenAIError } from '../../core/error'; +import { encodeUTF8 } from './bytes'; + +export const toBase64 = (data: string | Uint8Array | null | undefined): string => { + if (!data) return ''; + + if (typeof (globalThis as any).Buffer !== 'undefined') { + return (globalThis as any).Buffer.from(data).toString('base64'); + } + + if (typeof data === 'string') { + data = encodeUTF8(data); + } + + if (typeof btoa !== 'undefined') { + return btoa(String.fromCharCode.apply(null, data as any)); + } + + throw new OpenAIError('Cannot generate base64 string; Expected `Buffer` or `btoa` to be defined'); +}; + +export const fromBase64 = (str: string): Uint8Array => { + if (typeof (globalThis as any).Buffer !== 'undefined') { + const buf = (globalThis as any).Buffer.from(str, 'base64'); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + } + + if (typeof atob !== 'undefined') { + const bstr = atob(str); + const buf = new Uint8Array(bstr.length); + for (let i = 0; i < bstr.length; i++) { + buf[i] = bstr.charCodeAt(i); + } + return buf; + } + + throw new OpenAIError('Cannot decode base64 string; Expected `Buffer` or `atob` to be defined'); +}; + +/** + * Converts a Base64 encoded string to a Float32Array. + * @param base64Str - The Base64 encoded string. + * @returns An Array of numbers interpreted as Float32 values. + */ +export const toFloat32Array = (base64Str: string): Array => { + if (typeof Buffer !== 'undefined') { + // for Node.js environment + const buf = Buffer.from(base64Str, 'base64'); + return Array.from( + new Float32Array(buf.buffer, buf.byteOffset, buf.length / Float32Array.BYTES_PER_ELEMENT), + ); + } else { + // for legacy web platform APIs + const binaryStr = atob(base64Str); + const len = binaryStr.length; + const bytes = new Uint8Array(len); + for (let i = 0; i < len; i++) { + bytes[i] = binaryStr.charCodeAt(i); + } + return Array.from(new Float32Array(bytes.buffer)); + } +}; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/utils/bytes.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/utils/bytes.ts new file mode 100644 index 0000000000000000000000000000000000000000..8da627abe133306f787a3d0c4d7182ab3170804b --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/utils/bytes.ts @@ -0,0 +1,32 @@ +export function concatBytes(buffers: Uint8Array[]): Uint8Array { + 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_: (str: string) => Uint8Array; +export function encodeUTF8(str: string) { + let encoder; + return ( + encodeUTF8_ ?? + ((encoder = new (globalThis as any).TextEncoder()), (encodeUTF8_ = encoder.encode.bind(encoder))) + )(str); +} + +let decodeUTF8_: (bytes: Uint8Array) => string; +export function decodeUTF8(bytes: Uint8Array) { + let decoder; + return ( + decodeUTF8_ ?? + ((decoder = new (globalThis as any).TextDecoder()), (decodeUTF8_ = decoder.decode.bind(decoder))) + )(bytes); +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/utils/env.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/utils/env.ts new file mode 100644 index 0000000000000000000000000000000000000000..2d8480077c2302e9c2f376fc56afccb4330f94d8 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/utils/env.ts @@ -0,0 +1,18 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +/** + * Read an environment variable. + * + * Trims beginning and trailing whitespace. + * + * Will return undefined if the environment variable doesn't exist or cannot be accessed. + */ +export const readEnv = (env: string): string | undefined => { + if (typeof (globalThis as any).process !== 'undefined') { + return (globalThis as any).process.env?.[env]?.trim() ?? undefined; + } + if (typeof (globalThis as any).Deno !== 'undefined') { + return (globalThis as any).Deno.env?.get?.(env)?.trim(); + } + return undefined; +}; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/utils/log.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/utils/log.ts new file mode 100644 index 0000000000000000000000000000000000000000..5c082d98361df3b0b8e3e47e412b4ee27b5b040f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/utils/log.ts @@ -0,0 +1,126 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { hasOwn } from './values'; +import { type OpenAI } from '../../client'; +import { RequestOptions } from '../request-options'; + +type LogFn = (message: string, ...rest: unknown[]) => void; +export type Logger = { + error: LogFn; + warn: LogFn; + info: LogFn; + debug: LogFn; +}; +export type LogLevel = 'off' | 'error' | 'warn' | 'info' | 'debug'; + +const levelNumbers = { + off: 0, + error: 200, + warn: 300, + info: 400, + debug: 500, +}; + +export const parseLogLevel = ( + maybeLevel: string | undefined, + sourceName: string, + client: OpenAI, +): LogLevel | undefined => { + 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: keyof Logger, logger: Logger | undefined, logLevel: 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: OpenAI): Logger { + 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: { + options?: RequestOptions | undefined; + headers?: Headers | Record | undefined; + retryOfRequestLogID?: string | undefined; + retryOf?: string | undefined; + url?: string | undefined; + status?: number | undefined; + method?: string | undefined; + durationMs?: number | undefined; + message?: unknown; + body?: unknown; +}) => { + if (details.options) { + details.options = { ...details.options }; + delete details.options['headers']; // redundant + leaks internals + } + if (details.headers) { + details.headers = Object.fromEntries( + (details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map( + ([name, value]) => [ + name, + ( + name.toLowerCase() === 'authorization' || + name.toLowerCase() === 'cookie' || + name.toLowerCase() === 'set-cookie' + ) ? + '***' + : value, + ], + ), + ); + } + if ('retryOfRequestLogID' in details) { + if (details.retryOfRequestLogID) { + details.retryOf = details.retryOfRequestLogID; + } + delete details.retryOfRequestLogID; + } + return details; +}; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/utils/path.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/utils/path.ts new file mode 100644 index 0000000000000000000000000000000000000000..f18329ccf2f7305566d6229998328c0b3d84f7be --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/utils/path.ts @@ -0,0 +1,88 @@ +import { OpenAIError } from '../../core/error'; + +/** + * 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: string) { + 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: readonly string[], ...params: readonly unknown[]): string { + // 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 as any).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 OpenAIError( + `Path parameters result in path with invalid segments:\n${invalidSegments + .map((e) => e.error) + .join('\n')}\n${path}\n${underline}`, + ); + } + + return path; + }; + +/** + * URI-encodes path params and ensures no unsafe /./ or /../ path segments are introduced. + */ +export const path = /* @__PURE__ */ createPathTagFunction(encodeURIPath); diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/utils/sleep.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/utils/sleep.ts new file mode 100644 index 0000000000000000000000000000000000000000..65e52962bbb288c4a2f19fbe14b7ffb9baba6487 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/utils/sleep.ts @@ -0,0 +1,3 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/utils/uuid.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/utils/uuid.ts new file mode 100644 index 0000000000000000000000000000000000000000..b0e53aaf7ef092c1bd64847211ab62b27bb18869 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/utils/uuid.ts @@ -0,0 +1,17 @@ +// 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 as any; + 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), + ); +}; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/utils/values.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/utils/values.ts new file mode 100644 index 0000000000000000000000000000000000000000..801974e84053d25bf6b33b4087ce01f10087d76c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/internal/utils/values.ts @@ -0,0 +1,105 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { OpenAIError } from '../../core/error'; + +// https://url.spec.whatwg.org/#url-scheme-string +const startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i; + +export const isAbsoluteURL = (url: string): boolean => { + return startsWithSchemeRegexp.test(url); +}; + +export let isArray = (val: unknown): val is unknown[] => ((isArray = Array.isArray), isArray(val)); +export let isReadonlyArray = isArray as (val: unknown) => val is readonly unknown[]; + +/** Returns an object if the given value isn't an object, otherwise returns as-is */ +export function maybeObj(x: unknown): object { + if (typeof x !== 'object') { + return {}; + } + + return x ?? {}; +} + +// https://stackoverflow.com/a/34491287 +export function isEmptyObj(obj: Object | null | undefined): boolean { + 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: T, key: PropertyKey): key is keyof T { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +export function isObj(obj: unknown): obj is Record { + return obj != null && typeof obj === 'object' && !Array.isArray(obj); +} + +export const ensurePresent = (value: T | null | undefined): T => { + if (value == null) { + throw new OpenAIError(`Expected a value to be given but received ${value} instead.`); + } + + return value; +}; + +export const validatePositiveInteger = (name: string, n: unknown): number => { + if (typeof n !== 'number' || !Number.isInteger(n)) { + throw new OpenAIError(`${name} must be an integer`); + } + if (n < 0) { + throw new OpenAIError(`${name} must be a positive integer`); + } + return n; +}; + +export const coerceInteger = (value: unknown): number => { + if (typeof value === 'number') return Math.round(value); + if (typeof value === 'string') return parseInt(value, 10); + + throw new OpenAIError(`Could not coerce ${value} (type: ${typeof value}) into a number`); +}; + +export const coerceFloat = (value: unknown): number => { + if (typeof value === 'number') return value; + if (typeof value === 'string') return parseFloat(value); + + throw new OpenAIError(`Could not coerce ${value} (type: ${typeof value}) into a number`); +}; + +export const coerceBoolean = (value: unknown): boolean => { + if (typeof value === 'boolean') return value; + if (typeof value === 'string') return value === 'true'; + return Boolean(value); +}; + +export const maybeCoerceInteger = (value: unknown): number | undefined => { + if (value === undefined) { + return undefined; + } + return coerceInteger(value); +}; + +export const maybeCoerceFloat = (value: unknown): number | undefined => { + if (value === undefined) { + return undefined; + } + return coerceFloat(value); +}; + +export const maybeCoerceBoolean = (value: unknown): boolean | undefined => { + if (value === undefined) { + return undefined; + } + return coerceBoolean(value); +}; + +export const safeJSON = (text: string) => { + try { + return JSON.parse(text); + } catch (err) { + return undefined; + } +}; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/.keep b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/.keep new file mode 100644 index 0000000000000000000000000000000000000000..7554f8b20ae58485df49010107f79349db1c5943 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/.keep @@ -0,0 +1,4 @@ +File generated from our OpenAPI spec by Stainless. + +This directory can be used to store custom files to expand the SDK. +It is ignored by Stainless code generation and its content (other than this keep file) won't be touched. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/AbstractChatCompletionRunner.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/AbstractChatCompletionRunner.ts new file mode 100644 index 0000000000000000000000000000000000000000..982c572f6ea6176bb3105f5d4982a6399595ab09 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/AbstractChatCompletionRunner.ts @@ -0,0 +1,404 @@ +import { OpenAIError } from '../error'; +import type OpenAI from '../index'; +import type { RequestOptions } from '../internal/request-options'; +import { isAutoParsableTool, parseChatCompletion } from '../lib/parser'; +import type { + ChatCompletion, + ChatCompletionCreateParams, + ChatCompletionMessage, + ChatCompletionMessageFunctionToolCall, + ChatCompletionMessageParam, + ChatCompletionTool, + ParsedChatCompletion, +} from '../resources/chat/completions'; +import type { CompletionUsage } from '../resources/completions'; +import type { ChatCompletionToolRunnerParams } from './ChatCompletionRunner'; +import type { ChatCompletionStreamingToolRunnerParams } from './ChatCompletionStreamingRunner'; +import { isAssistantMessage, isToolMessage } from './chatCompletionUtils'; +import { BaseEvents, EventStream } from './EventStream'; +import { + isRunnableFunctionWithParse, + type BaseFunctionsArgs, + type RunnableFunction, + type RunnableToolFunction, +} from './RunnableFunction'; + +const DEFAULT_MAX_CHAT_COMPLETIONS = 10; +export interface RunnerOptions extends RequestOptions { + /** How many requests to make before canceling. Default 10. */ + maxChatCompletions?: number; +} + +export class AbstractChatCompletionRunner< + EventTypes extends AbstractChatCompletionRunnerEvents, + ParsedT, +> extends EventStream { + protected _chatCompletions: ParsedChatCompletion[] = []; + messages: ChatCompletionMessageParam[] = []; + + protected _addChatCompletion( + this: AbstractChatCompletionRunner, + chatCompletion: ParsedChatCompletion, + ): ParsedChatCompletion { + this._chatCompletions.push(chatCompletion); + this._emit('chatCompletion', chatCompletion); + const message = chatCompletion.choices[0]?.message; + if (message) this._addMessage(message as ChatCompletionMessageParam); + return chatCompletion; + } + + protected _addMessage( + this: AbstractChatCompletionRunner, + message: ChatCompletionMessageParam, + emit = true, + ) { + if (!('content' in message)) message.content = null; + + this.messages.push(message); + + if (emit) { + this._emit('message', message); + if (isToolMessage(message) && message.content) { + // Note, this assumes that {role: 'tool', content: …} is always the result of a call of tool of type=function. + this._emit('functionToolCallResult', message.content as string); + } else if (isAssistantMessage(message) && message.tool_calls) { + for (const tool_call of message.tool_calls) { + if (tool_call.type === 'function') { + this._emit('functionToolCall', tool_call.function); + } + } + } + } + } + + /** + * @returns a promise that resolves with the final ChatCompletion, or rejects + * if an error occurred or the stream ended prematurely without producing a ChatCompletion. + */ + async finalChatCompletion(): Promise> { + await this.done(); + const completion = this._chatCompletions[this._chatCompletions.length - 1]; + if (!completion) throw new OpenAIError('stream ended without producing a ChatCompletion'); + return completion; + } + + #getFinalContent(): string | null { + return this.#getFinalMessage().content ?? null; + } + + /** + * @returns a promise that resolves with the content of the final ChatCompletionMessage, or rejects + * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. + */ + async finalContent(): Promise { + await this.done(); + return this.#getFinalContent(); + } + + #getFinalMessage(): ChatCompletionMessage { + let i = this.messages.length; + while (i-- > 0) { + const message = this.messages[i]; + if (isAssistantMessage(message)) { + // TODO: support audio here + const ret: Omit = { + ...message, + content: (message as ChatCompletionMessage).content ?? null, + refusal: (message as ChatCompletionMessage).refusal ?? null, + }; + return ret; + } + } + throw new OpenAIError('stream ended without producing a ChatCompletionMessage with role=assistant'); + } + + /** + * @returns a promise that resolves with the the final assistant ChatCompletionMessage response, + * or rejects if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. + */ + async finalMessage(): Promise { + await this.done(); + return this.#getFinalMessage(); + } + + #getFinalFunctionToolCall(): ChatCompletionMessageFunctionToolCall.Function | undefined { + for (let i = this.messages.length - 1; i >= 0; i--) { + const message = this.messages[i]; + if (isAssistantMessage(message) && message?.tool_calls?.length) { + return message.tool_calls.filter((x) => x.type === 'function').at(-1)?.function; + } + } + + return; + } + + /** + * @returns a promise that resolves with the content of the final FunctionCall, or rejects + * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. + */ + async finalFunctionToolCall(): Promise { + await this.done(); + return this.#getFinalFunctionToolCall(); + } + + #getFinalFunctionToolCallResult(): string | undefined { + for (let i = this.messages.length - 1; i >= 0; i--) { + const message = this.messages[i]; + if ( + isToolMessage(message) && + message.content != null && + typeof message.content === 'string' && + this.messages.some( + (x) => + x.role === 'assistant' && + x.tool_calls?.some((y) => y.type === 'function' && y.id === message.tool_call_id), + ) + ) { + return message.content; + } + } + + return; + } + + async finalFunctionToolCallResult(): Promise { + await this.done(); + return this.#getFinalFunctionToolCallResult(); + } + + #calculateTotalUsage(): CompletionUsage { + const total: CompletionUsage = { + completion_tokens: 0, + prompt_tokens: 0, + total_tokens: 0, + }; + for (const { usage } of this._chatCompletions) { + if (usage) { + total.completion_tokens += usage.completion_tokens; + total.prompt_tokens += usage.prompt_tokens; + total.total_tokens += usage.total_tokens; + } + } + return total; + } + + async totalUsage(): Promise { + await this.done(); + return this.#calculateTotalUsage(); + } + + allChatCompletions(): ChatCompletion[] { + return [...this._chatCompletions]; + } + + protected override _emitFinal( + this: AbstractChatCompletionRunner, + ) { + const completion = this._chatCompletions[this._chatCompletions.length - 1]; + if (completion) this._emit('finalChatCompletion', completion); + const finalMessage = this.#getFinalMessage(); + if (finalMessage) this._emit('finalMessage', finalMessage); + const finalContent = this.#getFinalContent(); + if (finalContent) this._emit('finalContent', finalContent); + + const finalFunctionCall = this.#getFinalFunctionToolCall(); + if (finalFunctionCall) this._emit('finalFunctionToolCall', finalFunctionCall); + + const finalFunctionCallResult = this.#getFinalFunctionToolCallResult(); + if (finalFunctionCallResult != null) this._emit('finalFunctionToolCallResult', finalFunctionCallResult); + + if (this._chatCompletions.some((c) => c.usage)) { + this._emit('totalUsage', this.#calculateTotalUsage()); + } + } + + #validateParams(params: ChatCompletionCreateParams): void { + if (params.n != null && params.n > 1) { + throw new OpenAIError( + 'ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.', + ); + } + } + + protected async _createChatCompletion( + client: OpenAI, + params: ChatCompletionCreateParams, + options?: RequestOptions, + ): Promise> { + const signal = options?.signal; + if (signal) { + if (signal.aborted) this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + this.#validateParams(params); + + const chatCompletion = await client.chat.completions.create( + { ...params, stream: false }, + { ...options, signal: this.controller.signal }, + ); + this._connected(); + return this._addChatCompletion(parseChatCompletion(chatCompletion, params)); + } + + protected async _runChatCompletion( + client: OpenAI, + params: ChatCompletionCreateParams, + options?: RequestOptions, + ): Promise { + for (const message of params.messages) { + this._addMessage(message, false); + } + return await this._createChatCompletion(client, params, options); + } + + protected async _runTools( + client: OpenAI, + params: + | ChatCompletionToolRunnerParams + | ChatCompletionStreamingToolRunnerParams, + options?: RunnerOptions, + ) { + const role = 'tool' as const; + const { tool_choice = 'auto', stream, ...restParams } = params; + const singleFunctionToCall = + typeof tool_choice !== 'string' && tool_choice.type === 'function' && tool_choice?.function?.name; + const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {}; + + // TODO(someday): clean this logic up + const inputTools = params.tools.map((tool): RunnableToolFunction => { + if (isAutoParsableTool(tool)) { + if (!tool.$callback) { + throw new OpenAIError('Tool given to `.runTools()` that does not have an associated function'); + } + + return { + type: 'function', + function: { + function: tool.$callback, + name: tool.function.name, + description: tool.function.description || '', + parameters: tool.function.parameters as any, + parse: tool.$parseRaw, + strict: true, + }, + }; + } + + return tool as any as RunnableToolFunction; + }); + + const functionsByName: Record> = {}; + for (const f of inputTools) { + if (f.type === 'function') { + functionsByName[f.function.name || f.function.function.name] = f.function; + } + } + + const tools: ChatCompletionTool[] = + 'tools' in params ? + inputTools.map((t) => + t.type === 'function' ? + { + type: 'function', + function: { + name: t.function.name || t.function.function.name, + parameters: t.function.parameters as Record, + description: t.function.description, + strict: t.function.strict, + }, + } + : (t as unknown as ChatCompletionTool), + ) + : (undefined as any); + + for (const message of params.messages) { + this._addMessage(message, false); + } + + for (let i = 0; i < maxChatCompletions; ++i) { + const chatCompletion: ChatCompletion = await this._createChatCompletion( + client, + { + ...restParams, + tool_choice, + tools, + messages: [...this.messages], + }, + options, + ); + const message = chatCompletion.choices[0]?.message; + if (!message) { + throw new OpenAIError(`missing message in ChatCompletion response`); + } + if (!message.tool_calls?.length) { + return; + } + + for (const tool_call of message.tool_calls) { + if (tool_call.type !== 'function') continue; + const tool_call_id = tool_call.id; + const { name, arguments: args } = tool_call.function; + const fn = functionsByName[name]; + + if (!fn) { + const content = `Invalid tool_call: ${JSON.stringify(name)}. Available options are: ${Object.keys( + functionsByName, + ) + .map((name) => JSON.stringify(name)) + .join(', ')}. Please try again`; + + this._addMessage({ role, tool_call_id, content }); + continue; + } else if (singleFunctionToCall && singleFunctionToCall !== name) { + const content = `Invalid tool_call: ${JSON.stringify(name)}. ${JSON.stringify( + singleFunctionToCall, + )} requested. Please try again`; + + this._addMessage({ role, tool_call_id, content }); + continue; + } + + let parsed; + try { + parsed = isRunnableFunctionWithParse(fn) ? await fn.parse(args) : args; + } catch (error) { + const content = error instanceof Error ? error.message : String(error); + this._addMessage({ role, tool_call_id, content }); + continue; + } + + // @ts-expect-error it can't rule out `never` type. + const rawContent = await fn.function(parsed, this); + const content = this.#stringifyFunctionCallResult(rawContent); + this._addMessage({ role, tool_call_id, content }); + + if (singleFunctionToCall) { + return; + } + } + } + + return; + } + + #stringifyFunctionCallResult(rawContent: unknown): string { + return ( + typeof rawContent === 'string' ? rawContent + : rawContent === undefined ? 'undefined' + : JSON.stringify(rawContent) + ); + } +} + +export interface AbstractChatCompletionRunnerEvents extends BaseEvents { + functionToolCall: (functionCall: ChatCompletionMessageFunctionToolCall.Function) => void; + message: (message: ChatCompletionMessageParam) => void; + chatCompletion: (completion: ChatCompletion) => void; + finalContent: (contentSnapshot: string) => void; + finalMessage: (message: ChatCompletionMessageParam) => void; + finalChatCompletion: (completion: ChatCompletion) => void; + finalFunctionToolCall: (functionCall: ChatCompletionMessageFunctionToolCall.Function) => void; + functionToolCallResult: (content: string) => void; + finalFunctionToolCallResult: (content: string) => void; + totalUsage: (usage: CompletionUsage) => void; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/AssistantStream.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/AssistantStream.ts new file mode 100644 index 0000000000000000000000000000000000000000..bb2a2b5b36525aacb6a369b6dd36dea3639131f9 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/AssistantStream.ts @@ -0,0 +1,778 @@ +import { + TextContentBlock, + ImageFileContentBlock, + Message, + MessageContentDelta, + Text, + ImageFile, + TextDelta, + MessageDelta, + MessageContent, +} from '../resources/beta/threads/messages'; +import { RequestOptions } from '../internal/request-options'; +import { + Run, + RunCreateParamsBase, + RunCreateParamsStreaming, + Runs, + RunSubmitToolOutputsParamsBase, + RunSubmitToolOutputsParamsStreaming, +} from '../resources/beta/threads/runs/runs'; +import { type ReadableStream } from '../internal/shim-types'; +import { Stream } from '../streaming'; +import { APIUserAbortError, OpenAIError } from '../error'; +import { + AssistantStreamEvent, + MessageStreamEvent, + RunStepStreamEvent, + RunStreamEvent, +} from '../resources/beta/assistants'; +import { RunStep, RunStepDelta, ToolCall, ToolCallDelta } from '../resources/beta/threads/runs/steps'; +import { ThreadCreateAndRunParamsBase, Threads } from '../resources/beta/threads/threads'; +import { BaseEvents, EventStream } from './EventStream'; +import { isObj } from '../internal/utils'; + +export interface AssistantStreamEvents extends BaseEvents { + run: (run: Run) => void; + + //New event structure + messageCreated: (message: Message) => void; + messageDelta: (message: MessageDelta, snapshot: Message) => void; + messageDone: (message: Message) => void; + + runStepCreated: (runStep: RunStep) => void; + runStepDelta: (delta: RunStepDelta, snapshot: Runs.RunStep) => void; + runStepDone: (runStep: Runs.RunStep, snapshot: Runs.RunStep) => void; + + toolCallCreated: (toolCall: ToolCall) => void; + toolCallDelta: (delta: ToolCallDelta, snapshot: ToolCall) => void; + toolCallDone: (toolCall: ToolCall) => void; + + textCreated: (content: Text) => void; + textDelta: (delta: TextDelta, snapshot: Text) => void; + textDone: (content: Text, snapshot: Message) => void; + + //No created or delta as this is not streamed + imageFileDone: (content: ImageFile, snapshot: Message) => void; + + event: (event: AssistantStreamEvent) => void; +} + +export type ThreadCreateAndRunParamsBaseStream = Omit & { + stream?: true; +}; + +export type RunCreateParamsBaseStream = Omit & { + stream?: true; +}; + +export type RunSubmitToolOutputsParamsStream = Omit & { + stream?: true; +}; + +export class AssistantStream + extends EventStream + implements AsyncIterable +{ + //Track all events in a single list for reference + #events: AssistantStreamEvent[] = []; + + //Used to accumulate deltas + //We are accumulating many types so the value here is not strict + #runStepSnapshots: { [id: string]: Runs.RunStep } = {}; + #messageSnapshots: { [id: string]: Message } = {}; + #messageSnapshot: Message | undefined; + #finalRun: Run | undefined; + #currentContentIndex: number | undefined; + #currentContent: MessageContent | undefined; + #currentToolCallIndex: number | undefined; + #currentToolCall: ToolCall | undefined; + + //For current snapshot methods + #currentEvent: AssistantStreamEvent | undefined; + #currentRunSnapshot: Run | undefined; + #currentRunStepSnapshot: Runs.RunStep | undefined; + + [Symbol.asyncIterator](): AsyncIterator { + const pushQueue: AssistantStreamEvent[] = []; + const readQueue: { + resolve: (chunk: AssistantStreamEvent | undefined) => void; + reject: (err: unknown) => void; + }[] = []; + let done = false; + + //Catch all for passing along all events + this.on('event', (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 (): Promise> => { + 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 }; + }, + }; + } + + static fromReadableStream(stream: ReadableStream): AssistantStream { + const runner = new AssistantStream(); + runner._run(() => runner._fromReadableStream(stream)); + return runner; + } + + protected async _fromReadableStream( + readableStream: ReadableStream, + options?: RequestOptions, + ): Promise { + const signal = options?.signal; + if (signal) { + if (signal.aborted) this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + this._connected(); + const stream = Stream.fromReadableStream(readableStream, this.controller); + for await (const event of stream) { + this.#addEvent(event); + } + if (stream.controller.signal?.aborted) { + throw new APIUserAbortError(); + } + return this._addRun(this.#endRequest()); + } + + toReadableStream(): ReadableStream { + const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller); + return stream.toReadableStream(); + } + + static createToolAssistantStream( + runId: string, + runs: Runs, + params: RunSubmitToolOutputsParamsStream, + options: RequestOptions | undefined, + ): AssistantStream { + const runner = new AssistantStream(); + runner._run(() => + runner._runToolAssistantStream(runId, runs, params, { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, + }), + ); + return runner; + } + + protected async _createToolAssistantStream( + run: Runs, + runId: string, + params: RunSubmitToolOutputsParamsStream, + options?: RequestOptions, + ): Promise { + const signal = options?.signal; + if (signal) { + if (signal.aborted) this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + + const body: RunSubmitToolOutputsParamsStreaming = { ...params, stream: true }; + const stream = await run.submitToolOutputs(runId, body, { + ...options, + signal: this.controller.signal, + }); + + this._connected(); + + for await (const event of stream) { + this.#addEvent(event); + } + if (stream.controller.signal?.aborted) { + throw new APIUserAbortError(); + } + + return this._addRun(this.#endRequest()); + } + + static createThreadAssistantStream( + params: ThreadCreateAndRunParamsBaseStream, + thread: Threads, + options?: RequestOptions, + ): AssistantStream { + const runner = new AssistantStream(); + runner._run(() => + runner._threadAssistantStream(params, thread, { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, + }), + ); + return runner; + } + + static createAssistantStream( + threadId: string, + runs: Runs, + params: RunCreateParamsBaseStream, + options?: RequestOptions, + ): AssistantStream { + const runner = new AssistantStream(); + runner._run(() => + runner._runAssistantStream(threadId, runs, params, { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, + }), + ); + return runner; + } + + currentEvent(): AssistantStreamEvent | undefined { + return this.#currentEvent; + } + + currentRun(): Run | undefined { + return this.#currentRunSnapshot; + } + + currentMessageSnapshot(): Message | undefined { + return this.#messageSnapshot; + } + + currentRunStepSnapshot(): Runs.RunStep | undefined { + return this.#currentRunStepSnapshot; + } + + async finalRunSteps(): Promise { + await this.done(); + + return Object.values(this.#runStepSnapshots); + } + + async finalMessages(): Promise { + await this.done(); + + return Object.values(this.#messageSnapshots); + } + + async finalRun(): Promise { + await this.done(); + if (!this.#finalRun) throw Error('Final run was not received.'); + + return this.#finalRun; + } + + protected async _createThreadAssistantStream( + thread: Threads, + params: ThreadCreateAndRunParamsBase, + options?: RequestOptions, + ): Promise { + const signal = options?.signal; + if (signal) { + if (signal.aborted) this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + + const body: RunCreateParamsStreaming = { ...params, stream: true }; + const stream = await thread.createAndRun(body, { ...options, signal: this.controller.signal }); + + this._connected(); + + for await (const event of stream) { + this.#addEvent(event); + } + if (stream.controller.signal?.aborted) { + throw new APIUserAbortError(); + } + + return this._addRun(this.#endRequest()); + } + + protected async _createAssistantStream( + run: Runs, + threadId: string, + params: RunCreateParamsBase, + options?: RequestOptions, + ): Promise { + const signal = options?.signal; + if (signal) { + if (signal.aborted) this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + + const body: RunCreateParamsStreaming = { ...params, stream: true }; + const stream = await run.create(threadId, body, { ...options, signal: this.controller.signal }); + + this._connected(); + + for await (const event of stream) { + this.#addEvent(event); + } + if (stream.controller.signal?.aborted) { + throw new APIUserAbortError(); + } + + return this._addRun(this.#endRequest()); + } + + #addEvent(event: AssistantStreamEvent) { + if (this.ended) return; + + this.#currentEvent = event; + + this.#handleEvent(event); + + switch (event.event) { + case 'thread.created': + //No action on this event. + break; + + case 'thread.run.created': + case 'thread.run.queued': + case 'thread.run.in_progress': + case 'thread.run.requires_action': + case 'thread.run.completed': + case 'thread.run.incomplete': + case 'thread.run.failed': + case 'thread.run.cancelling': + case 'thread.run.cancelled': + case 'thread.run.expired': + this.#handleRun(event); + break; + + case 'thread.run.step.created': + case 'thread.run.step.in_progress': + case 'thread.run.step.delta': + case 'thread.run.step.completed': + case 'thread.run.step.failed': + case 'thread.run.step.cancelled': + case 'thread.run.step.expired': + this.#handleRunStep(event); + break; + + case 'thread.message.created': + case 'thread.message.in_progress': + case 'thread.message.delta': + case 'thread.message.completed': + case 'thread.message.incomplete': + this.#handleMessage(event); + break; + + case 'error': + //This is included for completeness, but errors are processed in the SSE event processing so this should not occur + throw new Error( + 'Encountered an error event in event processing - errors should be processed earlier', + ); + default: + assertNever(event); + } + } + + #endRequest(): Run { + if (this.ended) { + throw new OpenAIError(`stream has ended, this shouldn't happen`); + } + + if (!this.#finalRun) throw Error('Final run has not been received'); + + return this.#finalRun; + } + + #handleMessage(this: AssistantStream, event: MessageStreamEvent) { + const [accumulatedMessage, newContent] = this.#accumulateMessage(event, this.#messageSnapshot); + this.#messageSnapshot = accumulatedMessage; + this.#messageSnapshots[accumulatedMessage.id] = accumulatedMessage; + + for (const content of newContent) { + const snapshotContent = accumulatedMessage.content[content.index]; + if (snapshotContent?.type == 'text') { + this._emit('textCreated', snapshotContent.text); + } + } + + switch (event.event) { + case 'thread.message.created': + this._emit('messageCreated', event.data); + break; + + case 'thread.message.in_progress': + break; + + case 'thread.message.delta': + this._emit('messageDelta', event.data.delta, accumulatedMessage); + + if (event.data.delta.content) { + for (const content of event.data.delta.content) { + //If it is text delta, emit a text delta event + if (content.type == 'text' && content.text) { + let textDelta = content.text; + let snapshot = accumulatedMessage.content[content.index]; + if (snapshot && snapshot.type == 'text') { + this._emit('textDelta', textDelta, snapshot.text); + } else { + throw Error('The snapshot associated with this text delta is not text or missing'); + } + } + + if (content.index != this.#currentContentIndex) { + //See if we have in progress content + if (this.#currentContent) { + switch (this.#currentContent.type) { + case 'text': + this._emit('textDone', this.#currentContent.text, this.#messageSnapshot); + break; + case 'image_file': + this._emit('imageFileDone', this.#currentContent.image_file, this.#messageSnapshot); + break; + } + } + + this.#currentContentIndex = content.index; + } + + this.#currentContent = accumulatedMessage.content[content.index]; + } + } + + break; + + case 'thread.message.completed': + case 'thread.message.incomplete': + //We emit the latest content we were working on on completion (including incomplete) + if (this.#currentContentIndex !== undefined) { + const currentContent = event.data.content[this.#currentContentIndex]; + if (currentContent) { + switch (currentContent.type) { + case 'image_file': + this._emit('imageFileDone', currentContent.image_file, this.#messageSnapshot); + break; + case 'text': + this._emit('textDone', currentContent.text, this.#messageSnapshot); + break; + } + } + } + + if (this.#messageSnapshot) { + this._emit('messageDone', event.data); + } + + this.#messageSnapshot = undefined; + } + } + + #handleRunStep(this: AssistantStream, event: RunStepStreamEvent) { + const accumulatedRunStep = this.#accumulateRunStep(event); + this.#currentRunStepSnapshot = accumulatedRunStep; + + switch (event.event) { + case 'thread.run.step.created': + this._emit('runStepCreated', event.data); + break; + case 'thread.run.step.delta': + const delta = event.data.delta; + if ( + delta.step_details && + delta.step_details.type == 'tool_calls' && + delta.step_details.tool_calls && + accumulatedRunStep.step_details.type == 'tool_calls' + ) { + for (const toolCall of delta.step_details.tool_calls) { + if (toolCall.index == this.#currentToolCallIndex) { + this._emit( + 'toolCallDelta', + toolCall, + accumulatedRunStep.step_details.tool_calls[toolCall.index] as ToolCall, + ); + } else { + if (this.#currentToolCall) { + this._emit('toolCallDone', this.#currentToolCall); + } + + this.#currentToolCallIndex = toolCall.index; + this.#currentToolCall = accumulatedRunStep.step_details.tool_calls[toolCall.index]; + if (this.#currentToolCall) this._emit('toolCallCreated', this.#currentToolCall); + } + } + } + + this._emit('runStepDelta', event.data.delta, accumulatedRunStep); + break; + case 'thread.run.step.completed': + case 'thread.run.step.failed': + case 'thread.run.step.cancelled': + case 'thread.run.step.expired': + this.#currentRunStepSnapshot = undefined; + const details = event.data.step_details; + if (details.type == 'tool_calls') { + if (this.#currentToolCall) { + this._emit('toolCallDone', this.#currentToolCall as ToolCall); + this.#currentToolCall = undefined; + } + } + this._emit('runStepDone', event.data, accumulatedRunStep); + break; + case 'thread.run.step.in_progress': + break; + } + } + + #handleEvent(this: AssistantStream, event: AssistantStreamEvent) { + this.#events.push(event); + this._emit('event', event); + } + + #accumulateRunStep(event: RunStepStreamEvent): Runs.RunStep { + switch (event.event) { + case 'thread.run.step.created': + this.#runStepSnapshots[event.data.id] = event.data; + return event.data; + + case 'thread.run.step.delta': + let snapshot = this.#runStepSnapshots[event.data.id] as Runs.RunStep; + if (!snapshot) { + throw Error('Received a RunStepDelta before creation of a snapshot'); + } + + let data = event.data; + + if (data.delta) { + const accumulated = AssistantStream.accumulateDelta(snapshot, data.delta) as Runs.RunStep; + this.#runStepSnapshots[event.data.id] = accumulated; + } + + return this.#runStepSnapshots[event.data.id] as Runs.RunStep; + + case 'thread.run.step.completed': + case 'thread.run.step.failed': + case 'thread.run.step.cancelled': + case 'thread.run.step.expired': + case 'thread.run.step.in_progress': + this.#runStepSnapshots[event.data.id] = event.data; + break; + } + + if (this.#runStepSnapshots[event.data.id]) return this.#runStepSnapshots[event.data.id] as Runs.RunStep; + throw new Error('No snapshot available'); + } + + #accumulateMessage( + event: AssistantStreamEvent, + snapshot: Message | undefined, + ): [Message, MessageContentDelta[]] { + let newContent: MessageContentDelta[] = []; + + switch (event.event) { + case 'thread.message.created': + //On creation the snapshot is just the initial message + return [event.data, newContent]; + + case 'thread.message.delta': + if (!snapshot) { + throw Error( + 'Received a delta with no existing snapshot (there should be one from message creation)', + ); + } + + let data = event.data; + + //If this delta does not have content, nothing to process + if (data.delta.content) { + for (const contentElement of data.delta.content) { + if (contentElement.index in snapshot.content) { + let currentContent = snapshot.content[contentElement.index]; + snapshot.content[contentElement.index] = this.#accumulateContent( + contentElement, + currentContent, + ); + } else { + snapshot.content[contentElement.index] = contentElement as MessageContent; + // This is a new element + newContent.push(contentElement); + } + } + } + + return [snapshot, newContent]; + + case 'thread.message.in_progress': + case 'thread.message.completed': + case 'thread.message.incomplete': + //No changes on other thread events + if (snapshot) { + return [snapshot, newContent]; + } else { + throw Error('Received thread message event with no existing snapshot'); + } + } + throw Error('Tried to accumulate a non-message event'); + } + + #accumulateContent( + contentElement: MessageContentDelta, + currentContent: MessageContent | undefined, + ): TextContentBlock | ImageFileContentBlock { + return AssistantStream.accumulateDelta(currentContent as unknown as Record, contentElement) as + | TextContentBlock + | ImageFileContentBlock; + } + + static accumulateDelta(acc: Record, delta: Record): Record { + for (const [key, deltaValue] of Object.entries(delta)) { + if (!acc.hasOwnProperty(key)) { + acc[key] = deltaValue; + continue; + } + + let accValue = acc[key]; + if (accValue === null || accValue === undefined) { + acc[key] = deltaValue; + continue; + } + + // We don't accumulate these special properties + if (key === 'index' || key === 'type') { + acc[key] = deltaValue; + continue; + } + + // Type-specific accumulation logic + if (typeof accValue === 'string' && typeof deltaValue === 'string') { + accValue += deltaValue; + } else if (typeof accValue === 'number' && typeof deltaValue === 'number') { + accValue += deltaValue; + } else if (isObj(accValue) && isObj(deltaValue)) { + accValue = this.accumulateDelta(accValue as Record, deltaValue as Record); + } else if (Array.isArray(accValue) && Array.isArray(deltaValue)) { + if (accValue.every((x) => typeof x === 'string' || typeof x === 'number')) { + accValue.push(...deltaValue); // Use spread syntax for efficient addition + continue; + } + + for (const deltaEntry of deltaValue) { + if (!isObj(deltaEntry)) { + throw new Error(`Expected array delta entry to be an object but got: ${deltaEntry}`); + } + + const index = deltaEntry['index']; + if (index == null) { + console.error(deltaEntry); + throw new Error('Expected array delta entry to have an `index` property'); + } + + if (typeof index !== 'number') { + throw new Error(`Expected array delta entry \`index\` property to be a number but got ${index}`); + } + + const accEntry = accValue[index]; + if (accEntry == null) { + accValue.push(deltaEntry); + } else { + accValue[index] = this.accumulateDelta(accEntry, deltaEntry); + } + } + continue; + } else { + throw Error(`Unhandled record type: ${key}, deltaValue: ${deltaValue}, accValue: ${accValue}`); + } + acc[key] = accValue; + } + + return acc; + } + + #handleRun(this: AssistantStream, event: RunStreamEvent) { + this.#currentRunSnapshot = event.data; + + switch (event.event) { + case 'thread.run.created': + break; + case 'thread.run.queued': + break; + case 'thread.run.in_progress': + break; + case 'thread.run.requires_action': + case 'thread.run.cancelled': + case 'thread.run.failed': + case 'thread.run.completed': + case 'thread.run.expired': + case 'thread.run.incomplete': + this.#finalRun = event.data; + if (this.#currentToolCall) { + this._emit('toolCallDone', this.#currentToolCall); + this.#currentToolCall = undefined; + } + break; + case 'thread.run.cancelling': + break; + } + } + + protected _addRun(run: Run): Run { + return run; + } + + protected async _threadAssistantStream( + params: ThreadCreateAndRunParamsBase, + thread: Threads, + options?: RequestOptions, + ): Promise { + return await this._createThreadAssistantStream(thread, params, options); + } + + protected async _runAssistantStream( + threadId: string, + runs: Runs, + params: RunCreateParamsBase, + options?: RequestOptions, + ): Promise { + return await this._createAssistantStream(runs, threadId, params, options); + } + + protected async _runToolAssistantStream( + runId: string, + runs: Runs, + params: RunSubmitToolOutputsParamsStream, + options?: RequestOptions, + ): Promise { + return await this._createToolAssistantStream(runs, runId, params, options); + } +} + +function assertNever(_x: never) {} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/ChatCompletionRunner.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/ChatCompletionRunner.ts new file mode 100644 index 0000000000000000000000000000000000000000..a5edaf7411a198aeb81d37a79139baea32e1631f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/ChatCompletionRunner.ts @@ -0,0 +1,54 @@ +import { + type ChatCompletionMessageParam, + type ChatCompletionCreateParamsNonStreaming, +} from '../resources/chat/completions'; +import { type BaseFunctionsArgs, RunnableTools } from './RunnableFunction'; +import { + AbstractChatCompletionRunner, + AbstractChatCompletionRunnerEvents, + RunnerOptions, +} from './AbstractChatCompletionRunner'; +import { isAssistantMessage } from './chatCompletionUtils'; +import OpenAI from '../index'; +import { AutoParseableTool } from '../lib/parser'; + +export interface ChatCompletionRunnerEvents extends AbstractChatCompletionRunnerEvents { + content: (content: string) => void; +} + +export type ChatCompletionToolRunnerParams = Omit< + ChatCompletionCreateParamsNonStreaming, + 'tools' +> & { + tools: RunnableTools | AutoParseableTool[]; +}; + +export class ChatCompletionRunner extends AbstractChatCompletionRunner< + ChatCompletionRunnerEvents, + ParsedT +> { + static runTools( + client: OpenAI, + params: ChatCompletionToolRunnerParams, + options?: RunnerOptions, + ): ChatCompletionRunner { + const runner = new ChatCompletionRunner(); + const opts = { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runTools' }, + }; + runner._run(() => runner._runTools(client, params, opts)); + return runner; + } + + override _addMessage( + this: ChatCompletionRunner, + message: ChatCompletionMessageParam, + emit: boolean = true, + ) { + super._addMessage(message, emit); + if (isAssistantMessage(message) && message.content) { + this._emit('content', message.content as string); + } + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/ChatCompletionStream.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/ChatCompletionStream.ts new file mode 100644 index 0000000000000000000000000000000000000000..6dc5bc6c428930f7c95fd3fdbbb56e79807ec130 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/ChatCompletionStream.ts @@ -0,0 +1,872 @@ +import { partialParse } from '../_vendor/partial-json-parser/parser'; +import { + APIUserAbortError, + ContentFilterFinishReasonError, + LengthFinishReasonError, + OpenAIError, +} from '../error'; +import OpenAI from '../index'; +import { RequestOptions } from '../internal/request-options'; +import { type ReadableStream } from '../internal/shim-types'; +import { + AutoParseableResponseFormat, + hasAutoParseableInput, + isAutoParsableResponseFormat, + isAutoParsableTool, + isChatCompletionFunctionTool, + maybeParseChatCompletion, + shouldParseToolCall, +} from '../lib/parser'; +import { ChatCompletionFunctionTool, ParsedChatCompletion } from '../resources/chat/completions'; +import { + ChatCompletionTokenLogprob, + type ChatCompletion, + type ChatCompletionChunk, + type ChatCompletionCreateParams, + type ChatCompletionCreateParamsBase, + type ChatCompletionCreateParamsStreaming, + type ChatCompletionRole, +} from '../resources/chat/completions/completions'; +import { Stream } from '../streaming'; +import { + AbstractChatCompletionRunner, + type AbstractChatCompletionRunnerEvents, +} from './AbstractChatCompletionRunner'; + +export interface ContentDeltaEvent { + delta: string; + snapshot: string; + parsed: unknown | null; +} + +export interface ContentDoneEvent { + content: string; + parsed: ParsedT | null; +} + +export interface RefusalDeltaEvent { + delta: string; + snapshot: string; +} + +export interface RefusalDoneEvent { + refusal: string; +} + +export interface FunctionToolCallArgumentsDeltaEvent { + name: string; + + index: number; + + arguments: string; + + parsed_arguments: unknown; + + arguments_delta: string; +} + +export interface FunctionToolCallArgumentsDoneEvent { + name: string; + + index: number; + + arguments: string; + + parsed_arguments: unknown; +} + +export interface LogProbsContentDeltaEvent { + content: Array; + snapshot: Array; +} + +export interface LogProbsContentDoneEvent { + content: Array; +} + +export interface LogProbsRefusalDeltaEvent { + refusal: Array; + snapshot: Array; +} + +export interface LogProbsRefusalDoneEvent { + refusal: Array; +} + +export interface ChatCompletionStreamEvents extends AbstractChatCompletionRunnerEvents { + content: (contentDelta: string, contentSnapshot: string) => void; + chunk: (chunk: ChatCompletionChunk, snapshot: ChatCompletionSnapshot) => void; + + 'content.delta': (props: ContentDeltaEvent) => void; + 'content.done': (props: ContentDoneEvent) => void; + + 'refusal.delta': (props: RefusalDeltaEvent) => void; + 'refusal.done': (props: RefusalDoneEvent) => void; + + 'tool_calls.function.arguments.delta': (props: FunctionToolCallArgumentsDeltaEvent) => void; + 'tool_calls.function.arguments.done': (props: FunctionToolCallArgumentsDoneEvent) => void; + + 'logprobs.content.delta': (props: LogProbsContentDeltaEvent) => void; + 'logprobs.content.done': (props: LogProbsContentDoneEvent) => void; + + 'logprobs.refusal.delta': (props: LogProbsRefusalDeltaEvent) => void; + 'logprobs.refusal.done': (props: LogProbsRefusalDoneEvent) => void; +} + +export type ChatCompletionStreamParams = Omit & { + stream?: true; +}; + +interface ChoiceEventState { + content_done: boolean; + refusal_done: boolean; + logprobs_content_done: boolean; + logprobs_refusal_done: boolean; + current_tool_call_index: number | null; + done_tool_calls: Set; +} + +export class ChatCompletionStream + extends AbstractChatCompletionRunner, ParsedT> + implements AsyncIterable +{ + #params: ChatCompletionCreateParams | null; + #choiceEventStates: ChoiceEventState[]; + #currentChatCompletionSnapshot: ChatCompletionSnapshot | undefined; + + constructor(params: ChatCompletionCreateParams | null) { + super(); + this.#params = params; + this.#choiceEventStates = []; + } + + get currentChatCompletionSnapshot(): ChatCompletionSnapshot | undefined { + return this.#currentChatCompletionSnapshot; + } + + /** + * Intended for use on the frontend, consuming a stream produced with + * `.toReadableStream()` on the backend. + * + * Note that messages sent to the model do not appear in `.on('message')` + * in this context. + */ + static fromReadableStream(stream: ReadableStream): ChatCompletionStream { + const runner = new ChatCompletionStream(null); + runner._run(() => runner._fromReadableStream(stream)); + return runner; + } + + static createChatCompletion( + client: OpenAI, + params: ChatCompletionStreamParams, + options?: RequestOptions, + ): ChatCompletionStream { + const runner = new ChatCompletionStream(params as ChatCompletionCreateParamsStreaming); + runner._run(() => + runner._runChatCompletion( + client, + { ...params, stream: true }, + { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } }, + ), + ); + return runner; + } + + #beginRequest() { + if (this.ended) return; + this.#currentChatCompletionSnapshot = undefined; + } + + #getChoiceEventState(choice: ChatCompletionSnapshot.Choice): ChoiceEventState { + let state = this.#choiceEventStates[choice.index]; + if (state) { + return state; + } + + state = { + content_done: false, + refusal_done: false, + logprobs_content_done: false, + logprobs_refusal_done: false, + done_tool_calls: new Set(), + current_tool_call_index: null, + }; + this.#choiceEventStates[choice.index] = state; + return state; + } + + #addChunk(this: ChatCompletionStream, chunk: ChatCompletionChunk) { + if (this.ended) return; + + const completion = this.#accumulateChatCompletion(chunk); + this._emit('chunk', chunk, completion); + + for (const choice of chunk.choices) { + const choiceSnapshot = completion.choices[choice.index]!; + + if ( + choice.delta.content != null && + choiceSnapshot.message?.role === 'assistant' && + choiceSnapshot.message?.content + ) { + this._emit('content', choice.delta.content, choiceSnapshot.message.content); + this._emit('content.delta', { + delta: choice.delta.content, + snapshot: choiceSnapshot.message.content, + parsed: choiceSnapshot.message.parsed, + }); + } + + if ( + choice.delta.refusal != null && + choiceSnapshot.message?.role === 'assistant' && + choiceSnapshot.message?.refusal + ) { + this._emit('refusal.delta', { + delta: choice.delta.refusal, + snapshot: choiceSnapshot.message.refusal, + }); + } + + if (choice.logprobs?.content != null && choiceSnapshot.message?.role === 'assistant') { + this._emit('logprobs.content.delta', { + content: choice.logprobs?.content, + snapshot: choiceSnapshot.logprobs?.content ?? [], + }); + } + + if (choice.logprobs?.refusal != null && choiceSnapshot.message?.role === 'assistant') { + this._emit('logprobs.refusal.delta', { + refusal: choice.logprobs?.refusal, + snapshot: choiceSnapshot.logprobs?.refusal ?? [], + }); + } + + const state = this.#getChoiceEventState(choiceSnapshot); + + if (choiceSnapshot.finish_reason) { + this.#emitContentDoneEvents(choiceSnapshot); + + if (state.current_tool_call_index != null) { + this.#emitToolCallDoneEvent(choiceSnapshot, state.current_tool_call_index); + } + } + + for (const toolCall of choice.delta.tool_calls ?? []) { + if (state.current_tool_call_index !== toolCall.index) { + this.#emitContentDoneEvents(choiceSnapshot); + + // new tool call started, the previous one is done + if (state.current_tool_call_index != null) { + this.#emitToolCallDoneEvent(choiceSnapshot, state.current_tool_call_index); + } + } + + state.current_tool_call_index = toolCall.index; + } + + for (const toolCallDelta of choice.delta.tool_calls ?? []) { + const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallDelta.index]; + if (!toolCallSnapshot?.type) { + continue; + } + + if (toolCallSnapshot?.type === 'function') { + this._emit('tool_calls.function.arguments.delta', { + name: toolCallSnapshot.function?.name, + index: toolCallDelta.index, + arguments: toolCallSnapshot.function.arguments, + parsed_arguments: toolCallSnapshot.function.parsed_arguments, + arguments_delta: toolCallDelta.function?.arguments ?? '', + }); + } else { + assertNever(toolCallSnapshot?.type); + } + } + } + } + + #emitToolCallDoneEvent(choiceSnapshot: ChatCompletionSnapshot.Choice, toolCallIndex: number) { + const state = this.#getChoiceEventState(choiceSnapshot); + if (state.done_tool_calls.has(toolCallIndex)) { + // we've already fired the done event + return; + } + + const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallIndex]; + if (!toolCallSnapshot) { + throw new Error('no tool call snapshot'); + } + if (!toolCallSnapshot.type) { + throw new Error('tool call snapshot missing `type`'); + } + + if (toolCallSnapshot.type === 'function') { + const inputTool = this.#params?.tools?.find( + (tool) => isChatCompletionFunctionTool(tool) && tool.function.name === toolCallSnapshot.function.name, + ) as ChatCompletionFunctionTool | undefined; // TS doesn't narrow based on isChatCompletionTool + + this._emit('tool_calls.function.arguments.done', { + name: toolCallSnapshot.function.name, + index: toolCallIndex, + arguments: toolCallSnapshot.function.arguments, + parsed_arguments: + isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCallSnapshot.function.arguments) + : inputTool?.function.strict ? JSON.parse(toolCallSnapshot.function.arguments) + : null, + }); + } else { + assertNever(toolCallSnapshot.type); + } + } + + #emitContentDoneEvents(choiceSnapshot: ChatCompletionSnapshot.Choice) { + const state = this.#getChoiceEventState(choiceSnapshot); + + if (choiceSnapshot.message.content && !state.content_done) { + state.content_done = true; + + const responseFormat = this.#getAutoParseableResponseFormat(); + + this._emit('content.done', { + content: choiceSnapshot.message.content, + parsed: responseFormat ? responseFormat.$parseRaw(choiceSnapshot.message.content) : (null as any), + }); + } + + if (choiceSnapshot.message.refusal && !state.refusal_done) { + state.refusal_done = true; + + this._emit('refusal.done', { refusal: choiceSnapshot.message.refusal }); + } + + if (choiceSnapshot.logprobs?.content && !state.logprobs_content_done) { + state.logprobs_content_done = true; + + this._emit('logprobs.content.done', { content: choiceSnapshot.logprobs.content }); + } + + if (choiceSnapshot.logprobs?.refusal && !state.logprobs_refusal_done) { + state.logprobs_refusal_done = true; + + this._emit('logprobs.refusal.done', { refusal: choiceSnapshot.logprobs.refusal }); + } + } + + #endRequest(): ParsedChatCompletion { + if (this.ended) { + throw new OpenAIError(`stream has ended, this shouldn't happen`); + } + const snapshot = this.#currentChatCompletionSnapshot; + if (!snapshot) { + throw new OpenAIError(`request ended without sending any chunks`); + } + this.#currentChatCompletionSnapshot = undefined; + this.#choiceEventStates = []; + return finalizeChatCompletion(snapshot, this.#params); + } + + protected override async _createChatCompletion( + client: OpenAI, + params: ChatCompletionCreateParams, + options?: RequestOptions, + ): Promise> { + super._createChatCompletion; + const signal = options?.signal; + if (signal) { + if (signal.aborted) this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + this.#beginRequest(); + + const stream = await client.chat.completions.create( + { ...params, stream: true }, + { ...options, signal: this.controller.signal }, + ); + this._connected(); + for await (const chunk of stream) { + this.#addChunk(chunk); + } + if (stream.controller.signal?.aborted) { + throw new APIUserAbortError(); + } + return this._addChatCompletion(this.#endRequest()); + } + + protected async _fromReadableStream( + readableStream: ReadableStream, + options?: RequestOptions, + ): Promise { + const signal = options?.signal; + if (signal) { + if (signal.aborted) this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + this.#beginRequest(); + this._connected(); + const stream = Stream.fromReadableStream(readableStream, this.controller); + let chatId; + for await (const chunk of stream) { + if (chatId && chatId !== chunk.id) { + // A new request has been made. + this._addChatCompletion(this.#endRequest()); + } + + this.#addChunk(chunk); + chatId = chunk.id; + } + if (stream.controller.signal?.aborted) { + throw new APIUserAbortError(); + } + return this._addChatCompletion(this.#endRequest()); + } + + #getAutoParseableResponseFormat(): AutoParseableResponseFormat | null { + const responseFormat = this.#params?.response_format; + if (isAutoParsableResponseFormat(responseFormat)) { + return responseFormat; + } + + return null; + } + + #accumulateChatCompletion(chunk: ChatCompletionChunk): ChatCompletionSnapshot { + let snapshot = this.#currentChatCompletionSnapshot; + const { choices, ...rest } = chunk; + if (!snapshot) { + snapshot = this.#currentChatCompletionSnapshot = { + ...rest, + choices: [], + }; + } else { + Object.assign(snapshot, rest); + } + + for (const { delta, finish_reason, index, logprobs = null, ...other } of chunk.choices) { + let choice = snapshot.choices[index]; + if (!choice) { + choice = snapshot.choices[index] = { finish_reason, index, message: {}, logprobs, ...other }; + } + + if (logprobs) { + if (!choice.logprobs) { + choice.logprobs = Object.assign({}, logprobs); + } else { + const { content, refusal, ...rest } = logprobs; + assertIsEmpty(rest); + Object.assign(choice.logprobs, rest); + + if (content) { + choice.logprobs.content ??= []; + choice.logprobs.content.push(...content); + } + + if (refusal) { + choice.logprobs.refusal ??= []; + choice.logprobs.refusal.push(...refusal); + } + } + } + + if (finish_reason) { + choice.finish_reason = finish_reason; + + if (this.#params && hasAutoParseableInput(this.#params)) { + if (finish_reason === 'length') { + throw new LengthFinishReasonError(); + } + + if (finish_reason === 'content_filter') { + throw new ContentFilterFinishReasonError(); + } + } + } + + Object.assign(choice, other); + + if (!delta) continue; // Shouldn't happen; just in case. + + const { content, refusal, function_call, role, tool_calls, ...rest } = delta; + assertIsEmpty(rest); + Object.assign(choice.message, rest); + + if (refusal) { + choice.message.refusal = (choice.message.refusal || '') + refusal; + } + + if (role) choice.message.role = role; + if (function_call) { + if (!choice.message.function_call) { + choice.message.function_call = function_call; + } else { + if (function_call.name) choice.message.function_call.name = function_call.name; + if (function_call.arguments) { + choice.message.function_call.arguments ??= ''; + choice.message.function_call.arguments += function_call.arguments; + } + } + } + if (content) { + choice.message.content = (choice.message.content || '') + content; + + if (!choice.message.refusal && this.#getAutoParseableResponseFormat()) { + choice.message.parsed = partialParse(choice.message.content); + } + } + + if (tool_calls) { + if (!choice.message.tool_calls) choice.message.tool_calls = []; + + for (const { index, id, type, function: fn, ...rest } of tool_calls) { + const tool_call = (choice.message.tool_calls[index] ??= + {} as ChatCompletionSnapshot.Choice.Message.ToolCall); + Object.assign(tool_call, rest); + if (id) tool_call.id = id; + if (type) tool_call.type = type; + if (fn) tool_call.function ??= { name: fn.name ?? '', arguments: '' }; + if (fn?.name) tool_call.function!.name = fn.name; + if (fn?.arguments) { + tool_call.function!.arguments += fn.arguments; + + if (shouldParseToolCall(this.#params, tool_call)) { + tool_call.function!.parsed_arguments = partialParse(tool_call.function!.arguments); + } + } + } + } + } + return snapshot; + } + + [Symbol.asyncIterator](this: ChatCompletionStream): AsyncIterator { + const pushQueue: ChatCompletionChunk[] = []; + const readQueue: { + resolve: (chunk: ChatCompletionChunk | undefined) => void; + reject: (err: unknown) => void; + }[] = []; + let done = false; + + this.on('chunk', (chunk) => { + const reader = readQueue.shift(); + if (reader) { + reader.resolve(chunk); + } else { + pushQueue.push(chunk); + } + }); + + 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 (): Promise> => { + 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(): ReadableStream { + const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller); + return stream.toReadableStream(); + } +} + +function finalizeChatCompletion( + snapshot: ChatCompletionSnapshot, + params: ChatCompletionCreateParams | null, +): ParsedChatCompletion { + const { id, choices, created, model, system_fingerprint, ...rest } = snapshot; + const completion: ChatCompletion = { + ...rest, + id, + choices: choices.map( + ({ message, finish_reason, index, logprobs, ...choiceRest }): ChatCompletion.Choice => { + if (!finish_reason) { + throw new OpenAIError(`missing finish_reason for choice ${index}`); + } + + const { content = null, function_call, tool_calls, ...messageRest } = message; + const role = message.role as 'assistant'; // this is what we expect; in theory it could be different which would make our types a slight lie but would be fine. + if (!role) { + throw new OpenAIError(`missing role for choice ${index}`); + } + + if (function_call) { + const { arguments: args, name } = function_call; + if (args == null) { + throw new OpenAIError(`missing function_call.arguments for choice ${index}`); + } + + if (!name) { + throw new OpenAIError(`missing function_call.name for choice ${index}`); + } + + return { + ...choiceRest, + message: { + content, + function_call: { arguments: args, name }, + role, + refusal: message.refusal ?? null, + }, + finish_reason, + index, + logprobs, + }; + } + + if (tool_calls) { + return { + ...choiceRest, + index, + finish_reason, + logprobs, + message: { + ...messageRest, + role, + content, + refusal: message.refusal ?? null, + tool_calls: tool_calls.map((tool_call, i) => { + const { function: fn, type, id, ...toolRest } = tool_call; + const { arguments: args, name, ...fnRest } = fn || {}; + if (id == null) { + throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].id\n${str(snapshot)}`); + } + if (type == null) { + throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].type\n${str(snapshot)}`); + } + if (name == null) { + throw new OpenAIError( + `missing choices[${index}].tool_calls[${i}].function.name\n${str(snapshot)}`, + ); + } + if (args == null) { + throw new OpenAIError( + `missing choices[${index}].tool_calls[${i}].function.arguments\n${str(snapshot)}`, + ); + } + + return { ...toolRest, id, type, function: { ...fnRest, name, arguments: args } }; + }), + }, + }; + } + return { + ...choiceRest, + message: { ...messageRest, content, role, refusal: message.refusal ?? null }, + finish_reason, + index, + logprobs, + }; + }, + ), + created, + model, + object: 'chat.completion', + ...(system_fingerprint ? { system_fingerprint } : {}), + }; + + return maybeParseChatCompletion(completion, params); +} + +function str(x: unknown) { + return JSON.stringify(x); +} + +/** + * Represents a streamed chunk of a chat completion response returned by model, + * based on the provided input. + */ +export interface ChatCompletionSnapshot { + /** + * A unique identifier for the chat completion. + */ + id: string; + + /** + * A list of chat completion choices. Can be more than one if `n` is greater + * than 1. + */ + choices: Array; + + /** + * The Unix timestamp (in seconds) of when the chat completion was created. + */ + created: number; + + /** + * The model to generate the completion. + */ + model: string; + + // Note we do not include an "object" type on the snapshot, + // because the object is not a valid "chat.completion" until finalized. + // object: 'chat.completion'; + + /** + * This fingerprint represents the backend configuration that the model runs with. + * + * Can be used in conjunction with the `seed` request parameter to understand when + * backend changes have been made that might impact determinism. + */ + system_fingerprint?: string; +} + +export namespace ChatCompletionSnapshot { + export interface Choice { + /** + * A chat completion delta generated by streamed model responses. + */ + message: Choice.Message; + + /** + * The reason the model stopped generating tokens. This will be `stop` if the model + * hit a natural stop point or a provided stop sequence, `length` if the maximum + * number of tokens specified in the request was reached, `content_filter` if + * content was omitted due to a flag from our content filters, or `function_call` + * if the model called a function. + */ + finish_reason: ChatCompletion.Choice['finish_reason'] | null; + + /** + * Log probability information for the choice. + */ + logprobs: ChatCompletion.Choice.Logprobs | null; + + /** + * The index of the choice in the list of choices. + */ + index: number; + } + + export namespace Choice { + /** + * A chat completion delta generated by streamed model responses. + */ + export interface Message { + /** + * The contents of the chunk message. + */ + content?: string | null; + + refusal?: string | null; + + parsed?: unknown | null; + + /** + * The name and arguments of a function that should be called, as generated by the + * model. + */ + function_call?: Message.FunctionCall; + + tool_calls?: Array; + + /** + * The role of the author of this message. + */ + role?: ChatCompletionRole; + } + + export namespace Message { + export interface ToolCall { + /** + * The ID of the tool call. + */ + id: string; + + function: ToolCall.Function; + + /** + * The type of the tool. + */ + type: 'function'; + } + + export namespace ToolCall { + export interface Function { + /** + * The arguments to call the function with, as generated by the model in JSON + * format. Note that the model does not always generate valid JSON, and may + * hallucinate parameters not defined by your function schema. Validate the + * arguments in your code before calling your function. + */ + arguments: string; + + parsed_arguments?: unknown; + + /** + * The name of the function to call. + */ + name: string; + } + } + + /** + * The name and arguments of a function that should be called, as generated by the + * model. + */ + export interface FunctionCall { + /** + * The arguments to call the function with, as generated by the model in JSON + * format. Note that the model does not always generate valid JSON, and may + * hallucinate parameters not defined by your function schema. Validate the + * arguments in your code before calling your function. + */ + arguments?: string; + + /** + * The name of the function to call. + */ + name?: string; + } + } + } +} + +type AssertIsEmpty = keyof T extends never ? T : never; + +/** + * Ensures the given argument is an empty object, useful for + * asserting that all known properties on an object have been + * destructured. + */ +function assertIsEmpty(obj: AssertIsEmpty): asserts obj is AssertIsEmpty { + return; +} + +function assertNever(_x: never) {} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/ChatCompletionStreamingRunner.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/ChatCompletionStreamingRunner.ts new file mode 100644 index 0000000000000000000000000000000000000000..eb8fcc357946b944bb947a1e4d7a5abee6179066 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/ChatCompletionStreamingRunner.ts @@ -0,0 +1,50 @@ +import { + type ChatCompletionChunk, + type ChatCompletionCreateParamsStreaming, +} from '../resources/chat/completions'; +import { RunnerOptions, type AbstractChatCompletionRunnerEvents } from './AbstractChatCompletionRunner'; +import { type ReadableStream } from '../internal/shim-types'; +import { RunnableTools, type BaseFunctionsArgs } from './RunnableFunction'; +import { ChatCompletionSnapshot, ChatCompletionStream } from './ChatCompletionStream'; +import OpenAI from '../index'; +import { AutoParseableTool } from '../lib/parser'; + +export interface ChatCompletionStreamEvents extends AbstractChatCompletionRunnerEvents { + content: (contentDelta: string, contentSnapshot: string) => void; + chunk: (chunk: ChatCompletionChunk, snapshot: ChatCompletionSnapshot) => void; +} + +export type ChatCompletionStreamingToolRunnerParams = Omit< + ChatCompletionCreateParamsStreaming, + 'tools' +> & { + tools: RunnableTools | AutoParseableTool[]; +}; + +export class ChatCompletionStreamingRunner + extends ChatCompletionStream + implements AsyncIterable +{ + static override fromReadableStream(stream: ReadableStream): ChatCompletionStreamingRunner { + const runner = new ChatCompletionStreamingRunner(null); + runner._run(() => runner._fromReadableStream(stream)); + return runner; + } + + static runTools( + client: OpenAI, + params: ChatCompletionStreamingToolRunnerParams, + options?: RunnerOptions, + ): ChatCompletionStreamingRunner { + const runner = new ChatCompletionStreamingRunner( + // @ts-expect-error TODO these types are incompatible + params, + ); + const opts = { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runTools' }, + }; + runner._run(() => runner._runTools(client, params, opts)); + return runner; + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/EventEmitter.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/EventEmitter.ts new file mode 100644 index 0000000000000000000000000000000000000000..9adeebdc397daf49339704a4bd1cb3591f43a3d4 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/EventEmitter.ts @@ -0,0 +1,98 @@ +type EventListener = Events[EventType]; + +type EventListeners = Array<{ + listener: EventListener; + once?: boolean; +}>; + +export type EventParameters = { + [Event in EventType]: EventListener extends (...args: infer P) => any ? P : never; +}[EventType]; + +export class EventEmitter any>> { + #listeners: { + [Event in keyof EventTypes]?: EventListeners; + } = {}; + + /** + * 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, so that calls can be chained + */ + on(event: Event, listener: EventListener): this { + const listeners: EventListeners = + this.#listeners[event] || (this.#listeners[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, so that calls can be chained + */ + off(event: Event, listener: EventListener): this { + const listeners = this.#listeners[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, so that calls can be chained + */ + once(event: Event, listener: EventListener): this { + const listeners: EventListeners = + this.#listeners[event] || (this.#listeners[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: Event, + ): Promise< + EventParameters extends [infer Param] ? Param + : EventParameters extends [] ? void + : EventParameters + > { + return new Promise((resolve, reject) => { + // TODO: handle errors + this.once(event, resolve as any); + }); + } + + protected _emit( + this: EventEmitter, + event: Event, + ...args: EventParameters + ) { + const listeners: EventListeners | undefined = this.#listeners[event]; + if (listeners) { + this.#listeners[event] = listeners.filter((l) => !l.once) as any; + listeners.forEach(({ listener }: any) => listener(...(args as any))); + } + } + + protected _hasListener(event: keyof EventTypes): boolean { + const listeners = this.#listeners[event]; + return listeners && listeners.length > 0; + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/EventStream.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/EventStream.ts new file mode 100644 index 0000000000000000000000000000000000000000..d3f485e9d08fda69c56605e23a08f0a6547f3df2 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/EventStream.ts @@ -0,0 +1,239 @@ +import { APIUserAbortError, OpenAIError } from '../error'; + +export class EventStream { + controller: AbortController = new AbortController(); + + #connectedPromise: Promise; + #resolveConnectedPromise: () => void = () => {}; + #rejectConnectedPromise: (error: OpenAIError) => void = () => {}; + + #endPromise: Promise; + #resolveEndPromise: () => void = () => {}; + #rejectEndPromise: (error: OpenAIError) => void = () => {}; + + #listeners: { + [Event in keyof EventTypes]?: EventListeners; + } = {}; + + #ended = false; + #errored = false; + #aborted = false; + #catchingPromiseCreated = false; + + constructor() { + this.#connectedPromise = new Promise((resolve, reject) => { + this.#resolveConnectedPromise = resolve; + this.#rejectConnectedPromise = reject; + }); + + this.#endPromise = new Promise((resolve, reject) => { + this.#resolveEndPromise = resolve; + this.#rejectEndPromise = reject; + }); + + // 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. + this.#connectedPromise.catch(() => {}); + this.#endPromise.catch(() => {}); + } + + protected _run(this: EventStream, executor: () => Promise) { + // Unfortunately if we call `executor()` immediately we get runtime errors about + // references to `this` before the `super()` constructor call returns. + setTimeout(() => { + executor().then(() => { + this._emitFinal(); + this._emit('end'); + }, this.#handleError.bind(this)); + }, 0); + } + + protected _connected(this: EventStream) { + if (this.ended) return; + this.#resolveConnectedPromise(); + this._emit('connect'); + } + + get ended(): boolean { + return this.#ended; + } + + get errored(): boolean { + return this.#errored; + } + + get aborted(): boolean { + return this.#aborted; + } + + abort() { + this.controller.abort(); + } + + /** + * Adds the listener function to the end of the listeners array for the event. + * No checks are made to see if the listener has already been added. Multiple calls passing + * the same combination of event and listener will result in the listener being added, and + * called, multiple times. + * @returns this ChatCompletionStream, so that calls can be chained + */ + on(event: Event, listener: EventListener): this { + const listeners: EventListeners = + this.#listeners[event] || (this.#listeners[event] = []); + listeners.push({ listener }); + return this; + } + + /** + * Removes the specified listener from the listener array for the event. + * off() will remove, at most, one instance of a listener from the listener array. If any single + * listener has been added multiple times to the listener array for the specified event, then + * off() must be called multiple times to remove each instance. + * @returns this ChatCompletionStream, so that calls can be chained + */ + off(event: Event, listener: EventListener): this { + const listeners = this.#listeners[event]; + if (!listeners) return this; + const index = listeners.findIndex((l) => l.listener === listener); + if (index >= 0) listeners.splice(index, 1); + return this; + } + + /** + * Adds a one-time listener function for the event. The next time the event is triggered, + * this listener is removed and then invoked. + * @returns this ChatCompletionStream, so that calls can be chained + */ + once(event: Event, listener: EventListener): this { + const listeners: EventListeners = + this.#listeners[event] || (this.#listeners[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: Event, + ): Promise< + EventParameters extends [infer Param] ? Param + : EventParameters extends [] ? void + : EventParameters + > { + return new Promise((resolve, reject) => { + this.#catchingPromiseCreated = true; + if (event !== 'error') this.once('error', reject); + this.once(event, resolve as any); + }); + } + + async done(): Promise { + this.#catchingPromiseCreated = true; + await this.#endPromise; + } + + #handleError(this: EventStream, error: unknown) { + this.#errored = true; + if (error instanceof Error && error.name === 'AbortError') { + error = new APIUserAbortError(); + } + if (error instanceof APIUserAbortError) { + this.#aborted = true; + return this._emit('abort', error); + } + if (error instanceof OpenAIError) { + return this._emit('error', error); + } + if (error instanceof Error) { + const openAIError: OpenAIError = new OpenAIError(error.message); + // @ts-ignore + openAIError.cause = error; + return this._emit('error', openAIError); + } + return this._emit('error', new OpenAIError(String(error))); + } + + _emit(event: Event, ...args: EventParameters): void; + _emit(event: Event, ...args: EventParameters): void; + _emit( + this: EventStream, + event: Event, + ...args: EventParameters + ) { + // make sure we don't emit any events after end + if (this.#ended) { + return; + } + + if (event === 'end') { + this.#ended = true; + this.#resolveEndPromise(); + } + + const listeners: EventListeners | undefined = this.#listeners[event]; + if (listeners) { + this.#listeners[event] = listeners.filter((l) => !l.once) as any; + listeners.forEach(({ listener }: any) => listener(...(args as any))); + } + + if (event === 'abort') { + const error = args[0] as APIUserAbortError; + if (!this.#catchingPromiseCreated && !listeners?.length) { + Promise.reject(error); + } + this.#rejectConnectedPromise(error); + this.#rejectEndPromise(error); + this._emit('end'); + return; + } + + if (event === 'error') { + // NOTE: _emit('error', error) should only be called from #handleError(). + + const error = args[0] as OpenAIError; + if (!this.#catchingPromiseCreated && !listeners?.length) { + // Trigger an unhandled rejection if the user hasn't registered any error handlers. + // If you are seeing stack traces here, make sure to handle errors via either: + // - runner.on('error', () => ...) + // - await runner.done() + // - await runner.finalChatCompletion() + // - etc. + Promise.reject(error); + } + this.#rejectConnectedPromise(error); + this.#rejectEndPromise(error); + this._emit('end'); + } + } + + protected _emitFinal(): void {} +} + +type EventListener = Events[EventType]; + +type EventListeners = Array<{ + listener: EventListener; + once?: boolean; +}>; + +export type EventParameters = { + [Event in EventType]: EventListener extends (...args: infer P) => any ? P : never; +}[EventType]; + +export interface BaseEvents { + connect: () => void; + error: (error: OpenAIError) => void; + abort: (error: APIUserAbortError) => void; + end: () => void; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/ResponsesParser.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/ResponsesParser.ts new file mode 100644 index 0000000000000000000000000000000000000000..50a078ee9c758a087348e3014e5f2de8d6805479 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/ResponsesParser.ts @@ -0,0 +1,265 @@ +import { OpenAIError } from '../error'; +import type { ChatCompletionTool } from '../resources/chat/completions'; +import { + ResponseTextConfig, + type FunctionTool, + type ParsedContent, + type ParsedResponse, + type ParsedResponseFunctionToolCall, + type ParsedResponseOutputItem, + type Response, + type ResponseCreateParamsBase, + type ResponseCreateParamsNonStreaming, + type ResponseFunctionToolCall, + type Tool, +} from '../resources/responses/responses'; +import { type AutoParseableTextFormat, isAutoParsableResponseFormat } from '../lib/parser'; + +export type ParseableToolsParams = Array | ChatCompletionTool | null; + +export type ResponseCreateParamsWithTools = ResponseCreateParamsBase & { + tools?: ParseableToolsParams; +}; + +type TextConfigParams = { text?: ResponseTextConfig }; + +export type ExtractParsedContentFromParams = + NonNullable['format'] extends AutoParseableTextFormat ? P : null; + +export function maybeParseResponse< + Params extends ResponseCreateParamsBase | null, + ParsedT = Params extends null ? null : ExtractParsedContentFromParams>, +>(response: Response, params: Params): ParsedResponse { + if (!params || !hasAutoParseableInput(params)) { + return { + ...response, + output_parsed: null, + output: response.output.map((item) => { + if (item.type === 'function_call') { + return { + ...item, + parsed_arguments: null, + }; + } + + if (item.type === 'message') { + return { + ...item, + content: item.content.map((content) => ({ + ...content, + parsed: null, + })), + }; + } else { + return item; + } + }), + }; + } + + return parseResponse(response, params); +} + +export function parseResponse< + Params extends ResponseCreateParamsBase, + ParsedT = ExtractParsedContentFromParams, +>(response: Response, params: Params): ParsedResponse { + const output: Array> = response.output.map( + (item): ParsedResponseOutputItem => { + if (item.type === 'function_call') { + return { + ...item, + parsed_arguments: parseToolCall(params, item), + }; + } + if (item.type === 'message') { + const content: Array> = item.content.map((content) => { + if (content.type === 'output_text') { + return { + ...content, + parsed: parseTextFormat(params, content.text), + }; + } + + return content; + }); + + return { + ...item, + content, + }; + } + + return item; + }, + ); + + const parsed: Omit, 'output_parsed'> = Object.assign({}, response, { output }); + if (!Object.getOwnPropertyDescriptor(response, 'output_text')) { + addOutputText(parsed); + } + + Object.defineProperty(parsed, 'output_parsed', { + enumerable: true, + get() { + for (const output of parsed.output) { + if (output.type !== 'message') { + continue; + } + + for (const content of output.content) { + if (content.type === 'output_text' && content.parsed !== null) { + return content.parsed; + } + } + } + + return null; + }, + }); + + return parsed as ParsedResponse; +} + +function parseTextFormat< + Params extends ResponseCreateParamsBase, + ParsedT = ExtractParsedContentFromParams, +>(params: Params, content: string): ParsedT | null { + if (params.text?.format?.type !== 'json_schema') { + return null; + } + + if ('$parseRaw' in params.text?.format) { + const text_format = params.text?.format as unknown as AutoParseableTextFormat; + return text_format.$parseRaw(content); + } + + return JSON.parse(content); +} + +export function hasAutoParseableInput(params: ResponseCreateParamsWithTools): boolean { + if (isAutoParsableResponseFormat(params.text?.format)) { + return true; + } + + return false; +} + +type ToolOptions = { + name: string; + arguments: any; + function?: ((args: any) => any) | undefined; +}; + +export type AutoParseableResponseTool< + OptionsT extends ToolOptions, + HasFunction = OptionsT['function'] extends Function ? true : false, +> = FunctionTool & { + __arguments: OptionsT['arguments']; // type-level only + __name: OptionsT['name']; // type-level only + + $brand: 'auto-parseable-tool'; + $callback: ((args: OptionsT['arguments']) => any) | undefined; + $parseRaw(args: string): OptionsT['arguments']; +}; + +export function makeParseableResponseTool( + tool: FunctionTool, + { + parser, + callback, + }: { + parser: (content: string) => OptionsT['arguments']; + callback: ((args: any) => any) | undefined; + }, +): AutoParseableResponseTool { + const obj = { ...tool }; + + Object.defineProperties(obj, { + $brand: { + value: 'auto-parseable-tool', + enumerable: false, + }, + $parseRaw: { + value: parser, + enumerable: false, + }, + $callback: { + value: callback, + enumerable: false, + }, + }); + + return obj as AutoParseableResponseTool; +} + +export function isAutoParsableTool(tool: any): tool is AutoParseableResponseTool { + return tool?.['$brand'] === 'auto-parseable-tool'; +} + +function getInputToolByName(input_tools: Array, name: string): FunctionTool | undefined { + return input_tools.find((tool) => tool.type === 'function' && tool.name === name) as + | FunctionTool + | undefined; +} + +function parseToolCall( + params: Params, + toolCall: ResponseFunctionToolCall, +): ParsedResponseFunctionToolCall { + const inputTool = getInputToolByName(params.tools ?? [], toolCall.name); + + return { + ...toolCall, + ...toolCall, + parsed_arguments: + isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCall.arguments) + : inputTool?.strict ? JSON.parse(toolCall.arguments) + : null, + }; +} + +export function shouldParseToolCall( + params: ResponseCreateParamsNonStreaming | null | undefined, + toolCall: ResponseFunctionToolCall, +): boolean { + if (!params) { + return false; + } + + const inputTool = getInputToolByName(params.tools ?? [], toolCall.name); + return isAutoParsableTool(inputTool) || inputTool?.strict || false; +} + +export function validateInputTools(tools: ChatCompletionTool[] | undefined) { + for (const tool of tools ?? []) { + if (tool.type !== 'function') { + throw new OpenAIError( + `Currently only \`function\` tool types support auto-parsing; Received \`${tool.type}\``, + ); + } + + if (tool.function.strict !== true) { + throw new OpenAIError( + `The \`${tool.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`, + ); + } + } +} + +export function addOutputText(rsp: Response): void { + const texts: string[] = []; + for (const output of rsp.output) { + if (output.type !== 'message') { + continue; + } + + for (const content of output.content) { + if (content.type === 'output_text') { + texts.push(content.text); + } + } + } + + rsp.output_text = texts.join(''); +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/RunnableFunction.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/RunnableFunction.ts new file mode 100644 index 0000000000000000000000000000000000000000..d387245cd3458774a1750af60f2572d2b930cf3b --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/RunnableFunction.ts @@ -0,0 +1,114 @@ +import { type ChatCompletionRunner } from './ChatCompletionRunner'; +import { type ChatCompletionStreamingRunner } from './ChatCompletionStreamingRunner'; +import { JSONSchema } from './jsonschema'; + +type PromiseOrValue = T | Promise; + +export type RunnableFunctionWithParse = { + /** + * @param args the return value from `parse`. + * @param runner the runner evaluating this callback. + * @returns a string to send back to OpenAI. + */ + function: ( + args: Args, + runner: ChatCompletionRunner | ChatCompletionStreamingRunner, + ) => PromiseOrValue; + /** + * @param input the raw args from the OpenAI function call. + * @returns the parsed arguments to pass to `function` + */ + parse: (input: string) => PromiseOrValue; + /** + * The parameters the function accepts, describes as a JSON Schema object. + */ + parameters: JSONSchema; + /** + * A description of what the function does, used by the model to choose when and how to call the function. + */ + description: string; + /** + * The name of the function to be called. Will default to function.name if omitted. + */ + name?: string | undefined; + strict?: boolean | undefined; +}; + +export type RunnableFunctionWithoutParse = { + /** + * @param args the raw args from the OpenAI function call. + * @returns a string to send back to OpenAI + */ + function: ( + args: string, + runner: ChatCompletionRunner | ChatCompletionStreamingRunner, + ) => PromiseOrValue; + /** + * The parameters the function accepts, describes as a JSON Schema object. + */ + parameters: JSONSchema; + /** + * A description of what the function does, used by the model to choose when and how to call the function. + */ + description: string; + /** + * The name of the function to be called. Will default to function.name if omitted. + */ + name?: string | undefined; + strict?: boolean | undefined; +}; + +export type RunnableFunction = + Args extends string ? RunnableFunctionWithoutParse + : Args extends object ? RunnableFunctionWithParse + : never; + +export type RunnableToolFunction = + Args extends string ? RunnableToolFunctionWithoutParse + : Args extends object ? RunnableToolFunctionWithParse + : never; + +export type RunnableToolFunctionWithoutParse = { + type: 'function'; + function: RunnableFunctionWithoutParse; +}; +export type RunnableToolFunctionWithParse = { + type: 'function'; + function: RunnableFunctionWithParse; +}; + +export function isRunnableFunctionWithParse( + fn: any, +): fn is RunnableFunctionWithParse { + return typeof (fn as any).parse === 'function'; +} + +export type BaseFunctionsArgs = readonly (object | string)[]; + +export type RunnableFunctions = + [any[]] extends [FunctionsArgs] ? readonly RunnableFunction[] + : { + [Index in keyof FunctionsArgs]: Index extends number ? RunnableFunction + : FunctionsArgs[Index]; + }; + +export type RunnableTools = + [any[]] extends [FunctionsArgs] ? readonly RunnableToolFunction[] + : { + [Index in keyof FunctionsArgs]: Index extends number ? RunnableToolFunction + : FunctionsArgs[Index]; + }; + +/** + * This is helper class for passing a `function` and `parse` where the `function` + * argument type matches the `parse` return type. + */ +export class ParsingToolFunction { + type: 'function'; + function: RunnableFunctionWithParse; + + constructor(input: RunnableFunctionWithParse) { + this.type = 'function'; + this.function = input; + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/Util.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/Util.ts new file mode 100644 index 0000000000000000000000000000000000000000..ae09b8a911502c73b0b98aa8c0dadbf58135aad0 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/Util.ts @@ -0,0 +1,23 @@ +/** + * Like `Promise.allSettled()` but throws an error if any promises are rejected. + */ +export const allSettledWithThrow = async (promises: Promise[]): Promise => { + const results = await Promise.allSettled(promises); + const rejected = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected'); + if (rejected.length) { + for (const result of rejected) { + console.error(result.reason); + } + + throw new Error(`${rejected.length} promise(s) failed - see the above errors`); + } + + // Note: TS was complaining about using `.filter().map()` here for some reason + const values: R[] = []; + for (const result of results) { + if (result.status === 'fulfilled') { + values.push(result.value); + } + } + return values; +}; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/chatCompletionUtils.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/chatCompletionUtils.ts new file mode 100644 index 0000000000000000000000000000000000000000..2bf0d5b478ad6a6ab687d790ea9a5bad0c31e30f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/chatCompletionUtils.ts @@ -0,0 +1,21 @@ +import { + type ChatCompletionAssistantMessageParam, + type ChatCompletionMessageParam, + type ChatCompletionToolMessageParam, +} from '../resources'; + +export const isAssistantMessage = ( + message: ChatCompletionMessageParam | null | undefined, +): message is ChatCompletionAssistantMessageParam => { + return message?.role === 'assistant'; +}; + +export const isToolMessage = ( + message: ChatCompletionMessageParam | null | undefined, +): message is ChatCompletionToolMessageParam => { + return message?.role === 'tool'; +}; + +export function isPresent(obj: T | null | undefined): obj is T { + return obj != null; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/jsonschema.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/jsonschema.ts new file mode 100644 index 0000000000000000000000000000000000000000..6362777054006210c27a9deaecb198b670caab50 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/jsonschema.ts @@ -0,0 +1,148 @@ +// File mostly copied from @types/json-schema, but stripped down a bit for brevity +// https://github.com/DefinitelyTyped/DefinitelyTyped/blob/817274f3280152ba2929a6067c93df8b34c4c9aa/types/json-schema/index.d.ts +// +// ================================================================================================== +// JSON Schema Draft 07 +// ================================================================================================== +// https://tools.ietf.org/html/draft-handrews-json-schema-validation-01 +// -------------------------------------------------------------------------------------------------- + +/** + * Primitive type + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1.1 + */ +export type JSONSchemaTypeName = + | ({} & string) + | 'string' + | 'number' + | 'integer' + | 'boolean' + | 'object' + | 'array' + | 'null'; + +/** + * Primitive type + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1.1 + */ +export type JSONSchemaType = + | string // + | number + | boolean + | JSONSchemaObject + | JSONSchemaArray + | null; + +// Workaround for infinite type recursion +export interface JSONSchemaObject { + [key: string]: JSONSchemaType; +} + +// Workaround for infinite type recursion +// https://github.com/Microsoft/TypeScript/issues/3496#issuecomment-128553540 +export interface JSONSchemaArray extends Array {} + +/** + * Meta schema + * + * Recommended values: + * - 'http://json-schema.org/schema#' + * - 'http://json-schema.org/hyper-schema#' + * - 'http://json-schema.org/draft-07/schema#' + * - 'http://json-schema.org/draft-07/hyper-schema#' + * + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-5 + */ +export type JSONSchemaVersion = string; + +/** + * JSON Schema v7 + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01 + */ +export type JSONSchemaDefinition = JSONSchema | boolean; +export interface JSONSchema { + $id?: string | undefined; + $comment?: string | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1 + */ + type?: JSONSchemaTypeName | JSONSchemaTypeName[] | undefined; + enum?: JSONSchemaType[] | undefined; + const?: JSONSchemaType | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.2 + */ + multipleOf?: number | undefined; + maximum?: number | undefined; + exclusiveMaximum?: number | undefined; + minimum?: number | undefined; + exclusiveMinimum?: number | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.3 + */ + maxLength?: number | undefined; + minLength?: number | undefined; + pattern?: string | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.4 + */ + items?: JSONSchemaDefinition | JSONSchemaDefinition[] | undefined; + additionalItems?: JSONSchemaDefinition | undefined; + maxItems?: number | undefined; + minItems?: number | undefined; + uniqueItems?: boolean | undefined; + contains?: JSONSchemaDefinition | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.5 + */ + maxProperties?: number | undefined; + minProperties?: number | undefined; + required?: string[] | undefined; + properties?: + | { + [key: string]: JSONSchemaDefinition; + } + | undefined; + patternProperties?: + | { + [key: string]: JSONSchemaDefinition; + } + | undefined; + additionalProperties?: JSONSchemaDefinition | undefined; + propertyNames?: JSONSchemaDefinition | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.6 + */ + if?: JSONSchemaDefinition | undefined; + then?: JSONSchemaDefinition | undefined; + else?: JSONSchemaDefinition | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.7 + */ + allOf?: JSONSchemaDefinition[] | undefined; + anyOf?: JSONSchemaDefinition[] | undefined; + oneOf?: JSONSchemaDefinition[] | undefined; + not?: JSONSchemaDefinition | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-7 + */ + format?: string | undefined; + + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-10 + */ + title?: string | undefined; + description?: string | undefined; + default?: JSONSchemaType | undefined; + readOnly?: boolean | undefined; + writeOnly?: boolean | undefined; + examples?: JSONSchemaType | undefined; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/parser.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/parser.ts new file mode 100644 index 0000000000000000000000000000000000000000..78e1160731a3846239689836cf59a90e8e1088b4 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/parser.ts @@ -0,0 +1,311 @@ +import { ContentFilterFinishReasonError, LengthFinishReasonError, OpenAIError } from '../error'; +import { + ChatCompletion, + ChatCompletionCreateParams, + ChatCompletionCreateParamsBase, + ChatCompletionFunctionTool, + ChatCompletionMessage, + ChatCompletionMessageFunctionToolCall, + ChatCompletionStreamingToolRunnerParams, + ChatCompletionStreamParams, + ChatCompletionToolRunnerParams, + ParsedChatCompletion, + ParsedChoice, + ParsedFunctionToolCall, +} from '../resources/chat/completions'; +import { type ResponseFormatTextJSONSchemaConfig } from '../resources/responses/responses'; +import { ResponseFormatJSONSchema } from '../resources/shared'; + +type AnyChatCompletionCreateParams = + | ChatCompletionCreateParams + | ChatCompletionToolRunnerParams + | ChatCompletionStreamingToolRunnerParams + | ChatCompletionStreamParams; + +type Unpacked = T extends (infer U)[] ? U : T; + +type ToolCall = Unpacked; + +export function isChatCompletionFunctionTool(tool: ToolCall): tool is ChatCompletionFunctionTool { + return tool !== undefined && 'function' in tool && tool.function !== undefined; +} + +export type ExtractParsedContentFromParams = + Params['response_format'] extends AutoParseableResponseFormat ? P : null; + +export type AutoParseableResponseFormat = ResponseFormatJSONSchema & { + __output: ParsedT; // type-level only + + $brand: 'auto-parseable-response-format'; + $parseRaw(content: string): ParsedT; +}; + +export function makeParseableResponseFormat( + response_format: ResponseFormatJSONSchema, + parser: (content: string) => ParsedT, +): AutoParseableResponseFormat { + const obj = { ...response_format }; + + Object.defineProperties(obj, { + $brand: { + value: 'auto-parseable-response-format', + enumerable: false, + }, + $parseRaw: { + value: parser, + enumerable: false, + }, + }); + + return obj as AutoParseableResponseFormat; +} + +export type AutoParseableTextFormat = ResponseFormatTextJSONSchemaConfig & { + __output: ParsedT; // type-level only + + $brand: 'auto-parseable-response-format'; + $parseRaw(content: string): ParsedT; +}; + +export function makeParseableTextFormat( + response_format: ResponseFormatTextJSONSchemaConfig, + parser: (content: string) => ParsedT, +): AutoParseableTextFormat { + const obj = { ...response_format }; + + Object.defineProperties(obj, { + $brand: { + value: 'auto-parseable-response-format', + enumerable: false, + }, + $parseRaw: { + value: parser, + enumerable: false, + }, + }); + + return obj as AutoParseableTextFormat; +} + +export function isAutoParsableResponseFormat( + response_format: any, +): response_format is AutoParseableResponseFormat { + return response_format?.['$brand'] === 'auto-parseable-response-format'; +} + +type ToolOptions = { + name: string; + arguments: any; + function?: ((args: any) => any) | undefined; +}; + +export type AutoParseableTool< + OptionsT extends ToolOptions, + HasFunction = OptionsT['function'] extends Function ? true : false, +> = ChatCompletionFunctionTool & { + __arguments: OptionsT['arguments']; // type-level only + __name: OptionsT['name']; // type-level only + __hasFunction: HasFunction; // type-level only + + $brand: 'auto-parseable-tool'; + $callback: ((args: OptionsT['arguments']) => any) | undefined; + $parseRaw(args: string): OptionsT['arguments']; +}; + +export function makeParseableTool( + tool: ChatCompletionFunctionTool, + { + parser, + callback, + }: { + parser: (content: string) => OptionsT['arguments']; + callback: ((args: any) => any) | undefined; + }, +): AutoParseableTool { + const obj = { ...tool }; + + Object.defineProperties(obj, { + $brand: { + value: 'auto-parseable-tool', + enumerable: false, + }, + $parseRaw: { + value: parser, + enumerable: false, + }, + $callback: { + value: callback, + enumerable: false, + }, + }); + + return obj as AutoParseableTool; +} + +export function isAutoParsableTool(tool: any): tool is AutoParseableTool { + return tool?.['$brand'] === 'auto-parseable-tool'; +} + +export function maybeParseChatCompletion< + Params extends ChatCompletionCreateParams | null, + ParsedT = Params extends null ? null : ExtractParsedContentFromParams>, +>(completion: ChatCompletion, params: Params): ParsedChatCompletion { + if (!params || !hasAutoParseableInput(params)) { + return { + ...completion, + choices: completion.choices.map((choice) => { + assertToolCallsAreChatCompletionFunctionToolCalls(choice.message.tool_calls); + + return { + ...choice, + message: { + ...choice.message, + parsed: null, + ...(choice.message.tool_calls ? + { + tool_calls: choice.message.tool_calls, + } + : undefined), + }, + }; + }), + } as ParsedChatCompletion; + } + + return parseChatCompletion(completion, params); +} + +export function parseChatCompletion< + Params extends ChatCompletionCreateParams, + ParsedT = ExtractParsedContentFromParams, +>(completion: ChatCompletion, params: Params): ParsedChatCompletion { + const choices: Array> = completion.choices.map((choice): ParsedChoice => { + if (choice.finish_reason === 'length') { + throw new LengthFinishReasonError(); + } + + if (choice.finish_reason === 'content_filter') { + throw new ContentFilterFinishReasonError(); + } + + assertToolCallsAreChatCompletionFunctionToolCalls(choice.message.tool_calls); + + return { + ...choice, + message: { + ...choice.message, + ...(choice.message.tool_calls ? + { + tool_calls: + choice.message.tool_calls?.map((toolCall) => parseToolCall(params, toolCall)) ?? undefined, + } + : undefined), + parsed: + choice.message.content && !choice.message.refusal ? + parseResponseFormat(params, choice.message.content) + : null, + }, + } as ParsedChoice; + }); + + return { ...completion, choices }; +} + +function parseResponseFormat< + Params extends ChatCompletionCreateParams, + ParsedT = ExtractParsedContentFromParams, +>(params: Params, content: string): ParsedT | null { + if (params.response_format?.type !== 'json_schema') { + return null; + } + + if (params.response_format?.type === 'json_schema') { + if ('$parseRaw' in params.response_format) { + const response_format = params.response_format as AutoParseableResponseFormat; + + return response_format.$parseRaw(content); + } + + return JSON.parse(content); + } + + return null; +} + +function parseToolCall( + params: Params, + toolCall: ChatCompletionMessageFunctionToolCall, +): ParsedFunctionToolCall { + const inputTool = params.tools?.find( + (inputTool) => + isChatCompletionFunctionTool(inputTool) && inputTool.function?.name === toolCall.function.name, + ) as ChatCompletionFunctionTool | undefined; // TS doesn't narrow based on isChatCompletionTool + return { + ...toolCall, + function: { + ...toolCall.function, + parsed_arguments: + isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCall.function.arguments) + : inputTool?.function.strict ? JSON.parse(toolCall.function.arguments) + : null, + }, + }; +} + +export function shouldParseToolCall( + params: ChatCompletionCreateParams | null | undefined, + toolCall: ChatCompletionMessageFunctionToolCall, +): boolean { + if (!params || !('tools' in params) || !params.tools) { + return false; + } + + const inputTool = params.tools?.find( + (inputTool) => + isChatCompletionFunctionTool(inputTool) && inputTool.function?.name === toolCall.function.name, + ); + return ( + isChatCompletionFunctionTool(inputTool) && + (isAutoParsableTool(inputTool) || inputTool?.function.strict || false) + ); +} + +export function hasAutoParseableInput(params: AnyChatCompletionCreateParams): boolean { + if (isAutoParsableResponseFormat(params.response_format)) { + return true; + } + + return ( + params.tools?.some( + (t) => isAutoParsableTool(t) || (t.type === 'function' && t.function.strict === true), + ) ?? false + ); +} + +export function assertToolCallsAreChatCompletionFunctionToolCalls( + toolCalls: ChatCompletionMessage['tool_calls'], +): asserts toolCalls is ChatCompletionMessageFunctionToolCall[] { + for (const toolCall of toolCalls || []) { + if (toolCall.type !== 'function') { + throw new OpenAIError( + `Currently only \`function\` tool calls are supported; Received \`${toolCall.type}\``, + ); + } + } +} + +export function validateInputTools(tools: ChatCompletionCreateParamsBase['tools']) { + for (const tool of tools ?? []) { + if (tool.type !== 'function') { + throw new OpenAIError( + `Currently only \`function\` tool types support auto-parsing; Received \`${tool.type}\``, + ); + } + + if (tool.function.strict !== true) { + throw new OpenAIError( + `The \`${tool.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`, + ); + } + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/responses/EventTypes.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/responses/EventTypes.ts new file mode 100644 index 0000000000000000000000000000000000000000..8fc419fc61082965124b8722e44758b9c796dc75 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/responses/EventTypes.ts @@ -0,0 +1,74 @@ +import { + ResponseAudioDeltaEvent, + ResponseAudioDoneEvent, + ResponseAudioTranscriptDeltaEvent, + ResponseAudioTranscriptDoneEvent, + ResponseCodeInterpreterCallCodeDeltaEvent, + ResponseCodeInterpreterCallCodeDoneEvent, + ResponseCodeInterpreterCallCompletedEvent, + ResponseCodeInterpreterCallInProgressEvent, + ResponseCodeInterpreterCallInterpretingEvent, + ResponseCompletedEvent, + ResponseContentPartAddedEvent, + ResponseContentPartDoneEvent, + ResponseCreatedEvent, + ResponseErrorEvent, + ResponseFailedEvent, + ResponseFileSearchCallCompletedEvent, + ResponseFileSearchCallInProgressEvent, + ResponseFileSearchCallSearchingEvent, + ResponseFunctionCallArgumentsDeltaEvent as RawResponseFunctionCallArgumentsDeltaEvent, + ResponseFunctionCallArgumentsDoneEvent, + ResponseInProgressEvent, + ResponseOutputItemAddedEvent, + ResponseOutputItemDoneEvent, + ResponseRefusalDeltaEvent, + ResponseRefusalDoneEvent, + ResponseTextDeltaEvent as RawResponseTextDeltaEvent, + ResponseTextDoneEvent, + ResponseIncompleteEvent, + ResponseWebSearchCallCompletedEvent, + ResponseWebSearchCallInProgressEvent, + ResponseWebSearchCallSearchingEvent, +} from '../../resources/responses/responses'; + +export type ResponseFunctionCallArgumentsDeltaEvent = RawResponseFunctionCallArgumentsDeltaEvent & { + snapshot: string; +}; + +export type ResponseTextDeltaEvent = RawResponseTextDeltaEvent & { + snapshot: string; +}; + +export type ParsedResponseStreamEvent = + | ResponseAudioDeltaEvent + | ResponseAudioDoneEvent + | ResponseAudioTranscriptDeltaEvent + | ResponseAudioTranscriptDoneEvent + | ResponseCodeInterpreterCallCodeDeltaEvent + | ResponseCodeInterpreterCallCodeDoneEvent + | ResponseCodeInterpreterCallCompletedEvent + | ResponseCodeInterpreterCallInProgressEvent + | ResponseCodeInterpreterCallInterpretingEvent + | ResponseCompletedEvent + | ResponseContentPartAddedEvent + | ResponseContentPartDoneEvent + | ResponseCreatedEvent + | ResponseErrorEvent + | ResponseFileSearchCallCompletedEvent + | ResponseFileSearchCallInProgressEvent + | ResponseFileSearchCallSearchingEvent + | ResponseFunctionCallArgumentsDeltaEvent + | ResponseFunctionCallArgumentsDoneEvent + | ResponseInProgressEvent + | ResponseFailedEvent + | ResponseIncompleteEvent + | ResponseOutputItemAddedEvent + | ResponseOutputItemDoneEvent + | ResponseRefusalDeltaEvent + | ResponseRefusalDoneEvent + | ResponseTextDeltaEvent + | ResponseTextDoneEvent + | ResponseWebSearchCallCompletedEvent + | ResponseWebSearchCallInProgressEvent + | ResponseWebSearchCallSearchingEvent; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/responses/ResponseStream.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/responses/ResponseStream.ts new file mode 100644 index 0000000000000000000000000000000000000000..1c05c96cee402458ad1c4a2cd20e5837162183d7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/lib/responses/ResponseStream.ts @@ -0,0 +1,344 @@ +import { + ResponseTextConfig, + type ParsedResponse, + type Response, + type ResponseCreateParamsBase, + type ResponseCreateParamsStreaming, + type ResponseStreamEvent, +} from '../../resources/responses/responses'; +import { RequestOptions } from '../../internal/request-options'; +import { APIUserAbortError, OpenAIError } from '../../error'; +import OpenAI from '../../index'; +import { type BaseEvents, EventStream } from '../EventStream'; +import { type ResponseFunctionCallArgumentsDeltaEvent, type ResponseTextDeltaEvent } from './EventTypes'; +import { maybeParseResponse, ParseableToolsParams } from '../ResponsesParser'; +import { Stream } from '../../streaming'; + +export type ResponseStreamParams = ResponseCreateAndStreamParams | ResponseStreamByIdParams; + +export type ResponseCreateAndStreamParams = Omit & { + stream?: true; +}; + +export type ResponseStreamByIdParams = { + /** + * The ID of the response to stream. + */ + response_id: string; + /** + * If provided, the stream will start after the event with the given sequence number. + */ + starting_after?: number; + /** + * Configuration options for a text response from the model. Can be plain text or + * structured JSON data. Learn more: + * + * - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + * - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) + */ + text?: ResponseTextConfig; + + /** + * An array of tools the model may call while generating a response. When continuing a stream, provide + * the same tools as the original request. + */ + tools?: ParseableToolsParams; +}; + +type ResponseEvents = BaseEvents & + Omit< + { + [K in ResponseStreamEvent['type']]: (event: Extract) => void; + }, + 'response.output_text.delta' | 'response.function_call_arguments.delta' + > & { + event: (event: ResponseStreamEvent) => void; + 'response.output_text.delta': (event: ResponseTextDeltaEvent) => void; + 'response.function_call_arguments.delta': (event: ResponseFunctionCallArgumentsDeltaEvent) => void; + }; + +export type ResponseStreamingParams = Omit & { + stream?: true; +}; + +export class ResponseStream + extends EventStream + implements AsyncIterable +{ + #params: ResponseStreamingParams | null; + #currentResponseSnapshot: Response | undefined; + #finalResponse: ParsedResponse | undefined; + + constructor(params: ResponseStreamingParams | null) { + super(); + this.#params = params; + } + + static createResponse( + client: OpenAI, + params: ResponseStreamParams, + options?: RequestOptions, + ): ResponseStream { + const runner = new ResponseStream(params as ResponseCreateParamsStreaming); + runner._run(() => + runner._createOrRetrieveResponse(client, params, { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, + }), + ); + return runner; + } + + #beginRequest() { + if (this.ended) return; + this.#currentResponseSnapshot = undefined; + } + + #addEvent(this: ResponseStream, event: ResponseStreamEvent, starting_after: number | null) { + if (this.ended) return; + + const maybeEmit = (name: string, event: ResponseStreamEvent & { snapshot?: string }) => { + if (starting_after == null || event.sequence_number > starting_after) { + this._emit(name as any, event); + } + }; + + const response = this.#accumulateResponse(event); + maybeEmit('event', event); + + switch (event.type) { + case 'response.output_text.delta': { + const output = response.output[event.output_index]; + if (!output) { + throw new OpenAIError(`missing output at index ${event.output_index}`); + } + if (output.type === 'message') { + const content = output.content[event.content_index]; + if (!content) { + throw new OpenAIError(`missing content at index ${event.content_index}`); + } + if (content.type !== 'output_text') { + throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`); + } + + maybeEmit('response.output_text.delta', { + ...event, + snapshot: content.text, + }); + } + break; + } + case 'response.function_call_arguments.delta': { + const output = response.output[event.output_index]; + if (!output) { + throw new OpenAIError(`missing output at index ${event.output_index}`); + } + if (output.type === 'function_call') { + maybeEmit('response.function_call_arguments.delta', { + ...event, + snapshot: output.arguments, + }); + } + break; + } + default: + maybeEmit(event.type, event); + break; + } + } + + #endRequest(): ParsedResponse { + if (this.ended) { + throw new OpenAIError(`stream has ended, this shouldn't happen`); + } + const snapshot = this.#currentResponseSnapshot; + if (!snapshot) { + throw new OpenAIError(`request ended without sending any events`); + } + this.#currentResponseSnapshot = undefined; + const parsedResponse = finalizeResponse(snapshot, this.#params); + this.#finalResponse = parsedResponse; + + return parsedResponse; + } + + protected async _createOrRetrieveResponse( + client: OpenAI, + params: ResponseStreamParams, + options?: RequestOptions, + ): Promise> { + const signal = options?.signal; + if (signal) { + if (signal.aborted) this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + this.#beginRequest(); + + let stream: Stream | undefined; + let starting_after: number | null = null; + if ('response_id' in params) { + stream = await client.responses.retrieve( + params.response_id, + { stream: true }, + { ...options, signal: this.controller.signal, stream: true }, + ); + starting_after = params.starting_after ?? null; + } else { + stream = await client.responses.create( + { ...params, stream: true }, + { ...options, signal: this.controller.signal }, + ); + } + + this._connected(); + for await (const event of stream) { + this.#addEvent(event, starting_after); + } + if (stream.controller.signal?.aborted) { + throw new APIUserAbortError(); + } + return this.#endRequest(); + } + + #accumulateResponse(event: ResponseStreamEvent): Response { + let snapshot = this.#currentResponseSnapshot; + if (!snapshot) { + if (event.type !== 'response.created') { + throw new OpenAIError( + `When snapshot hasn't been set yet, expected 'response.created' event, got ${event.type}`, + ); + } + snapshot = this.#currentResponseSnapshot = event.response; + return snapshot; + } + + switch (event.type) { + case 'response.output_item.added': { + snapshot.output.push(event.item); + break; + } + case 'response.content_part.added': { + const output = snapshot.output[event.output_index]; + if (!output) { + throw new OpenAIError(`missing output at index ${event.output_index}`); + } + if (output.type === 'message') { + output.content.push(event.part); + } + break; + } + case 'response.output_text.delta': { + const output = snapshot.output[event.output_index]; + if (!output) { + throw new OpenAIError(`missing output at index ${event.output_index}`); + } + if (output.type === 'message') { + const content = output.content[event.content_index]; + if (!content) { + throw new OpenAIError(`missing content at index ${event.content_index}`); + } + if (content.type !== 'output_text') { + throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`); + } + content.text += event.delta; + } + break; + } + case 'response.function_call_arguments.delta': { + const output = snapshot.output[event.output_index]; + if (!output) { + throw new OpenAIError(`missing output at index ${event.output_index}`); + } + if (output.type === 'function_call') { + output.arguments += event.delta; + } + break; + } + case 'response.completed': { + this.#currentResponseSnapshot = event.response; + break; + } + } + + return snapshot; + } + + [Symbol.asyncIterator](this: ResponseStream): AsyncIterator { + const pushQueue: ResponseStreamEvent[] = []; + const readQueue: { + resolve: (event: ResponseStreamEvent | undefined) => void; + reject: (err: unknown) => void; + }[] = []; + let done = false; + + this.on('event', (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 (): Promise> => { + if (!pushQueue.length) { + if (done) { + return { value: undefined, done: true }; + } + return new Promise((resolve, reject) => + readQueue.push({ resolve, reject }), + ).then((event) => (event ? { value: event, done: false } : { value: undefined, done: true })); + } + const event = pushQueue.shift()!; + return { value: event, done: false }; + }, + return: async () => { + this.abort(); + return { value: undefined, done: true }; + }, + }; + } + + /** + * @returns a promise that resolves with the final Response, or rejects + * if an error occurred or the stream ended prematurely without producing a REsponse. + */ + async finalResponse(): Promise> { + await this.done(); + const response = this.#finalResponse; + if (!response) throw new OpenAIError('stream ended without producing a ChatCompletion'); + return response; + } +} + +function finalizeResponse( + snapshot: Response, + params: ResponseStreamingParams | null, +): ParsedResponse { + return maybeParseResponse(snapshot, params); +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/audio.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/audio.ts new file mode 100644 index 0000000000000000000000000000000000000000..bc19b759c7d053745b36425bcd008af21f2310bc --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/audio.ts @@ -0,0 +1,3 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export * from './audio/index'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/audio/audio.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/audio/audio.ts new file mode 100644 index 0000000000000000000000000000000000000000..081db7d9975ca3d6a7d2685d43dece52ffd39211 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/audio/audio.ts @@ -0,0 +1,78 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../core/resource'; +import * as SpeechAPI from './speech'; +import { Speech, SpeechCreateParams, SpeechModel } from './speech'; +import * as TranscriptionsAPI from './transcriptions'; +import { + Transcription, + TranscriptionCreateParams, + TranscriptionCreateParamsNonStreaming, + TranscriptionCreateParamsStreaming, + TranscriptionCreateResponse, + TranscriptionInclude, + TranscriptionSegment, + TranscriptionStreamEvent, + TranscriptionTextDeltaEvent, + TranscriptionTextDoneEvent, + TranscriptionVerbose, + TranscriptionWord, + Transcriptions, +} from './transcriptions'; +import * as TranslationsAPI from './translations'; +import { + Translation, + TranslationCreateParams, + TranslationCreateResponse, + TranslationVerbose, + Translations, +} from './translations'; + +export class Audio extends APIResource { + transcriptions: TranscriptionsAPI.Transcriptions = new TranscriptionsAPI.Transcriptions(this._client); + translations: TranslationsAPI.Translations = new TranslationsAPI.Translations(this._client); + speech: SpeechAPI.Speech = new SpeechAPI.Speech(this._client); +} + +export type AudioModel = 'whisper-1' | 'gpt-4o-transcribe' | 'gpt-4o-mini-transcribe'; + +/** + * The format of the output, in one of these options: `json`, `text`, `srt`, + * `verbose_json`, or `vtt`. For `gpt-4o-transcribe` and `gpt-4o-mini-transcribe`, + * the only supported format is `json`. + */ +export type AudioResponseFormat = 'json' | 'text' | 'srt' | 'verbose_json' | 'vtt'; + +Audio.Transcriptions = Transcriptions; +Audio.Translations = Translations; +Audio.Speech = Speech; + +export declare namespace Audio { + export { type AudioModel as AudioModel, type AudioResponseFormat as AudioResponseFormat }; + + export { + Transcriptions as Transcriptions, + type Transcription as Transcription, + type TranscriptionInclude as TranscriptionInclude, + type TranscriptionSegment as TranscriptionSegment, + type TranscriptionStreamEvent as TranscriptionStreamEvent, + type TranscriptionTextDeltaEvent as TranscriptionTextDeltaEvent, + type TranscriptionTextDoneEvent as TranscriptionTextDoneEvent, + type TranscriptionVerbose as TranscriptionVerbose, + type TranscriptionWord as TranscriptionWord, + type TranscriptionCreateResponse as TranscriptionCreateResponse, + type TranscriptionCreateParams as TranscriptionCreateParams, + type TranscriptionCreateParamsNonStreaming as TranscriptionCreateParamsNonStreaming, + type TranscriptionCreateParamsStreaming as TranscriptionCreateParamsStreaming, + }; + + export { + Translations as Translations, + type Translation as Translation, + type TranslationVerbose as TranslationVerbose, + type TranslationCreateResponse as TranslationCreateResponse, + type TranslationCreateParams as TranslationCreateParams, + }; + + export { Speech as Speech, type SpeechModel as SpeechModel, type SpeechCreateParams as SpeechCreateParams }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/audio/index.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/audio/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..deed39ede50293200742c4fc7d95c0e40ed5e6e4 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/audio/index.ts @@ -0,0 +1,26 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export { Audio, type AudioModel, type AudioResponseFormat } from './audio'; +export { Speech, type SpeechModel, type SpeechCreateParams } from './speech'; +export { + Transcriptions, + type Transcription, + type TranscriptionInclude, + type TranscriptionSegment, + type TranscriptionStreamEvent, + type TranscriptionTextDeltaEvent, + type TranscriptionTextDoneEvent, + type TranscriptionVerbose, + type TranscriptionWord, + type TranscriptionCreateResponse, + type TranscriptionCreateParams, + type TranscriptionCreateParamsNonStreaming, + type TranscriptionCreateParamsStreaming, +} from './transcriptions'; +export { + Translations, + type Translation, + type TranslationVerbose, + type TranslationCreateResponse, + type TranslationCreateParams, +} from './translations'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/audio/speech.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/audio/speech.ts new file mode 100644 index 0000000000000000000000000000000000000000..f533a558b75870db9fa3e7ad745478ab309d60af --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/audio/speech.ts @@ -0,0 +1,83 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../core/resource'; +import { APIPromise } from '../../core/api-promise'; +import { buildHeaders } from '../../internal/headers'; +import { RequestOptions } from '../../internal/request-options'; + +export class Speech extends APIResource { + /** + * Generates audio from the input text. + * + * @example + * ```ts + * const speech = await client.audio.speech.create({ + * input: 'input', + * model: 'string', + * voice: 'ash', + * }); + * + * const content = await speech.blob(); + * console.log(content); + * ``` + */ + create(body: SpeechCreateParams, options?: RequestOptions): APIPromise { + return this._client.post('/audio/speech', { + body, + ...options, + headers: buildHeaders([{ Accept: 'application/octet-stream' }, options?.headers]), + __binaryResponse: true, + }); + } +} + +export type SpeechModel = 'tts-1' | 'tts-1-hd' | 'gpt-4o-mini-tts'; + +export interface SpeechCreateParams { + /** + * The text to generate audio for. The maximum length is 4096 characters. + */ + input: string; + + /** + * One of the available [TTS models](https://platform.openai.com/docs/models#tts): + * `tts-1`, `tts-1-hd` or `gpt-4o-mini-tts`. + */ + model: (string & {}) | SpeechModel; + + /** + * The voice to use when generating the audio. Supported voices are `alloy`, `ash`, + * `ballad`, `coral`, `echo`, `fable`, `onyx`, `nova`, `sage`, `shimmer`, and + * `verse`. Previews of the voices are available in the + * [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech#voice-options). + */ + voice: (string & {}) | 'alloy' | 'ash' | 'ballad' | 'coral' | 'echo' | 'sage' | 'shimmer' | 'verse'; + + /** + * Control the voice of your generated audio with additional instructions. Does not + * work with `tts-1` or `tts-1-hd`. + */ + instructions?: string; + + /** + * The format to audio in. Supported formats are `mp3`, `opus`, `aac`, `flac`, + * `wav`, and `pcm`. + */ + response_format?: 'mp3' | 'opus' | 'aac' | 'flac' | 'wav' | 'pcm'; + + /** + * The speed of the generated audio. Select a value from `0.25` to `4.0`. `1.0` is + * the default. + */ + speed?: number; + + /** + * The format to stream the audio in. Supported formats are `sse` and `audio`. + * `sse` is not supported for `tts-1` or `tts-1-hd`. + */ + stream_format?: 'sse' | 'audio'; +} + +export declare namespace Speech { + export { type SpeechModel as SpeechModel, type SpeechCreateParams as SpeechCreateParams }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/audio/transcriptions.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/audio/transcriptions.ts new file mode 100644 index 0000000000000000000000000000000000000000..6fbbf8c3a6729ad4c8f6d8dee50cdbb728199ee4 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/audio/transcriptions.ts @@ -0,0 +1,617 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../core/resource'; +import * as TranscriptionsAPI from './transcriptions'; +import * as AudioAPI from './audio'; +import { APIPromise } from '../../core/api-promise'; +import { Stream } from '../../core/streaming'; +import { type Uploadable } from '../../core/uploads'; +import { RequestOptions } from '../../internal/request-options'; +import { multipartFormRequestOptions } from '../../internal/uploads'; + +export class Transcriptions extends APIResource { + /** + * Transcribes audio into the input language. + * + * @example + * ```ts + * const transcription = + * await client.audio.transcriptions.create({ + * file: fs.createReadStream('speech.mp3'), + * model: 'gpt-4o-transcribe', + * }); + * ``` + */ + create( + body: TranscriptionCreateParamsNonStreaming<'json' | undefined>, + options?: RequestOptions, + ): APIPromise; + create( + body: TranscriptionCreateParamsNonStreaming<'verbose_json'>, + options?: RequestOptions, + ): APIPromise; + create( + body: TranscriptionCreateParamsNonStreaming<'srt' | 'vtt' | 'text'>, + options?: RequestOptions, + ): APIPromise; + create(body: TranscriptionCreateParamsNonStreaming, options?: RequestOptions): APIPromise; + create( + body: TranscriptionCreateParamsStreaming, + options?: RequestOptions, + ): APIPromise>; + create( + body: TranscriptionCreateParamsStreaming, + options?: RequestOptions, + ): APIPromise>; + create( + body: TranscriptionCreateParams, + options?: RequestOptions, + ): APIPromise> { + return this._client.post( + '/audio/transcriptions', + multipartFormRequestOptions( + { + body, + ...options, + stream: body.stream ?? false, + __metadata: { model: body.model }, + }, + this._client, + ), + ); + } +} + +/** + * Represents a transcription response returned by model, based on the provided + * input. + */ +export interface Transcription { + /** + * The transcribed text. + */ + text: string; + + /** + * The log probabilities of the tokens in the transcription. Only returned with the + * models `gpt-4o-transcribe` and `gpt-4o-mini-transcribe` if `logprobs` is added + * to the `include` array. + */ + logprobs?: Array; + + /** + * Token usage statistics for the request. + */ + usage?: Transcription.Tokens | Transcription.Duration; +} + +export namespace Transcription { + export interface Logprob { + /** + * The token in the transcription. + */ + token?: string; + + /** + * The bytes of the token. + */ + bytes?: Array; + + /** + * The log probability of the token. + */ + logprob?: number; + } + + /** + * Usage statistics for models billed by token usage. + */ + export interface Tokens { + /** + * Number of input tokens billed for this request. + */ + input_tokens: number; + + /** + * Number of output tokens generated. + */ + output_tokens: number; + + /** + * Total number of tokens used (input + output). + */ + total_tokens: number; + + /** + * The type of the usage object. Always `tokens` for this variant. + */ + type: 'tokens'; + + /** + * Details about the input tokens billed for this request. + */ + input_token_details?: Tokens.InputTokenDetails; + } + + export namespace Tokens { + /** + * Details about the input tokens billed for this request. + */ + export interface InputTokenDetails { + /** + * Number of audio tokens billed for this request. + */ + audio_tokens?: number; + + /** + * Number of text tokens billed for this request. + */ + text_tokens?: number; + } + } + + /** + * Usage statistics for models billed by audio input duration. + */ + export interface Duration { + /** + * Duration of the input audio in seconds. + */ + seconds: number; + + /** + * The type of the usage object. Always `duration` for this variant. + */ + type: 'duration'; + } +} + +export type TranscriptionInclude = 'logprobs'; + +export interface TranscriptionSegment { + /** + * Unique identifier of the segment. + */ + id: number; + + /** + * Average logprob of the segment. If the value is lower than -1, consider the + * logprobs failed. + */ + avg_logprob: number; + + /** + * Compression ratio of the segment. If the value is greater than 2.4, consider the + * compression failed. + */ + compression_ratio: number; + + /** + * End time of the segment in seconds. + */ + end: number; + + /** + * Probability of no speech in the segment. If the value is higher than 1.0 and the + * `avg_logprob` is below -1, consider this segment silent. + */ + no_speech_prob: number; + + /** + * Seek offset of the segment. + */ + seek: number; + + /** + * Start time of the segment in seconds. + */ + start: number; + + /** + * Temperature parameter used for generating the segment. + */ + temperature: number; + + /** + * Text content of the segment. + */ + text: string; + + /** + * Array of token IDs for the text content. + */ + tokens: Array; +} + +/** + * Emitted when there is an additional text delta. This is also the first event + * emitted when the transcription starts. Only emitted when you + * [create a transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription) + * with the `Stream` parameter set to `true`. + */ +export type TranscriptionStreamEvent = TranscriptionTextDeltaEvent | TranscriptionTextDoneEvent; + +/** + * Emitted when there is an additional text delta. This is also the first event + * emitted when the transcription starts. Only emitted when you + * [create a transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription) + * with the `Stream` parameter set to `true`. + */ +export interface TranscriptionTextDeltaEvent { + /** + * The text delta that was additionally transcribed. + */ + delta: string; + + /** + * The type of the event. Always `transcript.text.delta`. + */ + type: 'transcript.text.delta'; + + /** + * The log probabilities of the delta. Only included if you + * [create a transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription) + * with the `include[]` parameter set to `logprobs`. + */ + logprobs?: Array; +} + +export namespace TranscriptionTextDeltaEvent { + export interface Logprob { + /** + * The token that was used to generate the log probability. + */ + token?: string; + + /** + * The bytes that were used to generate the log probability. + */ + bytes?: Array; + + /** + * The log probability of the token. + */ + logprob?: number; + } +} + +/** + * Emitted when the transcription is complete. Contains the complete transcription + * text. Only emitted when you + * [create a transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription) + * with the `Stream` parameter set to `true`. + */ +export interface TranscriptionTextDoneEvent { + /** + * The text that was transcribed. + */ + text: string; + + /** + * The type of the event. Always `transcript.text.done`. + */ + type: 'transcript.text.done'; + + /** + * The log probabilities of the individual tokens in the transcription. Only + * included if you + * [create a transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription) + * with the `include[]` parameter set to `logprobs`. + */ + logprobs?: Array; + + /** + * Usage statistics for models billed by token usage. + */ + usage?: TranscriptionTextDoneEvent.Usage; +} + +export namespace TranscriptionTextDoneEvent { + export interface Logprob { + /** + * The token that was used to generate the log probability. + */ + token?: string; + + /** + * The bytes that were used to generate the log probability. + */ + bytes?: Array; + + /** + * The log probability of the token. + */ + logprob?: number; + } + + /** + * Usage statistics for models billed by token usage. + */ + export interface Usage { + /** + * Number of input tokens billed for this request. + */ + input_tokens: number; + + /** + * Number of output tokens generated. + */ + output_tokens: number; + + /** + * Total number of tokens used (input + output). + */ + total_tokens: number; + + /** + * The type of the usage object. Always `tokens` for this variant. + */ + type: 'tokens'; + + /** + * Details about the input tokens billed for this request. + */ + input_token_details?: Usage.InputTokenDetails; + } + + export namespace Usage { + /** + * Details about the input tokens billed for this request. + */ + export interface InputTokenDetails { + /** + * Number of audio tokens billed for this request. + */ + audio_tokens?: number; + + /** + * Number of text tokens billed for this request. + */ + text_tokens?: number; + } + } +} + +/** + * Represents a verbose json transcription response returned by model, based on the + * provided input. + */ +export interface TranscriptionVerbose { + /** + * The duration of the input audio. + */ + duration: number; + + /** + * The language of the input audio. + */ + language: string; + + /** + * The transcribed text. + */ + text: string; + + /** + * Segments of the transcribed text and their corresponding details. + */ + segments?: Array; + + /** + * Usage statistics for models billed by audio input duration. + */ + usage?: TranscriptionVerbose.Usage; + + /** + * Extracted words and their corresponding timestamps. + */ + words?: Array; +} + +export namespace TranscriptionVerbose { + /** + * Usage statistics for models billed by audio input duration. + */ + export interface Usage { + /** + * Duration of the input audio in seconds. + */ + seconds: number; + + /** + * The type of the usage object. Always `duration` for this variant. + */ + type: 'duration'; + } +} + +export interface TranscriptionWord { + /** + * End time of the word in seconds. + */ + end: number; + + /** + * Start time of the word in seconds. + */ + start: number; + + /** + * The text content of the word. + */ + word: string; +} + +/** + * Represents a transcription response returned by model, based on the provided + * input. + */ +export type TranscriptionCreateResponse = Transcription | TranscriptionVerbose; + +export type TranscriptionCreateParams< + ResponseFormat extends AudioAPI.AudioResponseFormat | undefined = AudioAPI.AudioResponseFormat | undefined, +> = TranscriptionCreateParamsNonStreaming | TranscriptionCreateParamsStreaming; + +export interface TranscriptionCreateParamsBase< + ResponseFormat extends AudioAPI.AudioResponseFormat | undefined = AudioAPI.AudioResponseFormat | undefined, +> { + /** + * The audio file object (not file name) to transcribe, in one of these formats: + * flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. + */ + file: Uploadable; + + /** + * ID of the model to use. The options are `gpt-4o-transcribe`, + * `gpt-4o-mini-transcribe`, and `whisper-1` (which is powered by our open source + * Whisper V2 model). + */ + model: (string & {}) | AudioAPI.AudioModel; + + /** + * Controls how the audio is cut into chunks. When set to `"auto"`, the server + * first normalizes loudness and then uses voice activity detection (VAD) to choose + * boundaries. `server_vad` object can be provided to tweak VAD detection + * parameters manually. If unset, the audio is transcribed as a single block. + */ + chunking_strategy?: 'auto' | TranscriptionCreateParams.VadConfig | null; + + /** + * Additional information to include in the transcription response. `logprobs` will + * return the log probabilities of the tokens in the response to understand the + * model's confidence in the transcription. `logprobs` only works with + * response_format set to `json` and only with the models `gpt-4o-transcribe` and + * `gpt-4o-mini-transcribe`. + */ + include?: Array; + + /** + * The language of the input audio. Supplying the input language in + * [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) + * format will improve accuracy and latency. + */ + language?: string; + + /** + * An optional text to guide the model's style or continue a previous audio + * segment. The + * [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting) + * should match the audio language. + */ + prompt?: string; + + /** + * The format of the output, in one of these options: `json`, `text`, `srt`, + * `verbose_json`, or `vtt`. For `gpt-4o-transcribe` and `gpt-4o-mini-transcribe`, + * the only supported format is `json`. + */ + response_format?: ResponseFormat; + + /** + * If set to true, the model response data will be streamed to the client as it is + * generated using + * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + * See the + * [Streaming section of the Speech-to-Text guide](https://platform.openai.com/docs/guides/speech-to-text?lang=curl#streaming-transcriptions) + * for more information. + * + * Note: Streaming is not supported for the `whisper-1` model and will be ignored. + */ + stream?: boolean | null; + + /** + * The sampling temperature, between 0 and 1. Higher values like 0.8 will make the + * output more random, while lower values like 0.2 will make it more focused and + * deterministic. If set to 0, the model will use + * [log probability](https://en.wikipedia.org/wiki/Log_probability) to + * automatically increase the temperature until certain thresholds are hit. + */ + temperature?: number; + + /** + * The timestamp granularities to populate for this transcription. + * `response_format` must be set `verbose_json` to use timestamp granularities. + * Either or both of these options are supported: `word`, or `segment`. Note: There + * is no additional latency for segment timestamps, but generating word timestamps + * incurs additional latency. + */ + timestamp_granularities?: Array<'word' | 'segment'>; +} + +export namespace TranscriptionCreateParams { + export interface VadConfig { + /** + * Must be set to `server_vad` to enable manual chunking using server side VAD. + */ + type: 'server_vad'; + + /** + * Amount of audio to include before the VAD detected speech (in milliseconds). + */ + prefix_padding_ms?: number; + + /** + * Duration of silence to detect speech stop (in milliseconds). With shorter values + * the model will respond more quickly, but may jump in on short pauses from the + * user. + */ + silence_duration_ms?: number; + + /** + * Sensitivity threshold (0.0 to 1.0) for voice activity detection. A higher + * threshold will require louder audio to activate the model, and thus might + * perform better in noisy environments. + */ + threshold?: number; + } + + export type TranscriptionCreateParamsNonStreaming = TranscriptionsAPI.TranscriptionCreateParamsNonStreaming; + export type TranscriptionCreateParamsStreaming = TranscriptionsAPI.TranscriptionCreateParamsStreaming; +} + +export interface TranscriptionCreateParamsNonStreaming< + ResponseFormat extends AudioAPI.AudioResponseFormat | undefined = AudioAPI.AudioResponseFormat | undefined, +> extends TranscriptionCreateParamsBase { + /** + * If set to true, the model response data will be streamed to the client as it is + * generated using + * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + * See the + * [Streaming section of the Speech-to-Text guide](https://platform.openai.com/docs/guides/speech-to-text?lang=curl#streaming-transcriptions) + * for more information. + * + * Note: Streaming is not supported for the `whisper-1` model and will be ignored. + */ + stream?: false | null; +} + +export interface TranscriptionCreateParamsStreaming extends TranscriptionCreateParamsBase { + /** + * If set to true, the model response data will be streamed to the client as it is + * generated using + * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + * See the + * [Streaming section of the Speech-to-Text guide](https://platform.openai.com/docs/guides/speech-to-text?lang=curl#streaming-transcriptions) + * for more information. + * + * Note: Streaming is not supported for the `whisper-1` model and will be ignored. + */ + stream: true; +} + +export declare namespace Transcriptions { + export { + type Transcription as Transcription, + type TranscriptionInclude as TranscriptionInclude, + type TranscriptionSegment as TranscriptionSegment, + type TranscriptionStreamEvent as TranscriptionStreamEvent, + type TranscriptionTextDeltaEvent as TranscriptionTextDeltaEvent, + type TranscriptionTextDoneEvent as TranscriptionTextDoneEvent, + type TranscriptionVerbose as TranscriptionVerbose, + type TranscriptionWord as TranscriptionWord, + type TranscriptionCreateResponse as TranscriptionCreateResponse, + type TranscriptionCreateParams as TranscriptionCreateParams, + type TranscriptionCreateParamsNonStreaming as TranscriptionCreateParamsNonStreaming, + type TranscriptionCreateParamsStreaming as TranscriptionCreateParamsStreaming, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/audio/translations.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/audio/translations.ts new file mode 100644 index 0000000000000000000000000000000000000000..2e8c8f4a46a4303d5196afb0883bf501fadd0e18 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/audio/translations.ts @@ -0,0 +1,118 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../core/resource'; +import * as AudioAPI from './audio'; +import * as TranscriptionsAPI from './transcriptions'; +import { APIPromise } from '../../core/api-promise'; +import { type Uploadable } from '../../core/uploads'; +import { RequestOptions } from '../../internal/request-options'; +import { multipartFormRequestOptions } from '../../internal/uploads'; + +export class Translations extends APIResource { + /** + * Translates audio into English. + * + * @example + * ```ts + * const translation = await client.audio.translations.create({ + * file: fs.createReadStream('speech.mp3'), + * model: 'whisper-1', + * }); + * ``` + */ + create( + body: TranslationCreateParams<'json' | undefined>, + options?: RequestOptions, + ): APIPromise; + create( + body: TranslationCreateParams<'verbose_json'>, + options?: RequestOptions, + ): APIPromise; + create(body: TranslationCreateParams<'text' | 'srt' | 'vtt'>, options?: RequestOptions): APIPromise; + create(body: TranslationCreateParams, options?: RequestOptions): APIPromise; + create( + body: TranslationCreateParams, + options?: RequestOptions, + ): APIPromise { + return this._client.post( + '/audio/translations', + multipartFormRequestOptions({ body, ...options, __metadata: { model: body.model } }, this._client), + ); + } +} + +export interface Translation { + text: string; +} + +export interface TranslationVerbose { + /** + * The duration of the input audio. + */ + duration: number; + + /** + * The language of the output translation (always `english`). + */ + language: string; + + /** + * The translated text. + */ + text: string; + + /** + * Segments of the translated text and their corresponding details. + */ + segments?: Array; +} + +export type TranslationCreateResponse = Translation | TranslationVerbose; + +export interface TranslationCreateParams< + ResponseFormat extends AudioAPI.AudioResponseFormat | undefined = AudioAPI.AudioResponseFormat | undefined, +> { + /** + * The audio file object (not file name) translate, in one of these formats: flac, + * mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. + */ + file: Uploadable; + + /** + * ID of the model to use. Only `whisper-1` (which is powered by our open source + * Whisper V2 model) is currently available. + */ + model: (string & {}) | AudioAPI.AudioModel; + + /** + * An optional text to guide the model's style or continue a previous audio + * segment. The + * [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting) + * should be in English. + */ + prompt?: string; + + /** + * The format of the output, in one of these options: `json`, `text`, `srt`, + * `verbose_json`, or `vtt`. + */ + response_format?: 'json' | 'text' | 'srt' | 'verbose_json' | 'vtt'; + + /** + * The sampling temperature, between 0 and 1. Higher values like 0.8 will make the + * output more random, while lower values like 0.2 will make it more focused and + * deterministic. If set to 0, the model will use + * [log probability](https://en.wikipedia.org/wiki/Log_probability) to + * automatically increase the temperature until certain thresholds are hit. + */ + temperature?: number; +} + +export declare namespace Translations { + export { + type Translation as Translation, + type TranslationVerbose as TranslationVerbose, + type TranslationCreateResponse as TranslationCreateResponse, + type TranslationCreateParams as TranslationCreateParams, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/batches.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/batches.ts new file mode 100644 index 0000000000000000000000000000000000000000..1bd5c0f7c4c233e9d81d5747caff5a74e338db66 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/batches.ts @@ -0,0 +1,287 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../core/resource'; +import * as BatchesAPI from './batches'; +import * as Shared from './shared'; +import { APIPromise } from '../core/api-promise'; +import { CursorPage, type CursorPageParams, PagePromise } from '../core/pagination'; +import { RequestOptions } from '../internal/request-options'; +import { path } from '../internal/utils/path'; + +export class Batches extends APIResource { + /** + * Creates and executes a batch from an uploaded file of requests + */ + create(body: BatchCreateParams, options?: RequestOptions): APIPromise { + return this._client.post('/batches', { body, ...options }); + } + + /** + * Retrieves a batch. + */ + retrieve(batchID: string, options?: RequestOptions): APIPromise { + return this._client.get(path`/batches/${batchID}`, options); + } + + /** + * List your organization's batches. + */ + list( + query: BatchListParams | null | undefined = {}, + options?: RequestOptions, + ): PagePromise { + return this._client.getAPIList('/batches', CursorPage, { query, ...options }); + } + + /** + * Cancels an in-progress batch. The batch will be in status `cancelling` for up to + * 10 minutes, before changing to `cancelled`, where it will have partial results + * (if any) available in the output file. + */ + cancel(batchID: string, options?: RequestOptions): APIPromise { + return this._client.post(path`/batches/${batchID}/cancel`, options); + } +} + +export type BatchesPage = CursorPage; + +export interface Batch { + id: string; + + /** + * The time frame within which the batch should be processed. + */ + completion_window: string; + + /** + * The Unix timestamp (in seconds) for when the batch was created. + */ + created_at: number; + + /** + * The OpenAI API endpoint used by the batch. + */ + endpoint: string; + + /** + * The ID of the input file for the batch. + */ + input_file_id: string; + + /** + * The object type, which is always `batch`. + */ + object: 'batch'; + + /** + * The current status of the batch. + */ + status: + | 'validating' + | 'failed' + | 'in_progress' + | 'finalizing' + | 'completed' + | 'expired' + | 'cancelling' + | 'cancelled'; + + /** + * The Unix timestamp (in seconds) for when the batch was cancelled. + */ + cancelled_at?: number; + + /** + * The Unix timestamp (in seconds) for when the batch started cancelling. + */ + cancelling_at?: number; + + /** + * The Unix timestamp (in seconds) for when the batch was completed. + */ + completed_at?: number; + + /** + * The ID of the file containing the outputs of requests with errors. + */ + error_file_id?: string; + + errors?: Batch.Errors; + + /** + * The Unix timestamp (in seconds) for when the batch expired. + */ + expired_at?: number; + + /** + * The Unix timestamp (in seconds) for when the batch will expire. + */ + expires_at?: number; + + /** + * The Unix timestamp (in seconds) for when the batch failed. + */ + failed_at?: number; + + /** + * The Unix timestamp (in seconds) for when the batch started finalizing. + */ + finalizing_at?: number; + + /** + * The Unix timestamp (in seconds) for when the batch started processing. + */ + in_progress_at?: number; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; + + /** + * The ID of the file containing the outputs of successfully executed requests. + */ + output_file_id?: string; + + /** + * The request counts for different statuses within the batch. + */ + request_counts?: BatchRequestCounts; +} + +export namespace Batch { + export interface Errors { + data?: Array; + + /** + * The object type, which is always `list`. + */ + object?: string; + } +} + +export interface BatchError { + /** + * An error code identifying the error type. + */ + code?: string; + + /** + * The line number of the input file where the error occurred, if applicable. + */ + line?: number | null; + + /** + * A human-readable message providing more details about the error. + */ + message?: string; + + /** + * The name of the parameter that caused the error, if applicable. + */ + param?: string | null; +} + +/** + * The request counts for different statuses within the batch. + */ +export interface BatchRequestCounts { + /** + * Number of requests that have been completed successfully. + */ + completed: number; + + /** + * Number of requests that have failed. + */ + failed: number; + + /** + * Total number of requests in the batch. + */ + total: number; +} + +export interface BatchCreateParams { + /** + * The time frame within which the batch should be processed. Currently only `24h` + * is supported. + */ + completion_window: '24h'; + + /** + * The endpoint to be used for all requests in the batch. Currently + * `/v1/responses`, `/v1/chat/completions`, `/v1/embeddings`, and `/v1/completions` + * are supported. Note that `/v1/embeddings` batches are also restricted to a + * maximum of 50,000 embedding inputs across all requests in the batch. + */ + endpoint: '/v1/responses' | '/v1/chat/completions' | '/v1/embeddings' | '/v1/completions'; + + /** + * The ID of an uploaded file that contains requests for the new batch. + * + * See [upload file](https://platform.openai.com/docs/api-reference/files/create) + * for how to upload a file. + * + * Your input file must be formatted as a + * [JSONL file](https://platform.openai.com/docs/api-reference/batch/request-input), + * and must be uploaded with the purpose `batch`. The file can contain up to 50,000 + * requests, and can be up to 200 MB in size. + */ + input_file_id: string; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; + + /** + * The expiration policy for the output and/or error file that are generated for a + * batch. + */ + output_expires_after?: BatchCreateParams.OutputExpiresAfter; +} + +export namespace BatchCreateParams { + /** + * The expiration policy for the output and/or error file that are generated for a + * batch. + */ + export interface OutputExpiresAfter { + /** + * Anchor timestamp after which the expiration policy applies. Supported anchors: + * `created_at`. Note that the anchor is the file creation time, not the time the + * batch is created. + */ + anchor: 'created_at'; + + /** + * The number of seconds after the anchor time that the file will expire. Must be + * between 3600 (1 hour) and 2592000 (30 days). + */ + seconds: number; + } +} + +export interface BatchListParams extends CursorPageParams {} + +export declare namespace Batches { + export { + type Batch as Batch, + type BatchError as BatchError, + type BatchRequestCounts as BatchRequestCounts, + type BatchesPage as BatchesPage, + type BatchCreateParams as BatchCreateParams, + type BatchListParams as BatchListParams, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta.ts new file mode 100644 index 0000000000000000000000000000000000000000..1542e942b513d490a80ef1a063f8f7221de8b0c1 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta.ts @@ -0,0 +1,3 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export * from './beta/index'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/assistants.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/assistants.ts new file mode 100644 index 0000000000000000000000000000000000000000..14ec22e4d73171d2486e27a9571c62cafffdef4e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/assistants.ts @@ -0,0 +1,1550 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../core/resource'; +import * as Shared from '../shared'; +import * as MessagesAPI from './threads/messages'; +import * as ThreadsAPI from './threads/threads'; +import * as RunsAPI from './threads/runs/runs'; +import * as StepsAPI from './threads/runs/steps'; +import { APIPromise } from '../../core/api-promise'; +import { CursorPage, type CursorPageParams, PagePromise } from '../../core/pagination'; +import { buildHeaders } from '../../internal/headers'; +import { RequestOptions } from '../../internal/request-options'; +import { path } from '../../internal/utils/path'; +import { AssistantStream } from '../../lib/AssistantStream'; + +export class Assistants extends APIResource { + /** + * Create an assistant with a model and instructions. + * + * @example + * ```ts + * const assistant = await client.beta.assistants.create({ + * model: 'gpt-4o', + * }); + * ``` + */ + create(body: AssistantCreateParams, options?: RequestOptions): APIPromise { + return this._client.post('/assistants', { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + + /** + * Retrieves an assistant. + * + * @example + * ```ts + * const assistant = await client.beta.assistants.retrieve( + * 'assistant_id', + * ); + * ``` + */ + retrieve(assistantID: string, options?: RequestOptions): APIPromise { + return this._client.get(path`/assistants/${assistantID}`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + + /** + * Modifies an assistant. + * + * @example + * ```ts + * const assistant = await client.beta.assistants.update( + * 'assistant_id', + * ); + * ``` + */ + update(assistantID: string, body: AssistantUpdateParams, options?: RequestOptions): APIPromise { + return this._client.post(path`/assistants/${assistantID}`, { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + + /** + * Returns a list of assistants. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const assistant of client.beta.assistants.list()) { + * // ... + * } + * ``` + */ + list( + query: AssistantListParams | null | undefined = {}, + options?: RequestOptions, + ): PagePromise { + return this._client.getAPIList('/assistants', CursorPage, { + query, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + + /** + * Delete an assistant. + * + * @example + * ```ts + * const assistantDeleted = + * await client.beta.assistants.delete('assistant_id'); + * ``` + */ + delete(assistantID: string, options?: RequestOptions): APIPromise { + return this._client.delete(path`/assistants/${assistantID}`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } +} + +export type AssistantsPage = CursorPage; + +/** + * Represents an `assistant` that can call the model and use tools. + */ +export interface Assistant { + /** + * The identifier, which can be referenced in API endpoints. + */ + id: string; + + /** + * The Unix timestamp (in seconds) for when the assistant was created. + */ + created_at: number; + + /** + * The description of the assistant. The maximum length is 512 characters. + */ + description: string | null; + + /** + * The system instructions that the assistant uses. The maximum length is 256,000 + * characters. + */ + instructions: string | null; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata: Shared.Metadata | null; + + /** + * ID of the model to use. You can use the + * [List models](https://platform.openai.com/docs/api-reference/models/list) API to + * see all of your available models, or see our + * [Model overview](https://platform.openai.com/docs/models) for descriptions of + * them. + */ + model: string; + + /** + * The name of the assistant. The maximum length is 256 characters. + */ + name: string | null; + + /** + * The object type, which is always `assistant`. + */ + object: 'assistant'; + + /** + * A list of tool enabled on the assistant. There can be a maximum of 128 tools per + * assistant. Tools can be of types `code_interpreter`, `file_search`, or + * `function`. + */ + tools: Array; + + /** + * Specifies the format that the model must output. Compatible with + * [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), + * [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), + * and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + * + * Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + * Outputs which ensures the model will match your supplied JSON schema. Learn more + * in the + * [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + * + * Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the + * message the model generates is valid JSON. + * + * **Important:** when using JSON mode, you **must** also instruct the model to + * produce JSON yourself via a system or user message. Without this, the model may + * generate an unending stream of whitespace until the generation reaches the token + * limit, resulting in a long-running and seemingly "stuck" request. Also note that + * the message content may be partially cut off if `finish_reason="length"`, which + * indicates the generation exceeded `max_tokens` or the conversation exceeded the + * max context length. + */ + response_format?: ThreadsAPI.AssistantResponseFormatOption | null; + + /** + * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + * make the output more random, while lower values like 0.2 will make it more + * focused and deterministic. + */ + temperature?: number | null; + + /** + * A set of resources that are used by the assistant's tools. The resources are + * specific to the type of tool. For example, the `code_interpreter` tool requires + * a list of file IDs, while the `file_search` tool requires a list of vector store + * IDs. + */ + tool_resources?: Assistant.ToolResources | null; + + /** + * An alternative to sampling with temperature, called nucleus sampling, where the + * model considers the results of the tokens with top_p probability mass. So 0.1 + * means only the tokens comprising the top 10% probability mass are considered. + * + * We generally recommend altering this or temperature but not both. + */ + top_p?: number | null; +} + +export namespace Assistant { + /** + * A set of resources that are used by the assistant's tools. The resources are + * specific to the type of tool. For example, the `code_interpreter` tool requires + * a list of file IDs, while the `file_search` tool requires a list of vector store + * IDs. + */ + export interface ToolResources { + code_interpreter?: ToolResources.CodeInterpreter; + + file_search?: ToolResources.FileSearch; + } + + export namespace ToolResources { + export interface CodeInterpreter { + /** + * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made + * available to the `code_interpreter`` tool. There can be a maximum of 20 files + * associated with the tool. + */ + file_ids?: Array; + } + + export interface FileSearch { + /** + * The ID of the + * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) + * attached to this assistant. There can be a maximum of 1 vector store attached to + * the assistant. + */ + vector_store_ids?: Array; + } + } +} + +export interface AssistantDeleted { + id: string; + + deleted: boolean; + + object: 'assistant.deleted'; +} + +/** + * Represents an event emitted when streaming a Run. + * + * Each event in a server-sent events stream has an `event` and `data` property: + * + * ``` + * event: thread.created + * data: {"id": "thread_123", "object": "thread", ...} + * ``` + * + * We emit events whenever a new object is created, transitions to a new state, or + * is being streamed in parts (deltas). For example, we emit `thread.run.created` + * when a new run is created, `thread.run.completed` when a run completes, and so + * on. When an Assistant chooses to create a message during a run, we emit a + * `thread.message.created event`, a `thread.message.in_progress` event, many + * `thread.message.delta` events, and finally a `thread.message.completed` event. + * + * We may add additional events over time, so we recommend handling unknown events + * gracefully in your code. See the + * [Assistants API quickstart](https://platform.openai.com/docs/assistants/overview) + * to learn how to integrate the Assistants API with streaming. + */ +export type AssistantStreamEvent = + | AssistantStreamEvent.ThreadCreated + | AssistantStreamEvent.ThreadRunCreated + | AssistantStreamEvent.ThreadRunQueued + | AssistantStreamEvent.ThreadRunInProgress + | AssistantStreamEvent.ThreadRunRequiresAction + | AssistantStreamEvent.ThreadRunCompleted + | AssistantStreamEvent.ThreadRunIncomplete + | AssistantStreamEvent.ThreadRunFailed + | AssistantStreamEvent.ThreadRunCancelling + | AssistantStreamEvent.ThreadRunCancelled + | AssistantStreamEvent.ThreadRunExpired + | AssistantStreamEvent.ThreadRunStepCreated + | AssistantStreamEvent.ThreadRunStepInProgress + | AssistantStreamEvent.ThreadRunStepDelta + | AssistantStreamEvent.ThreadRunStepCompleted + | AssistantStreamEvent.ThreadRunStepFailed + | AssistantStreamEvent.ThreadRunStepCancelled + | AssistantStreamEvent.ThreadRunStepExpired + | AssistantStreamEvent.ThreadMessageCreated + | AssistantStreamEvent.ThreadMessageInProgress + | AssistantStreamEvent.ThreadMessageDelta + | AssistantStreamEvent.ThreadMessageCompleted + | AssistantStreamEvent.ThreadMessageIncomplete + | AssistantStreamEvent.ErrorEvent; + +export namespace AssistantStreamEvent { + /** + * Occurs when a new + * [thread](https://platform.openai.com/docs/api-reference/threads/object) is + * created. + */ + export interface ThreadCreated { + /** + * Represents a thread that contains + * [messages](https://platform.openai.com/docs/api-reference/messages). + */ + data: ThreadsAPI.Thread; + + event: 'thread.created'; + + /** + * Whether to enable input audio transcription. + */ + enabled?: boolean; + } + + /** + * Occurs when a new + * [run](https://platform.openai.com/docs/api-reference/runs/object) is created. + */ + export interface ThreadRunCreated { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.created'; + } + + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * moves to a `queued` status. + */ + export interface ThreadRunQueued { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.queued'; + } + + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * moves to an `in_progress` status. + */ + export interface ThreadRunInProgress { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.in_progress'; + } + + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * moves to a `requires_action` status. + */ + export interface ThreadRunRequiresAction { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.requires_action'; + } + + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * is completed. + */ + export interface ThreadRunCompleted { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.completed'; + } + + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * ends with status `incomplete`. + */ + export interface ThreadRunIncomplete { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.incomplete'; + } + + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * fails. + */ + export interface ThreadRunFailed { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.failed'; + } + + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * moves to a `cancelling` status. + */ + export interface ThreadRunCancelling { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.cancelling'; + } + + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * is cancelled. + */ + export interface ThreadRunCancelled { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.cancelled'; + } + + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * expires. + */ + export interface ThreadRunExpired { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.expired'; + } + + /** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) + * is created. + */ + export interface ThreadRunStepCreated { + /** + * Represents a step in execution of a run. + */ + data: StepsAPI.RunStep; + + event: 'thread.run.step.created'; + } + + /** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) + * moves to an `in_progress` state. + */ + export interface ThreadRunStepInProgress { + /** + * Represents a step in execution of a run. + */ + data: StepsAPI.RunStep; + + event: 'thread.run.step.in_progress'; + } + + /** + * Occurs when parts of a + * [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) + * are being streamed. + */ + export interface ThreadRunStepDelta { + /** + * Represents a run step delta i.e. any changed fields on a run step during + * streaming. + */ + data: StepsAPI.RunStepDeltaEvent; + + event: 'thread.run.step.delta'; + } + + /** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) + * is completed. + */ + export interface ThreadRunStepCompleted { + /** + * Represents a step in execution of a run. + */ + data: StepsAPI.RunStep; + + event: 'thread.run.step.completed'; + } + + /** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) + * fails. + */ + export interface ThreadRunStepFailed { + /** + * Represents a step in execution of a run. + */ + data: StepsAPI.RunStep; + + event: 'thread.run.step.failed'; + } + + /** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) + * is cancelled. + */ + export interface ThreadRunStepCancelled { + /** + * Represents a step in execution of a run. + */ + data: StepsAPI.RunStep; + + event: 'thread.run.step.cancelled'; + } + + /** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) + * expires. + */ + export interface ThreadRunStepExpired { + /** + * Represents a step in execution of a run. + */ + data: StepsAPI.RunStep; + + event: 'thread.run.step.expired'; + } + + /** + * Occurs when a + * [message](https://platform.openai.com/docs/api-reference/messages/object) is + * created. + */ + export interface ThreadMessageCreated { + /** + * Represents a message within a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: MessagesAPI.Message; + + event: 'thread.message.created'; + } + + /** + * Occurs when a + * [message](https://platform.openai.com/docs/api-reference/messages/object) moves + * to an `in_progress` state. + */ + export interface ThreadMessageInProgress { + /** + * Represents a message within a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: MessagesAPI.Message; + + event: 'thread.message.in_progress'; + } + + /** + * Occurs when parts of a + * [Message](https://platform.openai.com/docs/api-reference/messages/object) are + * being streamed. + */ + export interface ThreadMessageDelta { + /** + * Represents a message delta i.e. any changed fields on a message during + * streaming. + */ + data: MessagesAPI.MessageDeltaEvent; + + event: 'thread.message.delta'; + } + + /** + * Occurs when a + * [message](https://platform.openai.com/docs/api-reference/messages/object) is + * completed. + */ + export interface ThreadMessageCompleted { + /** + * Represents a message within a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: MessagesAPI.Message; + + event: 'thread.message.completed'; + } + + /** + * Occurs when a + * [message](https://platform.openai.com/docs/api-reference/messages/object) ends + * before it is completed. + */ + export interface ThreadMessageIncomplete { + /** + * Represents a message within a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: MessagesAPI.Message; + + event: 'thread.message.incomplete'; + } + + /** + * Occurs when an + * [error](https://platform.openai.com/docs/guides/error-codes#api-errors) occurs. + * This can happen due to an internal server error or a timeout. + */ + export interface ErrorEvent { + data: Shared.ErrorObject; + + event: 'error'; + } +} + +export type AssistantTool = CodeInterpreterTool | FileSearchTool | FunctionTool; + +export interface CodeInterpreterTool { + /** + * The type of tool being defined: `code_interpreter` + */ + type: 'code_interpreter'; +} + +export interface FileSearchTool { + /** + * The type of tool being defined: `file_search` + */ + type: 'file_search'; + + /** + * Overrides for the file search tool. + */ + file_search?: FileSearchTool.FileSearch; +} + +export namespace FileSearchTool { + /** + * Overrides for the file search tool. + */ + export interface FileSearch { + /** + * The maximum number of results the file search tool should output. The default is + * 20 for `gpt-4*` models and 5 for `gpt-3.5-turbo`. This number should be between + * 1 and 50 inclusive. + * + * Note that the file search tool may output fewer than `max_num_results` results. + * See the + * [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) + * for more information. + */ + max_num_results?: number; + + /** + * The ranking options for the file search. If not specified, the file search tool + * will use the `auto` ranker and a score_threshold of 0. + * + * See the + * [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) + * for more information. + */ + ranking_options?: FileSearch.RankingOptions; + } + + export namespace FileSearch { + /** + * The ranking options for the file search. If not specified, the file search tool + * will use the `auto` ranker and a score_threshold of 0. + * + * See the + * [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) + * for more information. + */ + export interface RankingOptions { + /** + * The score threshold for the file search. All values must be a floating point + * number between 0 and 1. + */ + score_threshold: number; + + /** + * The ranker to use for the file search. If not specified will use the `auto` + * ranker. + */ + ranker?: 'auto' | 'default_2024_08_21'; + } + } +} + +export interface FunctionTool { + function: Shared.FunctionDefinition; + + /** + * The type of tool being defined: `function` + */ + type: 'function'; +} + +/** + * Occurs when a + * [message](https://platform.openai.com/docs/api-reference/messages/object) is + * created. + */ +export type MessageStreamEvent = + | MessageStreamEvent.ThreadMessageCreated + | MessageStreamEvent.ThreadMessageInProgress + | MessageStreamEvent.ThreadMessageDelta + | MessageStreamEvent.ThreadMessageCompleted + | MessageStreamEvent.ThreadMessageIncomplete; + +export namespace MessageStreamEvent { + /** + * Occurs when a + * [message](https://platform.openai.com/docs/api-reference/messages/object) is + * created. + */ + export interface ThreadMessageCreated { + /** + * Represents a message within a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: MessagesAPI.Message; + + event: 'thread.message.created'; + } + + /** + * Occurs when a + * [message](https://platform.openai.com/docs/api-reference/messages/object) moves + * to an `in_progress` state. + */ + export interface ThreadMessageInProgress { + /** + * Represents a message within a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: MessagesAPI.Message; + + event: 'thread.message.in_progress'; + } + + /** + * Occurs when parts of a + * [Message](https://platform.openai.com/docs/api-reference/messages/object) are + * being streamed. + */ + export interface ThreadMessageDelta { + /** + * Represents a message delta i.e. any changed fields on a message during + * streaming. + */ + data: MessagesAPI.MessageDeltaEvent; + + event: 'thread.message.delta'; + } + + /** + * Occurs when a + * [message](https://platform.openai.com/docs/api-reference/messages/object) is + * completed. + */ + export interface ThreadMessageCompleted { + /** + * Represents a message within a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: MessagesAPI.Message; + + event: 'thread.message.completed'; + } + + /** + * Occurs when a + * [message](https://platform.openai.com/docs/api-reference/messages/object) ends + * before it is completed. + */ + export interface ThreadMessageIncomplete { + /** + * Represents a message within a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: MessagesAPI.Message; + + event: 'thread.message.incomplete'; + } +} + +/** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) + * is created. + */ +export type RunStepStreamEvent = + | RunStepStreamEvent.ThreadRunStepCreated + | RunStepStreamEvent.ThreadRunStepInProgress + | RunStepStreamEvent.ThreadRunStepDelta + | RunStepStreamEvent.ThreadRunStepCompleted + | RunStepStreamEvent.ThreadRunStepFailed + | RunStepStreamEvent.ThreadRunStepCancelled + | RunStepStreamEvent.ThreadRunStepExpired; + +export namespace RunStepStreamEvent { + /** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) + * is created. + */ + export interface ThreadRunStepCreated { + /** + * Represents a step in execution of a run. + */ + data: StepsAPI.RunStep; + + event: 'thread.run.step.created'; + } + + /** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) + * moves to an `in_progress` state. + */ + export interface ThreadRunStepInProgress { + /** + * Represents a step in execution of a run. + */ + data: StepsAPI.RunStep; + + event: 'thread.run.step.in_progress'; + } + + /** + * Occurs when parts of a + * [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) + * are being streamed. + */ + export interface ThreadRunStepDelta { + /** + * Represents a run step delta i.e. any changed fields on a run step during + * streaming. + */ + data: StepsAPI.RunStepDeltaEvent; + + event: 'thread.run.step.delta'; + } + + /** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) + * is completed. + */ + export interface ThreadRunStepCompleted { + /** + * Represents a step in execution of a run. + */ + data: StepsAPI.RunStep; + + event: 'thread.run.step.completed'; + } + + /** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) + * fails. + */ + export interface ThreadRunStepFailed { + /** + * Represents a step in execution of a run. + */ + data: StepsAPI.RunStep; + + event: 'thread.run.step.failed'; + } + + /** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) + * is cancelled. + */ + export interface ThreadRunStepCancelled { + /** + * Represents a step in execution of a run. + */ + data: StepsAPI.RunStep; + + event: 'thread.run.step.cancelled'; + } + + /** + * Occurs when a + * [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) + * expires. + */ + export interface ThreadRunStepExpired { + /** + * Represents a step in execution of a run. + */ + data: StepsAPI.RunStep; + + event: 'thread.run.step.expired'; + } +} + +/** + * Occurs when a new + * [run](https://platform.openai.com/docs/api-reference/runs/object) is created. + */ +export type RunStreamEvent = + | RunStreamEvent.ThreadRunCreated + | RunStreamEvent.ThreadRunQueued + | RunStreamEvent.ThreadRunInProgress + | RunStreamEvent.ThreadRunRequiresAction + | RunStreamEvent.ThreadRunCompleted + | RunStreamEvent.ThreadRunIncomplete + | RunStreamEvent.ThreadRunFailed + | RunStreamEvent.ThreadRunCancelling + | RunStreamEvent.ThreadRunCancelled + | RunStreamEvent.ThreadRunExpired; + +export namespace RunStreamEvent { + /** + * Occurs when a new + * [run](https://platform.openai.com/docs/api-reference/runs/object) is created. + */ + export interface ThreadRunCreated { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.created'; + } + + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * moves to a `queued` status. + */ + export interface ThreadRunQueued { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.queued'; + } + + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * moves to an `in_progress` status. + */ + export interface ThreadRunInProgress { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.in_progress'; + } + + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * moves to a `requires_action` status. + */ + export interface ThreadRunRequiresAction { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.requires_action'; + } + + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * is completed. + */ + export interface ThreadRunCompleted { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.completed'; + } + + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * ends with status `incomplete`. + */ + export interface ThreadRunIncomplete { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.incomplete'; + } + + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * fails. + */ + export interface ThreadRunFailed { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.failed'; + } + + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * moves to a `cancelling` status. + */ + export interface ThreadRunCancelling { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.cancelling'; + } + + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * is cancelled. + */ + export interface ThreadRunCancelled { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.cancelled'; + } + + /** + * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) + * expires. + */ + export interface ThreadRunExpired { + /** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ + data: RunsAPI.Run; + + event: 'thread.run.expired'; + } +} + +/** + * Occurs when a new + * [thread](https://platform.openai.com/docs/api-reference/threads/object) is + * created. + */ +export interface ThreadStreamEvent { + /** + * Represents a thread that contains + * [messages](https://platform.openai.com/docs/api-reference/messages). + */ + data: ThreadsAPI.Thread; + + event: 'thread.created'; + + /** + * Whether to enable input audio transcription. + */ + enabled?: boolean; +} + +export interface AssistantCreateParams { + /** + * ID of the model to use. You can use the + * [List models](https://platform.openai.com/docs/api-reference/models/list) API to + * see all of your available models, or see our + * [Model overview](https://platform.openai.com/docs/models) for descriptions of + * them. + */ + model: (string & {}) | Shared.ChatModel; + + /** + * The description of the assistant. The maximum length is 512 characters. + */ + description?: string | null; + + /** + * The system instructions that the assistant uses. The maximum length is 256,000 + * characters. + */ + instructions?: string | null; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; + + /** + * The name of the assistant. The maximum length is 256 characters. + */ + name?: string | null; + + /** + * Constrains effort on reasoning for + * [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently + * supported values are `minimal`, `low`, `medium`, and `high`. Reducing reasoning + * effort can result in faster responses and fewer tokens used on reasoning in a + * response. + */ + reasoning_effort?: Shared.ReasoningEffort | null; + + /** + * Specifies the format that the model must output. Compatible with + * [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), + * [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), + * and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + * + * Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + * Outputs which ensures the model will match your supplied JSON schema. Learn more + * in the + * [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + * + * Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the + * message the model generates is valid JSON. + * + * **Important:** when using JSON mode, you **must** also instruct the model to + * produce JSON yourself via a system or user message. Without this, the model may + * generate an unending stream of whitespace until the generation reaches the token + * limit, resulting in a long-running and seemingly "stuck" request. Also note that + * the message content may be partially cut off if `finish_reason="length"`, which + * indicates the generation exceeded `max_tokens` or the conversation exceeded the + * max context length. + */ + response_format?: ThreadsAPI.AssistantResponseFormatOption | null; + + /** + * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + * make the output more random, while lower values like 0.2 will make it more + * focused and deterministic. + */ + temperature?: number | null; + + /** + * A set of resources that are used by the assistant's tools. The resources are + * specific to the type of tool. For example, the `code_interpreter` tool requires + * a list of file IDs, while the `file_search` tool requires a list of vector store + * IDs. + */ + tool_resources?: AssistantCreateParams.ToolResources | null; + + /** + * A list of tool enabled on the assistant. There can be a maximum of 128 tools per + * assistant. Tools can be of types `code_interpreter`, `file_search`, or + * `function`. + */ + tools?: Array; + + /** + * An alternative to sampling with temperature, called nucleus sampling, where the + * model considers the results of the tokens with top_p probability mass. So 0.1 + * means only the tokens comprising the top 10% probability mass are considered. + * + * We generally recommend altering this or temperature but not both. + */ + top_p?: number | null; +} + +export namespace AssistantCreateParams { + /** + * A set of resources that are used by the assistant's tools. The resources are + * specific to the type of tool. For example, the `code_interpreter` tool requires + * a list of file IDs, while the `file_search` tool requires a list of vector store + * IDs. + */ + export interface ToolResources { + code_interpreter?: ToolResources.CodeInterpreter; + + file_search?: ToolResources.FileSearch; + } + + export namespace ToolResources { + export interface CodeInterpreter { + /** + * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made + * available to the `code_interpreter` tool. There can be a maximum of 20 files + * associated with the tool. + */ + file_ids?: Array; + } + + export interface FileSearch { + /** + * The + * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) + * attached to this assistant. There can be a maximum of 1 vector store attached to + * the assistant. + */ + vector_store_ids?: Array; + + /** + * A helper to create a + * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) + * with file_ids and attach it to this assistant. There can be a maximum of 1 + * vector store attached to the assistant. + */ + vector_stores?: Array; + } + + export namespace FileSearch { + export interface VectorStore { + /** + * The chunking strategy used to chunk the file(s). If not set, will use the `auto` + * strategy. + */ + chunking_strategy?: VectorStore.Auto | VectorStore.Static; + + /** + * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs to + * add to the vector store. There can be a maximum of 10000 files in a vector + * store. + */ + file_ids?: Array; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; + } + + export namespace VectorStore { + /** + * The default strategy. This strategy currently uses a `max_chunk_size_tokens` of + * `800` and `chunk_overlap_tokens` of `400`. + */ + export interface Auto { + /** + * Always `auto`. + */ + type: 'auto'; + } + + export interface Static { + static: Static.Static; + + /** + * Always `static`. + */ + type: 'static'; + } + + export namespace Static { + export interface Static { + /** + * The number of tokens that overlap between chunks. The default value is `400`. + * + * Note that the overlap must not exceed half of `max_chunk_size_tokens`. + */ + chunk_overlap_tokens: number; + + /** + * The maximum number of tokens in each chunk. The default value is `800`. The + * minimum value is `100` and the maximum value is `4096`. + */ + max_chunk_size_tokens: number; + } + } + } + } + } +} + +export interface AssistantUpdateParams { + /** + * The description of the assistant. The maximum length is 512 characters. + */ + description?: string | null; + + /** + * The system instructions that the assistant uses. The maximum length is 256,000 + * characters. + */ + instructions?: string | null; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; + + /** + * ID of the model to use. You can use the + * [List models](https://platform.openai.com/docs/api-reference/models/list) API to + * see all of your available models, or see our + * [Model overview](https://platform.openai.com/docs/models) for descriptions of + * them. + */ + model?: + | (string & {}) + | 'gpt-5' + | 'gpt-5-mini' + | 'gpt-5-nano' + | 'gpt-5-2025-08-07' + | 'gpt-5-mini-2025-08-07' + | 'gpt-5-nano-2025-08-07' + | 'gpt-4.1' + | 'gpt-4.1-mini' + | 'gpt-4.1-nano' + | 'gpt-4.1-2025-04-14' + | 'gpt-4.1-mini-2025-04-14' + | 'gpt-4.1-nano-2025-04-14' + | 'o3-mini' + | 'o3-mini-2025-01-31' + | 'o1' + | 'o1-2024-12-17' + | 'gpt-4o' + | 'gpt-4o-2024-11-20' + | 'gpt-4o-2024-08-06' + | 'gpt-4o-2024-05-13' + | 'gpt-4o-mini' + | 'gpt-4o-mini-2024-07-18' + | 'gpt-4.5-preview' + | 'gpt-4.5-preview-2025-02-27' + | 'gpt-4-turbo' + | 'gpt-4-turbo-2024-04-09' + | 'gpt-4-0125-preview' + | 'gpt-4-turbo-preview' + | 'gpt-4-1106-preview' + | 'gpt-4-vision-preview' + | 'gpt-4' + | 'gpt-4-0314' + | 'gpt-4-0613' + | 'gpt-4-32k' + | 'gpt-4-32k-0314' + | 'gpt-4-32k-0613' + | 'gpt-3.5-turbo' + | 'gpt-3.5-turbo-16k' + | 'gpt-3.5-turbo-0613' + | 'gpt-3.5-turbo-1106' + | 'gpt-3.5-turbo-0125' + | 'gpt-3.5-turbo-16k-0613'; + + /** + * The name of the assistant. The maximum length is 256 characters. + */ + name?: string | null; + + /** + * Constrains effort on reasoning for + * [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently + * supported values are `minimal`, `low`, `medium`, and `high`. Reducing reasoning + * effort can result in faster responses and fewer tokens used on reasoning in a + * response. + */ + reasoning_effort?: Shared.ReasoningEffort | null; + + /** + * Specifies the format that the model must output. Compatible with + * [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), + * [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), + * and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + * + * Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + * Outputs which ensures the model will match your supplied JSON schema. Learn more + * in the + * [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + * + * Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the + * message the model generates is valid JSON. + * + * **Important:** when using JSON mode, you **must** also instruct the model to + * produce JSON yourself via a system or user message. Without this, the model may + * generate an unending stream of whitespace until the generation reaches the token + * limit, resulting in a long-running and seemingly "stuck" request. Also note that + * the message content may be partially cut off if `finish_reason="length"`, which + * indicates the generation exceeded `max_tokens` or the conversation exceeded the + * max context length. + */ + response_format?: ThreadsAPI.AssistantResponseFormatOption | null; + + /** + * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + * make the output more random, while lower values like 0.2 will make it more + * focused and deterministic. + */ + temperature?: number | null; + + /** + * A set of resources that are used by the assistant's tools. The resources are + * specific to the type of tool. For example, the `code_interpreter` tool requires + * a list of file IDs, while the `file_search` tool requires a list of vector store + * IDs. + */ + tool_resources?: AssistantUpdateParams.ToolResources | null; + + /** + * A list of tool enabled on the assistant. There can be a maximum of 128 tools per + * assistant. Tools can be of types `code_interpreter`, `file_search`, or + * `function`. + */ + tools?: Array; + + /** + * An alternative to sampling with temperature, called nucleus sampling, where the + * model considers the results of the tokens with top_p probability mass. So 0.1 + * means only the tokens comprising the top 10% probability mass are considered. + * + * We generally recommend altering this or temperature but not both. + */ + top_p?: number | null; +} + +export namespace AssistantUpdateParams { + /** + * A set of resources that are used by the assistant's tools. The resources are + * specific to the type of tool. For example, the `code_interpreter` tool requires + * a list of file IDs, while the `file_search` tool requires a list of vector store + * IDs. + */ + export interface ToolResources { + code_interpreter?: ToolResources.CodeInterpreter; + + file_search?: ToolResources.FileSearch; + } + + export namespace ToolResources { + export interface CodeInterpreter { + /** + * Overrides the list of + * [file](https://platform.openai.com/docs/api-reference/files) IDs made available + * to the `code_interpreter` tool. There can be a maximum of 20 files associated + * with the tool. + */ + file_ids?: Array; + } + + export interface FileSearch { + /** + * Overrides the + * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) + * attached to this assistant. There can be a maximum of 1 vector store attached to + * the assistant. + */ + vector_store_ids?: Array; + } + } +} + +export interface AssistantListParams extends CursorPageParams { + /** + * A cursor for use in pagination. `before` is an object ID that defines your place + * in the list. For instance, if you make a list request and receive 100 objects, + * starting with obj_foo, your subsequent call can include before=obj_foo in order + * to fetch the previous page of the list. + */ + before?: string; + + /** + * Sort order by the `created_at` timestamp of the objects. `asc` for ascending + * order and `desc` for descending order. + */ + order?: 'asc' | 'desc'; +} + +export declare namespace Assistants { + export { + type Assistant as Assistant, + type AssistantDeleted as AssistantDeleted, + type AssistantStreamEvent as AssistantStreamEvent, + type AssistantTool as AssistantTool, + type CodeInterpreterTool as CodeInterpreterTool, + type FileSearchTool as FileSearchTool, + type FunctionTool as FunctionTool, + type MessageStreamEvent as MessageStreamEvent, + type RunStepStreamEvent as RunStepStreamEvent, + type RunStreamEvent as RunStreamEvent, + type ThreadStreamEvent as ThreadStreamEvent, + type AssistantsPage as AssistantsPage, + type AssistantCreateParams as AssistantCreateParams, + type AssistantUpdateParams as AssistantUpdateParams, + type AssistantListParams as AssistantListParams, + }; + + export { AssistantStream }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/beta.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/beta.ts new file mode 100644 index 0000000000000000000000000000000000000000..0d6b5e6f3f9c9bbbe33b2e87555aae701a9198d5 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/beta.ts @@ -0,0 +1,193 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../core/resource'; +import * as AssistantsAPI from './assistants'; +import { + Assistant, + AssistantCreateParams, + AssistantDeleted, + AssistantListParams, + AssistantStreamEvent, + AssistantTool, + AssistantUpdateParams, + Assistants, + AssistantsPage, + CodeInterpreterTool, + FileSearchTool, + FunctionTool, + MessageStreamEvent, + RunStepStreamEvent, + RunStreamEvent, + ThreadStreamEvent, +} from './assistants'; +import * as RealtimeAPI from './realtime/realtime'; +import { + ConversationCreatedEvent, + ConversationItem, + ConversationItemContent, + ConversationItemCreateEvent, + ConversationItemCreatedEvent, + ConversationItemDeleteEvent, + ConversationItemDeletedEvent, + ConversationItemInputAudioTranscriptionCompletedEvent, + ConversationItemInputAudioTranscriptionDeltaEvent, + ConversationItemInputAudioTranscriptionFailedEvent, + ConversationItemRetrieveEvent, + ConversationItemTruncateEvent, + ConversationItemTruncatedEvent, + ConversationItemWithReference, + ErrorEvent, + InputAudioBufferAppendEvent, + InputAudioBufferClearEvent, + InputAudioBufferClearedEvent, + InputAudioBufferCommitEvent, + InputAudioBufferCommittedEvent, + InputAudioBufferSpeechStartedEvent, + InputAudioBufferSpeechStoppedEvent, + RateLimitsUpdatedEvent, + Realtime, + RealtimeClientEvent, + RealtimeResponse, + RealtimeResponseStatus, + RealtimeResponseUsage, + RealtimeServerEvent, + ResponseAudioDeltaEvent, + ResponseAudioDoneEvent, + ResponseAudioTranscriptDeltaEvent, + ResponseAudioTranscriptDoneEvent, + ResponseCancelEvent, + ResponseContentPartAddedEvent, + ResponseContentPartDoneEvent, + ResponseCreateEvent, + ResponseCreatedEvent, + ResponseDoneEvent, + ResponseFunctionCallArgumentsDeltaEvent, + ResponseFunctionCallArgumentsDoneEvent, + ResponseOutputItemAddedEvent, + ResponseOutputItemDoneEvent, + ResponseTextDeltaEvent, + ResponseTextDoneEvent, + SessionCreatedEvent, + SessionUpdateEvent, + SessionUpdatedEvent, + TranscriptionSessionUpdate, + TranscriptionSessionUpdatedEvent, +} from './realtime/realtime'; +import * as ThreadsAPI from './threads/threads'; +import { + AssistantResponseFormatOption, + AssistantToolChoice, + AssistantToolChoiceFunction, + AssistantToolChoiceOption, + Thread, + ThreadCreateAndRunParams, + ThreadCreateAndRunParamsNonStreaming, + ThreadCreateAndRunParamsStreaming, + ThreadCreateAndRunPollParams, + ThreadCreateAndRunStreamParams, + ThreadCreateParams, + ThreadDeleted, + ThreadUpdateParams, + Threads, +} from './threads/threads'; + +export class Beta extends APIResource { + realtime: RealtimeAPI.Realtime = new RealtimeAPI.Realtime(this._client); + assistants: AssistantsAPI.Assistants = new AssistantsAPI.Assistants(this._client); + threads: ThreadsAPI.Threads = new ThreadsAPI.Threads(this._client); +} + +Beta.Realtime = Realtime; +Beta.Assistants = Assistants; +Beta.Threads = Threads; + +export declare namespace Beta { + export { + Realtime as Realtime, + type ConversationCreatedEvent as ConversationCreatedEvent, + type ConversationItem as ConversationItem, + type ConversationItemContent as ConversationItemContent, + type ConversationItemCreateEvent as ConversationItemCreateEvent, + type ConversationItemCreatedEvent as ConversationItemCreatedEvent, + type ConversationItemDeleteEvent as ConversationItemDeleteEvent, + type ConversationItemDeletedEvent as ConversationItemDeletedEvent, + type ConversationItemInputAudioTranscriptionCompletedEvent as ConversationItemInputAudioTranscriptionCompletedEvent, + type ConversationItemInputAudioTranscriptionDeltaEvent as ConversationItemInputAudioTranscriptionDeltaEvent, + type ConversationItemInputAudioTranscriptionFailedEvent as ConversationItemInputAudioTranscriptionFailedEvent, + type ConversationItemRetrieveEvent as ConversationItemRetrieveEvent, + type ConversationItemTruncateEvent as ConversationItemTruncateEvent, + type ConversationItemTruncatedEvent as ConversationItemTruncatedEvent, + type ConversationItemWithReference as ConversationItemWithReference, + type ErrorEvent as ErrorEvent, + type InputAudioBufferAppendEvent as InputAudioBufferAppendEvent, + type InputAudioBufferClearEvent as InputAudioBufferClearEvent, + type InputAudioBufferClearedEvent as InputAudioBufferClearedEvent, + type InputAudioBufferCommitEvent as InputAudioBufferCommitEvent, + type InputAudioBufferCommittedEvent as InputAudioBufferCommittedEvent, + type InputAudioBufferSpeechStartedEvent as InputAudioBufferSpeechStartedEvent, + type InputAudioBufferSpeechStoppedEvent as InputAudioBufferSpeechStoppedEvent, + type RateLimitsUpdatedEvent as RateLimitsUpdatedEvent, + type RealtimeClientEvent as RealtimeClientEvent, + type RealtimeResponse as RealtimeResponse, + type RealtimeResponseStatus as RealtimeResponseStatus, + type RealtimeResponseUsage as RealtimeResponseUsage, + type RealtimeServerEvent as RealtimeServerEvent, + type ResponseAudioDeltaEvent as ResponseAudioDeltaEvent, + type ResponseAudioDoneEvent as ResponseAudioDoneEvent, + type ResponseAudioTranscriptDeltaEvent as ResponseAudioTranscriptDeltaEvent, + type ResponseAudioTranscriptDoneEvent as ResponseAudioTranscriptDoneEvent, + type ResponseCancelEvent as ResponseCancelEvent, + type ResponseContentPartAddedEvent as ResponseContentPartAddedEvent, + type ResponseContentPartDoneEvent as ResponseContentPartDoneEvent, + type ResponseCreateEvent as ResponseCreateEvent, + type ResponseCreatedEvent as ResponseCreatedEvent, + type ResponseDoneEvent as ResponseDoneEvent, + type ResponseFunctionCallArgumentsDeltaEvent as ResponseFunctionCallArgumentsDeltaEvent, + type ResponseFunctionCallArgumentsDoneEvent as ResponseFunctionCallArgumentsDoneEvent, + type ResponseOutputItemAddedEvent as ResponseOutputItemAddedEvent, + type ResponseOutputItemDoneEvent as ResponseOutputItemDoneEvent, + type ResponseTextDeltaEvent as ResponseTextDeltaEvent, + type ResponseTextDoneEvent as ResponseTextDoneEvent, + type SessionCreatedEvent as SessionCreatedEvent, + type SessionUpdateEvent as SessionUpdateEvent, + type SessionUpdatedEvent as SessionUpdatedEvent, + type TranscriptionSessionUpdate as TranscriptionSessionUpdate, + type TranscriptionSessionUpdatedEvent as TranscriptionSessionUpdatedEvent, + }; + + export { + Assistants as Assistants, + type Assistant as Assistant, + type AssistantDeleted as AssistantDeleted, + type AssistantStreamEvent as AssistantStreamEvent, + type AssistantTool as AssistantTool, + type CodeInterpreterTool as CodeInterpreterTool, + type FileSearchTool as FileSearchTool, + type FunctionTool as FunctionTool, + type MessageStreamEvent as MessageStreamEvent, + type RunStepStreamEvent as RunStepStreamEvent, + type RunStreamEvent as RunStreamEvent, + type ThreadStreamEvent as ThreadStreamEvent, + type AssistantsPage as AssistantsPage, + type AssistantCreateParams as AssistantCreateParams, + type AssistantUpdateParams as AssistantUpdateParams, + type AssistantListParams as AssistantListParams, + }; + + export { + Threads as Threads, + type AssistantResponseFormatOption as AssistantResponseFormatOption, + type AssistantToolChoice as AssistantToolChoice, + type AssistantToolChoiceFunction as AssistantToolChoiceFunction, + type AssistantToolChoiceOption as AssistantToolChoiceOption, + type Thread as Thread, + type ThreadDeleted as ThreadDeleted, + type ThreadCreateParams as ThreadCreateParams, + type ThreadUpdateParams as ThreadUpdateParams, + type ThreadCreateAndRunParams as ThreadCreateAndRunParams, + type ThreadCreateAndRunParamsNonStreaming as ThreadCreateAndRunParamsNonStreaming, + type ThreadCreateAndRunParamsStreaming as ThreadCreateAndRunParamsStreaming, + type ThreadCreateAndRunPollParams, + type ThreadCreateAndRunStreamParams, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/index.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..a4d5a7ea6d77af84b49f3ed958cf20e7214851a9 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/index.ts @@ -0,0 +1,38 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export { + Assistants, + type Assistant, + type AssistantDeleted, + type AssistantStreamEvent, + type AssistantTool, + type CodeInterpreterTool, + type FileSearchTool, + type FunctionTool, + type MessageStreamEvent, + type RunStepStreamEvent, + type RunStreamEvent, + type ThreadStreamEvent, + type AssistantCreateParams, + type AssistantUpdateParams, + type AssistantListParams, + type AssistantsPage, +} from './assistants'; +export { Beta } from './beta'; +export { Realtime } from './realtime/index'; +export { + Threads, + type AssistantResponseFormatOption, + type AssistantToolChoice, + type AssistantToolChoiceFunction, + type AssistantToolChoiceOption, + type Thread, + type ThreadDeleted, + type ThreadCreateParams, + type ThreadUpdateParams, + type ThreadCreateAndRunParams, + type ThreadCreateAndRunParamsNonStreaming, + type ThreadCreateAndRunParamsStreaming, + type ThreadCreateAndRunPollParams, + type ThreadCreateAndRunStreamParams, +} from './threads/index'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/realtime.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/realtime.ts new file mode 100644 index 0000000000000000000000000000000000000000..1c5df27d93fef3d511b085488f8c4db20e3f88b0 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/realtime.ts @@ -0,0 +1,3 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export * from './realtime/index'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/realtime/index.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/realtime/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..ba51d8a6621f179985538cb1ea702d351a4f84ef --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/realtime/index.ts @@ -0,0 +1,9 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export { Realtime } from './realtime'; +export { Sessions, type Session, type SessionCreateResponse, type SessionCreateParams } from './sessions'; +export { + TranscriptionSessions, + type TranscriptionSession, + type TranscriptionSessionCreateParams, +} from './transcription-sessions'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/realtime/realtime.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/realtime/realtime.ts new file mode 100644 index 0000000000000000000000000000000000000000..4635c6762a5d21e038d9be36c17aeec0abb6a49d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/realtime/realtime.ts @@ -0,0 +1,2826 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../../core/resource'; +import * as RealtimeAPI from './realtime'; +import * as Shared from '../../shared'; +import * as SessionsAPI from './sessions'; +import { + Session as SessionsAPISession, + SessionCreateParams, + SessionCreateResponse, + Sessions, +} from './sessions'; +import * as TranscriptionSessionsAPI from './transcription-sessions'; +import { + TranscriptionSession, + TranscriptionSessionCreateParams, + TranscriptionSessions, +} from './transcription-sessions'; + +export class Realtime extends APIResource { + sessions: SessionsAPI.Sessions = new SessionsAPI.Sessions(this._client); + transcriptionSessions: TranscriptionSessionsAPI.TranscriptionSessions = + new TranscriptionSessionsAPI.TranscriptionSessions(this._client); +} + +/** + * Returned when a conversation is created. Emitted right after session creation. + */ +export interface ConversationCreatedEvent { + /** + * The conversation resource. + */ + conversation: ConversationCreatedEvent.Conversation; + + /** + * The unique ID of the server event. + */ + event_id: string; + + /** + * The event type, must be `conversation.created`. + */ + type: 'conversation.created'; +} + +export namespace ConversationCreatedEvent { + /** + * The conversation resource. + */ + export interface Conversation { + /** + * The unique ID of the conversation. + */ + id?: string; + + /** + * The object type, must be `realtime.conversation`. + */ + object?: 'realtime.conversation'; + } +} + +/** + * The item to add to the conversation. + */ +export interface ConversationItem { + /** + * The unique ID of the item, this can be generated by the client to help manage + * server-side context, but is not required because the server will generate one if + * not provided. + */ + id?: string; + + /** + * The arguments of the function call (for `function_call` items). + */ + arguments?: string; + + /** + * The ID of the function call (for `function_call` and `function_call_output` + * items). If passed on a `function_call_output` item, the server will check that a + * `function_call` item with the same ID exists in the conversation history. + */ + call_id?: string; + + /** + * The content of the message, applicable for `message` items. + * + * - Message items of role `system` support only `input_text` content + * - Message items of role `user` support `input_text` and `input_audio` content + * - Message items of role `assistant` support `text` content. + */ + content?: Array; + + /** + * The name of the function being called (for `function_call` items). + */ + name?: string; + + /** + * Identifier for the API object being returned - always `realtime.item`. + */ + object?: 'realtime.item'; + + /** + * The output of the function call (for `function_call_output` items). + */ + output?: string; + + /** + * The role of the message sender (`user`, `assistant`, `system`), only applicable + * for `message` items. + */ + role?: 'user' | 'assistant' | 'system'; + + /** + * The status of the item (`completed`, `incomplete`, `in_progress`). These have no + * effect on the conversation, but are accepted for consistency with the + * `conversation.item.created` event. + */ + status?: 'completed' | 'incomplete' | 'in_progress'; + + /** + * The type of the item (`message`, `function_call`, `function_call_output`). + */ + type?: 'message' | 'function_call' | 'function_call_output'; +} + +export interface ConversationItemContent { + /** + * ID of a previous conversation item to reference (for `item_reference` content + * types in `response.create` events). These can reference both client and server + * created items. + */ + id?: string; + + /** + * Base64-encoded audio bytes, used for `input_audio` content type. + */ + audio?: string; + + /** + * The text content, used for `input_text` and `text` content types. + */ + text?: string; + + /** + * The transcript of the audio, used for `input_audio` and `audio` content types. + */ + transcript?: string; + + /** + * The content type (`input_text`, `input_audio`, `item_reference`, `text`, + * `audio`). + */ + type?: 'input_text' | 'input_audio' | 'item_reference' | 'text' | 'audio'; +} + +/** + * Add a new Item to the Conversation's context, including messages, function + * calls, and function call responses. This event can be used both to populate a + * "history" of the conversation and to add new items mid-stream, but has the + * current limitation that it cannot populate assistant audio messages. + * + * If successful, the server will respond with a `conversation.item.created` event, + * otherwise an `error` event will be sent. + */ +export interface ConversationItemCreateEvent { + /** + * The item to add to the conversation. + */ + item: ConversationItem; + + /** + * The event type, must be `conversation.item.create`. + */ + type: 'conversation.item.create'; + + /** + * Optional client-generated ID used to identify this event. + */ + event_id?: string; + + /** + * The ID of the preceding item after which the new item will be inserted. If not + * set, the new item will be appended to the end of the conversation. If set to + * `root`, the new item will be added to the beginning of the conversation. If set + * to an existing ID, it allows an item to be inserted mid-conversation. If the ID + * cannot be found, an error will be returned and the item will not be added. + */ + previous_item_id?: string; +} + +/** + * Returned when a conversation item is created. There are several scenarios that + * produce this event: + * + * - The server is generating a Response, which if successful will produce either + * one or two Items, which will be of type `message` (role `assistant`) or type + * `function_call`. + * - The input audio buffer has been committed, either by the client or the server + * (in `server_vad` mode). The server will take the content of the input audio + * buffer and add it to a new user message Item. + * - The client has sent a `conversation.item.create` event to add a new Item to + * the Conversation. + */ +export interface ConversationItemCreatedEvent { + /** + * The unique ID of the server event. + */ + event_id: string; + + /** + * The item to add to the conversation. + */ + item: ConversationItem; + + /** + * The event type, must be `conversation.item.created`. + */ + type: 'conversation.item.created'; + + /** + * The ID of the preceding item in the Conversation context, allows the client to + * understand the order of the conversation. Can be `null` if the item has no + * predecessor. + */ + previous_item_id?: string | null; +} + +/** + * Send this event when you want to remove any item from the conversation history. + * The server will respond with a `conversation.item.deleted` event, unless the + * item does not exist in the conversation history, in which case the server will + * respond with an error. + */ +export interface ConversationItemDeleteEvent { + /** + * The ID of the item to delete. + */ + item_id: string; + + /** + * The event type, must be `conversation.item.delete`. + */ + type: 'conversation.item.delete'; + + /** + * Optional client-generated ID used to identify this event. + */ + event_id?: string; +} + +/** + * Returned when an item in the conversation is deleted by the client with a + * `conversation.item.delete` event. This event is used to synchronize the server's + * understanding of the conversation history with the client's view. + */ +export interface ConversationItemDeletedEvent { + /** + * The unique ID of the server event. + */ + event_id: string; + + /** + * The ID of the item that was deleted. + */ + item_id: string; + + /** + * The event type, must be `conversation.item.deleted`. + */ + type: 'conversation.item.deleted'; +} + +/** + * This event is the output of audio transcription for user audio written to the + * user audio buffer. Transcription begins when the input audio buffer is committed + * by the client or server (in `server_vad` mode). Transcription runs + * asynchronously with Response creation, so this event may come before or after + * the Response events. + * + * Realtime API models accept audio natively, and thus input transcription is a + * separate process run on a separate ASR (Automatic Speech Recognition) model. The + * transcript may diverge somewhat from the model's interpretation, and should be + * treated as a rough guide. + */ +export interface ConversationItemInputAudioTranscriptionCompletedEvent { + /** + * The index of the content part containing the audio. + */ + content_index: number; + + /** + * The unique ID of the server event. + */ + event_id: string; + + /** + * The ID of the user message item containing the audio. + */ + item_id: string; + + /** + * The transcribed text. + */ + transcript: string; + + /** + * The event type, must be `conversation.item.input_audio_transcription.completed`. + */ + type: 'conversation.item.input_audio_transcription.completed'; + + /** + * Usage statistics for the transcription. + */ + usage: + | ConversationItemInputAudioTranscriptionCompletedEvent.TranscriptTextUsageTokens + | ConversationItemInputAudioTranscriptionCompletedEvent.TranscriptTextUsageDuration; + + /** + * The log probabilities of the transcription. + */ + logprobs?: Array | null; +} + +export namespace ConversationItemInputAudioTranscriptionCompletedEvent { + /** + * Usage statistics for models billed by token usage. + */ + export interface TranscriptTextUsageTokens { + /** + * Number of input tokens billed for this request. + */ + input_tokens: number; + + /** + * Number of output tokens generated. + */ + output_tokens: number; + + /** + * Total number of tokens used (input + output). + */ + total_tokens: number; + + /** + * The type of the usage object. Always `tokens` for this variant. + */ + type: 'tokens'; + + /** + * Details about the input tokens billed for this request. + */ + input_token_details?: TranscriptTextUsageTokens.InputTokenDetails; + } + + export namespace TranscriptTextUsageTokens { + /** + * Details about the input tokens billed for this request. + */ + export interface InputTokenDetails { + /** + * Number of audio tokens billed for this request. + */ + audio_tokens?: number; + + /** + * Number of text tokens billed for this request. + */ + text_tokens?: number; + } + } + + /** + * Usage statistics for models billed by audio input duration. + */ + export interface TranscriptTextUsageDuration { + /** + * Duration of the input audio in seconds. + */ + seconds: number; + + /** + * The type of the usage object. Always `duration` for this variant. + */ + type: 'duration'; + } + + /** + * A log probability object. + */ + export interface Logprob { + /** + * The token that was used to generate the log probability. + */ + token: string; + + /** + * The bytes that were used to generate the log probability. + */ + bytes: Array; + + /** + * The log probability of the token. + */ + logprob: number; + } +} + +/** + * Returned when the text value of an input audio transcription content part is + * updated. + */ +export interface ConversationItemInputAudioTranscriptionDeltaEvent { + /** + * The unique ID of the server event. + */ + event_id: string; + + /** + * The ID of the item. + */ + item_id: string; + + /** + * The event type, must be `conversation.item.input_audio_transcription.delta`. + */ + type: 'conversation.item.input_audio_transcription.delta'; + + /** + * The index of the content part in the item's content array. + */ + content_index?: number; + + /** + * The text delta. + */ + delta?: string; + + /** + * The log probabilities of the transcription. + */ + logprobs?: Array | null; +} + +export namespace ConversationItemInputAudioTranscriptionDeltaEvent { + /** + * A log probability object. + */ + export interface Logprob { + /** + * The token that was used to generate the log probability. + */ + token: string; + + /** + * The bytes that were used to generate the log probability. + */ + bytes: Array; + + /** + * The log probability of the token. + */ + logprob: number; + } +} + +/** + * Returned when input audio transcription is configured, and a transcription + * request for a user message failed. These events are separate from other `error` + * events so that the client can identify the related Item. + */ +export interface ConversationItemInputAudioTranscriptionFailedEvent { + /** + * The index of the content part containing the audio. + */ + content_index: number; + + /** + * Details of the transcription error. + */ + error: ConversationItemInputAudioTranscriptionFailedEvent.Error; + + /** + * The unique ID of the server event. + */ + event_id: string; + + /** + * The ID of the user message item. + */ + item_id: string; + + /** + * The event type, must be `conversation.item.input_audio_transcription.failed`. + */ + type: 'conversation.item.input_audio_transcription.failed'; +} + +export namespace ConversationItemInputAudioTranscriptionFailedEvent { + /** + * Details of the transcription error. + */ + export interface Error { + /** + * Error code, if any. + */ + code?: string; + + /** + * A human-readable error message. + */ + message?: string; + + /** + * Parameter related to the error, if any. + */ + param?: string; + + /** + * The type of error. + */ + type?: string; + } +} + +/** + * Send this event when you want to retrieve the server's representation of a + * specific item in the conversation history. This is useful, for example, to + * inspect user audio after noise cancellation and VAD. The server will respond + * with a `conversation.item.retrieved` event, unless the item does not exist in + * the conversation history, in which case the server will respond with an error. + */ +export interface ConversationItemRetrieveEvent { + /** + * The ID of the item to retrieve. + */ + item_id: string; + + /** + * The event type, must be `conversation.item.retrieve`. + */ + type: 'conversation.item.retrieve'; + + /** + * Optional client-generated ID used to identify this event. + */ + event_id?: string; +} + +/** + * Send this event to truncate a previous assistant message’s audio. The server + * will produce audio faster than realtime, so this event is useful when the user + * interrupts to truncate audio that has already been sent to the client but not + * yet played. This will synchronize the server's understanding of the audio with + * the client's playback. + * + * Truncating audio will delete the server-side text transcript to ensure there is + * not text in the context that hasn't been heard by the user. + * + * If successful, the server will respond with a `conversation.item.truncated` + * event. + */ +export interface ConversationItemTruncateEvent { + /** + * Inclusive duration up to which audio is truncated, in milliseconds. If the + * audio_end_ms is greater than the actual audio duration, the server will respond + * with an error. + */ + audio_end_ms: number; + + /** + * The index of the content part to truncate. Set this to 0. + */ + content_index: number; + + /** + * The ID of the assistant message item to truncate. Only assistant message items + * can be truncated. + */ + item_id: string; + + /** + * The event type, must be `conversation.item.truncate`. + */ + type: 'conversation.item.truncate'; + + /** + * Optional client-generated ID used to identify this event. + */ + event_id?: string; +} + +/** + * Returned when an earlier assistant audio message item is truncated by the client + * with a `conversation.item.truncate` event. This event is used to synchronize the + * server's understanding of the audio with the client's playback. + * + * This action will truncate the audio and remove the server-side text transcript + * to ensure there is no text in the context that hasn't been heard by the user. + */ +export interface ConversationItemTruncatedEvent { + /** + * The duration up to which the audio was truncated, in milliseconds. + */ + audio_end_ms: number; + + /** + * The index of the content part that was truncated. + */ + content_index: number; + + /** + * The unique ID of the server event. + */ + event_id: string; + + /** + * The ID of the assistant message item that was truncated. + */ + item_id: string; + + /** + * The event type, must be `conversation.item.truncated`. + */ + type: 'conversation.item.truncated'; +} + +/** + * The item to add to the conversation. + */ +export interface ConversationItemWithReference { + /** + * For an item of type (`message` | `function_call` | `function_call_output`) this + * field allows the client to assign the unique ID of the item. It is not required + * because the server will generate one if not provided. + * + * For an item of type `item_reference`, this field is required and is a reference + * to any item that has previously existed in the conversation. + */ + id?: string; + + /** + * The arguments of the function call (for `function_call` items). + */ + arguments?: string; + + /** + * The ID of the function call (for `function_call` and `function_call_output` + * items). If passed on a `function_call_output` item, the server will check that a + * `function_call` item with the same ID exists in the conversation history. + */ + call_id?: string; + + /** + * The content of the message, applicable for `message` items. + * + * - Message items of role `system` support only `input_text` content + * - Message items of role `user` support `input_text` and `input_audio` content + * - Message items of role `assistant` support `text` content. + */ + content?: Array; + + /** + * The name of the function being called (for `function_call` items). + */ + name?: string; + + /** + * Identifier for the API object being returned - always `realtime.item`. + */ + object?: 'realtime.item'; + + /** + * The output of the function call (for `function_call_output` items). + */ + output?: string; + + /** + * The role of the message sender (`user`, `assistant`, `system`), only applicable + * for `message` items. + */ + role?: 'user' | 'assistant' | 'system'; + + /** + * The status of the item (`completed`, `incomplete`, `in_progress`). These have no + * effect on the conversation, but are accepted for consistency with the + * `conversation.item.created` event. + */ + status?: 'completed' | 'incomplete' | 'in_progress'; + + /** + * The type of the item (`message`, `function_call`, `function_call_output`, + * `item_reference`). + */ + type?: 'message' | 'function_call' | 'function_call_output' | 'item_reference'; +} + +export namespace ConversationItemWithReference { + export interface Content { + /** + * ID of a previous conversation item to reference (for `item_reference` content + * types in `response.create` events). These can reference both client and server + * created items. + */ + id?: string; + + /** + * Base64-encoded audio bytes, used for `input_audio` content type. + */ + audio?: string; + + /** + * The text content, used for `input_text` and `text` content types. + */ + text?: string; + + /** + * The transcript of the audio, used for `input_audio` content type. + */ + transcript?: string; + + /** + * The content type (`input_text`, `input_audio`, `item_reference`, `text`). + */ + type?: 'input_text' | 'input_audio' | 'item_reference' | 'text'; + } +} + +/** + * Returned when an error occurs, which could be a client problem or a server + * problem. Most errors are recoverable and the session will stay open, we + * recommend to implementors to monitor and log error messages by default. + */ +export interface ErrorEvent { + /** + * Details of the error. + */ + error: ErrorEvent.Error; + + /** + * The unique ID of the server event. + */ + event_id: string; + + /** + * The event type, must be `error`. + */ + type: 'error'; +} + +export namespace ErrorEvent { + /** + * Details of the error. + */ + export interface Error { + /** + * A human-readable error message. + */ + message: string; + + /** + * The type of error (e.g., "invalid_request_error", "server_error"). + */ + type: string; + + /** + * Error code, if any. + */ + code?: string | null; + + /** + * The event_id of the client event that caused the error, if applicable. + */ + event_id?: string | null; + + /** + * Parameter related to the error, if any. + */ + param?: string | null; + } +} + +/** + * Send this event to append audio bytes to the input audio buffer. The audio + * buffer is temporary storage you can write to and later commit. In Server VAD + * mode, the audio buffer is used to detect speech and the server will decide when + * to commit. When Server VAD is disabled, you must commit the audio buffer + * manually. + * + * The client may choose how much audio to place in each event up to a maximum of + * 15 MiB, for example streaming smaller chunks from the client may allow the VAD + * to be more responsive. Unlike made other client events, the server will not send + * a confirmation response to this event. + */ +export interface InputAudioBufferAppendEvent { + /** + * Base64-encoded audio bytes. This must be in the format specified by the + * `input_audio_format` field in the session configuration. + */ + audio: string; + + /** + * The event type, must be `input_audio_buffer.append`. + */ + type: 'input_audio_buffer.append'; + + /** + * Optional client-generated ID used to identify this event. + */ + event_id?: string; +} + +/** + * Send this event to clear the audio bytes in the buffer. The server will respond + * with an `input_audio_buffer.cleared` event. + */ +export interface InputAudioBufferClearEvent { + /** + * The event type, must be `input_audio_buffer.clear`. + */ + type: 'input_audio_buffer.clear'; + + /** + * Optional client-generated ID used to identify this event. + */ + event_id?: string; +} + +/** + * Returned when the input audio buffer is cleared by the client with a + * `input_audio_buffer.clear` event. + */ +export interface InputAudioBufferClearedEvent { + /** + * The unique ID of the server event. + */ + event_id: string; + + /** + * The event type, must be `input_audio_buffer.cleared`. + */ + type: 'input_audio_buffer.cleared'; +} + +/** + * Send this event to commit the user input audio buffer, which will create a new + * user message item in the conversation. This event will produce an error if the + * input audio buffer is empty. When in Server VAD mode, the client does not need + * to send this event, the server will commit the audio buffer automatically. + * + * Committing the input audio buffer will trigger input audio transcription (if + * enabled in session configuration), but it will not create a response from the + * model. The server will respond with an `input_audio_buffer.committed` event. + */ +export interface InputAudioBufferCommitEvent { + /** + * The event type, must be `input_audio_buffer.commit`. + */ + type: 'input_audio_buffer.commit'; + + /** + * Optional client-generated ID used to identify this event. + */ + event_id?: string; +} + +/** + * Returned when an input audio buffer is committed, either by the client or + * automatically in server VAD mode. The `item_id` property is the ID of the user + * message item that will be created, thus a `conversation.item.created` event will + * also be sent to the client. + */ +export interface InputAudioBufferCommittedEvent { + /** + * The unique ID of the server event. + */ + event_id: string; + + /** + * The ID of the user message item that will be created. + */ + item_id: string; + + /** + * The event type, must be `input_audio_buffer.committed`. + */ + type: 'input_audio_buffer.committed'; + + /** + * The ID of the preceding item after which the new item will be inserted. Can be + * `null` if the item has no predecessor. + */ + previous_item_id?: string | null; +} + +/** + * Sent by the server when in `server_vad` mode to indicate that speech has been + * detected in the audio buffer. This can happen any time audio is added to the + * buffer (unless speech is already detected). The client may want to use this + * event to interrupt audio playback or provide visual feedback to the user. + * + * The client should expect to receive a `input_audio_buffer.speech_stopped` event + * when speech stops. The `item_id` property is the ID of the user message item + * that will be created when speech stops and will also be included in the + * `input_audio_buffer.speech_stopped` event (unless the client manually commits + * the audio buffer during VAD activation). + */ +export interface InputAudioBufferSpeechStartedEvent { + /** + * Milliseconds from the start of all audio written to the buffer during the + * session when speech was first detected. This will correspond to the beginning of + * audio sent to the model, and thus includes the `prefix_padding_ms` configured in + * the Session. + */ + audio_start_ms: number; + + /** + * The unique ID of the server event. + */ + event_id: string; + + /** + * The ID of the user message item that will be created when speech stops. + */ + item_id: string; + + /** + * The event type, must be `input_audio_buffer.speech_started`. + */ + type: 'input_audio_buffer.speech_started'; +} + +/** + * Returned in `server_vad` mode when the server detects the end of speech in the + * audio buffer. The server will also send an `conversation.item.created` event + * with the user message item that is created from the audio buffer. + */ +export interface InputAudioBufferSpeechStoppedEvent { + /** + * Milliseconds since the session started when speech stopped. This will correspond + * to the end of audio sent to the model, and thus includes the + * `min_silence_duration_ms` configured in the Session. + */ + audio_end_ms: number; + + /** + * The unique ID of the server event. + */ + event_id: string; + + /** + * The ID of the user message item that will be created. + */ + item_id: string; + + /** + * The event type, must be `input_audio_buffer.speech_stopped`. + */ + type: 'input_audio_buffer.speech_stopped'; +} + +/** + * Emitted at the beginning of a Response to indicate the updated rate limits. When + * a Response is created some tokens will be "reserved" for the output tokens, the + * rate limits shown here reflect that reservation, which is then adjusted + * accordingly once the Response is completed. + */ +export interface RateLimitsUpdatedEvent { + /** + * The unique ID of the server event. + */ + event_id: string; + + /** + * List of rate limit information. + */ + rate_limits: Array; + + /** + * The event type, must be `rate_limits.updated`. + */ + type: 'rate_limits.updated'; +} + +export namespace RateLimitsUpdatedEvent { + export interface RateLimit { + /** + * The maximum allowed value for the rate limit. + */ + limit?: number; + + /** + * The name of the rate limit (`requests`, `tokens`). + */ + name?: 'requests' | 'tokens'; + + /** + * The remaining value before the limit is reached. + */ + remaining?: number; + + /** + * Seconds until the rate limit resets. + */ + reset_seconds?: number; + } +} + +/** + * A realtime client event. + */ +export type RealtimeClientEvent = + | ConversationItemCreateEvent + | ConversationItemDeleteEvent + | ConversationItemRetrieveEvent + | ConversationItemTruncateEvent + | InputAudioBufferAppendEvent + | InputAudioBufferClearEvent + | RealtimeClientEvent.OutputAudioBufferClear + | InputAudioBufferCommitEvent + | ResponseCancelEvent + | ResponseCreateEvent + | SessionUpdateEvent + | TranscriptionSessionUpdate; + +export namespace RealtimeClientEvent { + /** + * **WebRTC Only:** Emit to cut off the current audio response. This will trigger + * the server to stop generating audio and emit a `output_audio_buffer.cleared` + * event. This event should be preceded by a `response.cancel` client event to stop + * the generation of the current response. + * [Learn more](https://platform.openai.com/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc). + */ + export interface OutputAudioBufferClear { + /** + * The event type, must be `output_audio_buffer.clear`. + */ + type: 'output_audio_buffer.clear'; + + /** + * The unique ID of the client event used for error handling. + */ + event_id?: string; + } +} + +/** + * The response resource. + */ +export interface RealtimeResponse { + /** + * The unique ID of the response. + */ + id?: string; + + /** + * Which conversation the response is added to, determined by the `conversation` + * field in the `response.create` event. If `auto`, the response will be added to + * the default conversation and the value of `conversation_id` will be an id like + * `conv_1234`. If `none`, the response will not be added to any conversation and + * the value of `conversation_id` will be `null`. If responses are being triggered + * by server VAD, the response will be added to the default conversation, thus the + * `conversation_id` will be an id like `conv_1234`. + */ + conversation_id?: string; + + /** + * Maximum number of output tokens for a single assistant response, inclusive of + * tool calls, that was used in this response. + */ + max_output_tokens?: number | 'inf'; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; + + /** + * The set of modalities the model used to respond. If there are multiple + * modalities, the model will pick one, for example if `modalities` is + * `["text", "audio"]`, the model could be responding in either text or audio. + */ + modalities?: Array<'text' | 'audio'>; + + /** + * The object type, must be `realtime.response`. + */ + object?: 'realtime.response'; + + /** + * The list of output items generated by the response. + */ + output?: Array; + + /** + * The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. + */ + output_audio_format?: 'pcm16' | 'g711_ulaw' | 'g711_alaw'; + + /** + * The final status of the response (`completed`, `cancelled`, `failed`, or + * `incomplete`, `in_progress`). + */ + status?: 'completed' | 'cancelled' | 'failed' | 'incomplete' | 'in_progress'; + + /** + * Additional details about the status. + */ + status_details?: RealtimeResponseStatus; + + /** + * Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8. + */ + temperature?: number; + + /** + * Usage statistics for the Response, this will correspond to billing. A Realtime + * API session will maintain a conversation context and append new Items to the + * Conversation, thus output from previous turns (text and audio tokens) will + * become the input for later turns. + */ + usage?: RealtimeResponseUsage; + + /** + * The voice the model used to respond. Current voice options are `alloy`, `ash`, + * `ballad`, `coral`, `echo`, `sage`, `shimmer`, and `verse`. + */ + voice?: (string & {}) | 'alloy' | 'ash' | 'ballad' | 'coral' | 'echo' | 'sage' | 'shimmer' | 'verse'; +} + +/** + * Additional details about the status. + */ +export interface RealtimeResponseStatus { + /** + * A description of the error that caused the response to fail, populated when the + * `status` is `failed`. + */ + error?: RealtimeResponseStatus.Error; + + /** + * The reason the Response did not complete. For a `cancelled` Response, one of + * `turn_detected` (the server VAD detected a new start of speech) or + * `client_cancelled` (the client sent a cancel event). For an `incomplete` + * Response, one of `max_output_tokens` or `content_filter` (the server-side safety + * filter activated and cut off the response). + */ + reason?: 'turn_detected' | 'client_cancelled' | 'max_output_tokens' | 'content_filter'; + + /** + * The type of error that caused the response to fail, corresponding with the + * `status` field (`completed`, `cancelled`, `incomplete`, `failed`). + */ + type?: 'completed' | 'cancelled' | 'incomplete' | 'failed'; +} + +export namespace RealtimeResponseStatus { + /** + * A description of the error that caused the response to fail, populated when the + * `status` is `failed`. + */ + export interface Error { + /** + * Error code, if any. + */ + code?: string; + + /** + * The type of error. + */ + type?: string; + } +} + +/** + * Usage statistics for the Response, this will correspond to billing. A Realtime + * API session will maintain a conversation context and append new Items to the + * Conversation, thus output from previous turns (text and audio tokens) will + * become the input for later turns. + */ +export interface RealtimeResponseUsage { + /** + * Details about the input tokens used in the Response. + */ + input_token_details?: RealtimeResponseUsage.InputTokenDetails; + + /** + * The number of input tokens used in the Response, including text and audio + * tokens. + */ + input_tokens?: number; + + /** + * Details about the output tokens used in the Response. + */ + output_token_details?: RealtimeResponseUsage.OutputTokenDetails; + + /** + * The number of output tokens sent in the Response, including text and audio + * tokens. + */ + output_tokens?: number; + + /** + * The total number of tokens in the Response including input and output text and + * audio tokens. + */ + total_tokens?: number; +} + +export namespace RealtimeResponseUsage { + /** + * Details about the input tokens used in the Response. + */ + export interface InputTokenDetails { + /** + * The number of audio tokens used in the Response. + */ + audio_tokens?: number; + + /** + * The number of cached tokens used in the Response. + */ + cached_tokens?: number; + + /** + * The number of text tokens used in the Response. + */ + text_tokens?: number; + } + + /** + * Details about the output tokens used in the Response. + */ + export interface OutputTokenDetails { + /** + * The number of audio tokens used in the Response. + */ + audio_tokens?: number; + + /** + * The number of text tokens used in the Response. + */ + text_tokens?: number; + } +} + +/** + * A realtime server event. + */ +export type RealtimeServerEvent = + | ConversationCreatedEvent + | ConversationItemCreatedEvent + | ConversationItemDeletedEvent + | ConversationItemInputAudioTranscriptionCompletedEvent + | ConversationItemInputAudioTranscriptionDeltaEvent + | ConversationItemInputAudioTranscriptionFailedEvent + | RealtimeServerEvent.ConversationItemRetrieved + | ConversationItemTruncatedEvent + | ErrorEvent + | InputAudioBufferClearedEvent + | InputAudioBufferCommittedEvent + | InputAudioBufferSpeechStartedEvent + | InputAudioBufferSpeechStoppedEvent + | RateLimitsUpdatedEvent + | ResponseAudioDeltaEvent + | ResponseAudioDoneEvent + | ResponseAudioTranscriptDeltaEvent + | ResponseAudioTranscriptDoneEvent + | ResponseContentPartAddedEvent + | ResponseContentPartDoneEvent + | ResponseCreatedEvent + | ResponseDoneEvent + | ResponseFunctionCallArgumentsDeltaEvent + | ResponseFunctionCallArgumentsDoneEvent + | ResponseOutputItemAddedEvent + | ResponseOutputItemDoneEvent + | ResponseTextDeltaEvent + | ResponseTextDoneEvent + | SessionCreatedEvent + | SessionUpdatedEvent + | TranscriptionSessionUpdatedEvent + | RealtimeServerEvent.OutputAudioBufferStarted + | RealtimeServerEvent.OutputAudioBufferStopped + | RealtimeServerEvent.OutputAudioBufferCleared; + +export namespace RealtimeServerEvent { + /** + * Returned when a conversation item is retrieved with + * `conversation.item.retrieve`. + */ + export interface ConversationItemRetrieved { + /** + * The unique ID of the server event. + */ + event_id: string; + + /** + * The item to add to the conversation. + */ + item: RealtimeAPI.ConversationItem; + + /** + * The event type, must be `conversation.item.retrieved`. + */ + type: 'conversation.item.retrieved'; + } + + /** + * **WebRTC Only:** Emitted when the server begins streaming audio to the client. + * This event is emitted after an audio content part has been added + * (`response.content_part.added`) to the response. + * [Learn more](https://platform.openai.com/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc). + */ + export interface OutputAudioBufferStarted { + /** + * The unique ID of the server event. + */ + event_id: string; + + /** + * The unique ID of the response that produced the audio. + */ + response_id: string; + + /** + * The event type, must be `output_audio_buffer.started`. + */ + type: 'output_audio_buffer.started'; + } + + /** + * **WebRTC Only:** Emitted when the output audio buffer has been completely + * drained on the server, and no more audio is forthcoming. This event is emitted + * after the full response data has been sent to the client (`response.done`). + * [Learn more](https://platform.openai.com/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc). + */ + export interface OutputAudioBufferStopped { + /** + * The unique ID of the server event. + */ + event_id: string; + + /** + * The unique ID of the response that produced the audio. + */ + response_id: string; + + /** + * The event type, must be `output_audio_buffer.stopped`. + */ + type: 'output_audio_buffer.stopped'; + } + + /** + * **WebRTC Only:** Emitted when the output audio buffer is cleared. This happens + * either in VAD mode when the user has interrupted + * (`input_audio_buffer.speech_started`), or when the client has emitted the + * `output_audio_buffer.clear` event to manually cut off the current audio + * response. + * [Learn more](https://platform.openai.com/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc). + */ + export interface OutputAudioBufferCleared { + /** + * The unique ID of the server event. + */ + event_id: string; + + /** + * The unique ID of the response that produced the audio. + */ + response_id: string; + + /** + * The event type, must be `output_audio_buffer.cleared`. + */ + type: 'output_audio_buffer.cleared'; + } +} + +/** + * Returned when the model-generated audio is updated. + */ +export interface ResponseAudioDeltaEvent { + /** + * The index of the content part in the item's content array. + */ + content_index: number; + + /** + * Base64-encoded audio data delta. + */ + delta: string; + + /** + * The unique ID of the server event. + */ + event_id: string; + + /** + * The ID of the item. + */ + item_id: string; + + /** + * The index of the output item in the response. + */ + output_index: number; + + /** + * The ID of the response. + */ + response_id: string; + + /** + * The event type, must be `response.audio.delta`. + */ + type: 'response.audio.delta'; +} + +/** + * Returned when the model-generated audio is done. Also emitted when a Response is + * interrupted, incomplete, or cancelled. + */ +export interface ResponseAudioDoneEvent { + /** + * The index of the content part in the item's content array. + */ + content_index: number; + + /** + * The unique ID of the server event. + */ + event_id: string; + + /** + * The ID of the item. + */ + item_id: string; + + /** + * The index of the output item in the response. + */ + output_index: number; + + /** + * The ID of the response. + */ + response_id: string; + + /** + * The event type, must be `response.audio.done`. + */ + type: 'response.audio.done'; +} + +/** + * Returned when the model-generated transcription of audio output is updated. + */ +export interface ResponseAudioTranscriptDeltaEvent { + /** + * The index of the content part in the item's content array. + */ + content_index: number; + + /** + * The transcript delta. + */ + delta: string; + + /** + * The unique ID of the server event. + */ + event_id: string; + + /** + * The ID of the item. + */ + item_id: string; + + /** + * The index of the output item in the response. + */ + output_index: number; + + /** + * The ID of the response. + */ + response_id: string; + + /** + * The event type, must be `response.audio_transcript.delta`. + */ + type: 'response.audio_transcript.delta'; +} + +/** + * Returned when the model-generated transcription of audio output is done + * streaming. Also emitted when a Response is interrupted, incomplete, or + * cancelled. + */ +export interface ResponseAudioTranscriptDoneEvent { + /** + * The index of the content part in the item's content array. + */ + content_index: number; + + /** + * The unique ID of the server event. + */ + event_id: string; + + /** + * The ID of the item. + */ + item_id: string; + + /** + * The index of the output item in the response. + */ + output_index: number; + + /** + * The ID of the response. + */ + response_id: string; + + /** + * The final transcript of the audio. + */ + transcript: string; + + /** + * The event type, must be `response.audio_transcript.done`. + */ + type: 'response.audio_transcript.done'; +} + +/** + * Send this event to cancel an in-progress response. The server will respond with + * a `response.done` event with a status of `response.status=cancelled`. If there + * is no response to cancel, the server will respond with an error. + */ +export interface ResponseCancelEvent { + /** + * The event type, must be `response.cancel`. + */ + type: 'response.cancel'; + + /** + * Optional client-generated ID used to identify this event. + */ + event_id?: string; + + /** + * A specific response ID to cancel - if not provided, will cancel an in-progress + * response in the default conversation. + */ + response_id?: string; +} + +/** + * Returned when a new content part is added to an assistant message item during + * response generation. + */ +export interface ResponseContentPartAddedEvent { + /** + * The index of the content part in the item's content array. + */ + content_index: number; + + /** + * The unique ID of the server event. + */ + event_id: string; + + /** + * The ID of the item to which the content part was added. + */ + item_id: string; + + /** + * The index of the output item in the response. + */ + output_index: number; + + /** + * The content part that was added. + */ + part: ResponseContentPartAddedEvent.Part; + + /** + * The ID of the response. + */ + response_id: string; + + /** + * The event type, must be `response.content_part.added`. + */ + type: 'response.content_part.added'; +} + +export namespace ResponseContentPartAddedEvent { + /** + * The content part that was added. + */ + export interface Part { + /** + * Base64-encoded audio data (if type is "audio"). + */ + audio?: string; + + /** + * The text content (if type is "text"). + */ + text?: string; + + /** + * The transcript of the audio (if type is "audio"). + */ + transcript?: string; + + /** + * The content type ("text", "audio"). + */ + type?: 'text' | 'audio'; + } +} + +/** + * Returned when a content part is done streaming in an assistant message item. + * Also emitted when a Response is interrupted, incomplete, or cancelled. + */ +export interface ResponseContentPartDoneEvent { + /** + * The index of the content part in the item's content array. + */ + content_index: number; + + /** + * The unique ID of the server event. + */ + event_id: string; + + /** + * The ID of the item. + */ + item_id: string; + + /** + * The index of the output item in the response. + */ + output_index: number; + + /** + * The content part that is done. + */ + part: ResponseContentPartDoneEvent.Part; + + /** + * The ID of the response. + */ + response_id: string; + + /** + * The event type, must be `response.content_part.done`. + */ + type: 'response.content_part.done'; +} + +export namespace ResponseContentPartDoneEvent { + /** + * The content part that is done. + */ + export interface Part { + /** + * Base64-encoded audio data (if type is "audio"). + */ + audio?: string; + + /** + * The text content (if type is "text"). + */ + text?: string; + + /** + * The transcript of the audio (if type is "audio"). + */ + transcript?: string; + + /** + * The content type ("text", "audio"). + */ + type?: 'text' | 'audio'; + } +} + +/** + * This event instructs the server to create a Response, which means triggering + * model inference. When in Server VAD mode, the server will create Responses + * automatically. + * + * A Response will include at least one Item, and may have two, in which case the + * second will be a function call. These Items will be appended to the conversation + * history. + * + * The server will respond with a `response.created` event, events for Items and + * content created, and finally a `response.done` event to indicate the Response is + * complete. + * + * The `response.create` event includes inference configuration like + * `instructions`, and `temperature`. These fields will override the Session's + * configuration for this Response only. + */ +export interface ResponseCreateEvent { + /** + * The event type, must be `response.create`. + */ + type: 'response.create'; + + /** + * Optional client-generated ID used to identify this event. + */ + event_id?: string; + + /** + * Create a new Realtime response with these parameters + */ + response?: ResponseCreateEvent.Response; +} + +export namespace ResponseCreateEvent { + /** + * Create a new Realtime response with these parameters + */ + export interface Response { + /** + * Controls which conversation the response is added to. Currently supports `auto` + * and `none`, with `auto` as the default value. The `auto` value means that the + * contents of the response will be added to the default conversation. Set this to + * `none` to create an out-of-band response which will not add items to default + * conversation. + */ + conversation?: (string & {}) | 'auto' | 'none'; + + /** + * Input items to include in the prompt for the model. Using this field creates a + * new context for this Response instead of using the default conversation. An + * empty array `[]` will clear the context for this Response. Note that this can + * include references to items from the default conversation. + */ + input?: Array; + + /** + * The default system instructions (i.e. system message) prepended to model calls. + * This field allows the client to guide the model on desired responses. The model + * can be instructed on response content and format, (e.g. "be extremely succinct", + * "act friendly", "here are examples of good responses") and on audio behavior + * (e.g. "talk quickly", "inject emotion into your voice", "laugh frequently"). The + * instructions are not guaranteed to be followed by the model, but they provide + * guidance to the model on the desired behavior. + * + * Note that the server sets default instructions which will be used if this field + * is not set and are visible in the `session.created` event at the start of the + * session. + */ + instructions?: string; + + /** + * Maximum number of output tokens for a single assistant response, inclusive of + * tool calls. Provide an integer between 1 and 4096 to limit output tokens, or + * `inf` for the maximum available tokens for a given model. Defaults to `inf`. + */ + max_response_output_tokens?: number | 'inf'; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; + + /** + * The set of modalities the model can respond with. To disable audio, set this to + * ["text"]. + */ + modalities?: Array<'text' | 'audio'>; + + /** + * The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. + */ + output_audio_format?: 'pcm16' | 'g711_ulaw' | 'g711_alaw'; + + /** + * Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8. + */ + temperature?: number; + + /** + * How the model chooses tools. Options are `auto`, `none`, `required`, or specify + * a function, like `{"type": "function", "function": {"name": "my_function"}}`. + */ + tool_choice?: string; + + /** + * Tools (functions) available to the model. + */ + tools?: Array; + + /** + * The voice the model uses to respond. Voice cannot be changed during the session + * once the model has responded with audio at least once. Current voice options are + * `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`, `shimmer`, and `verse`. + */ + voice?: (string & {}) | 'alloy' | 'ash' | 'ballad' | 'coral' | 'echo' | 'sage' | 'shimmer' | 'verse'; + } + + export namespace Response { + export interface Tool { + /** + * The description of the function, including guidance on when and how to call it, + * and guidance about what to tell the user when calling (if anything). + */ + description?: string; + + /** + * The name of the function. + */ + name?: string; + + /** + * Parameters of the function in JSON Schema. + */ + parameters?: unknown; + + /** + * The type of the tool, i.e. `function`. + */ + type?: 'function'; + } + } +} + +/** + * Returned when a new Response is created. The first event of response creation, + * where the response is in an initial state of `in_progress`. + */ +export interface ResponseCreatedEvent { + /** + * The unique ID of the server event. + */ + event_id: string; + + /** + * The response resource. + */ + response: RealtimeResponse; + + /** + * The event type, must be `response.created`. + */ + type: 'response.created'; +} + +/** + * Returned when a Response is done streaming. Always emitted, no matter the final + * state. The Response object included in the `response.done` event will include + * all output Items in the Response but will omit the raw audio data. + */ +export interface ResponseDoneEvent { + /** + * The unique ID of the server event. + */ + event_id: string; + + /** + * The response resource. + */ + response: RealtimeResponse; + + /** + * The event type, must be `response.done`. + */ + type: 'response.done'; +} + +/** + * Returned when the model-generated function call arguments are updated. + */ +export interface ResponseFunctionCallArgumentsDeltaEvent { + /** + * The ID of the function call. + */ + call_id: string; + + /** + * The arguments delta as a JSON string. + */ + delta: string; + + /** + * The unique ID of the server event. + */ + event_id: string; + + /** + * The ID of the function call item. + */ + item_id: string; + + /** + * The index of the output item in the response. + */ + output_index: number; + + /** + * The ID of the response. + */ + response_id: string; + + /** + * The event type, must be `response.function_call_arguments.delta`. + */ + type: 'response.function_call_arguments.delta'; +} + +/** + * Returned when the model-generated function call arguments are done streaming. + * Also emitted when a Response is interrupted, incomplete, or cancelled. + */ +export interface ResponseFunctionCallArgumentsDoneEvent { + /** + * The final arguments as a JSON string. + */ + arguments: string; + + /** + * The ID of the function call. + */ + call_id: string; + + /** + * The unique ID of the server event. + */ + event_id: string; + + /** + * The ID of the function call item. + */ + item_id: string; + + /** + * The index of the output item in the response. + */ + output_index: number; + + /** + * The ID of the response. + */ + response_id: string; + + /** + * The event type, must be `response.function_call_arguments.done`. + */ + type: 'response.function_call_arguments.done'; +} + +/** + * Returned when a new Item is created during Response generation. + */ +export interface ResponseOutputItemAddedEvent { + /** + * The unique ID of the server event. + */ + event_id: string; + + /** + * The item to add to the conversation. + */ + item: ConversationItem; + + /** + * The index of the output item in the Response. + */ + output_index: number; + + /** + * The ID of the Response to which the item belongs. + */ + response_id: string; + + /** + * The event type, must be `response.output_item.added`. + */ + type: 'response.output_item.added'; +} + +/** + * Returned when an Item is done streaming. Also emitted when a Response is + * interrupted, incomplete, or cancelled. + */ +export interface ResponseOutputItemDoneEvent { + /** + * The unique ID of the server event. + */ + event_id: string; + + /** + * The item to add to the conversation. + */ + item: ConversationItem; + + /** + * The index of the output item in the Response. + */ + output_index: number; + + /** + * The ID of the Response to which the item belongs. + */ + response_id: string; + + /** + * The event type, must be `response.output_item.done`. + */ + type: 'response.output_item.done'; +} + +/** + * Returned when the text value of a "text" content part is updated. + */ +export interface ResponseTextDeltaEvent { + /** + * The index of the content part in the item's content array. + */ + content_index: number; + + /** + * The text delta. + */ + delta: string; + + /** + * The unique ID of the server event. + */ + event_id: string; + + /** + * The ID of the item. + */ + item_id: string; + + /** + * The index of the output item in the response. + */ + output_index: number; + + /** + * The ID of the response. + */ + response_id: string; + + /** + * The event type, must be `response.text.delta`. + */ + type: 'response.text.delta'; +} + +/** + * Returned when the text value of a "text" content part is done streaming. Also + * emitted when a Response is interrupted, incomplete, or cancelled. + */ +export interface ResponseTextDoneEvent { + /** + * The index of the content part in the item's content array. + */ + content_index: number; + + /** + * The unique ID of the server event. + */ + event_id: string; + + /** + * The ID of the item. + */ + item_id: string; + + /** + * The index of the output item in the response. + */ + output_index: number; + + /** + * The ID of the response. + */ + response_id: string; + + /** + * The final text content. + */ + text: string; + + /** + * The event type, must be `response.text.done`. + */ + type: 'response.text.done'; +} + +/** + * Returned when a Session is created. Emitted automatically when a new connection + * is established as the first server event. This event will contain the default + * Session configuration. + */ +export interface SessionCreatedEvent { + /** + * The unique ID of the server event. + */ + event_id: string; + + /** + * Realtime session object configuration. + */ + session: SessionsAPI.Session; + + /** + * The event type, must be `session.created`. + */ + type: 'session.created'; +} + +/** + * Send this event to update the session’s default configuration. The client may + * send this event at any time to update any field, except for `voice`. However, + * note that once a session has been initialized with a particular `model`, it + * can’t be changed to another model using `session.update`. + * + * When the server receives a `session.update`, it will respond with a + * `session.updated` event showing the full, effective configuration. Only the + * fields that are present are updated. To clear a field like `instructions`, pass + * an empty string. + */ +export interface SessionUpdateEvent { + /** + * Realtime session object configuration. + */ + session: SessionUpdateEvent.Session; + + /** + * The event type, must be `session.update`. + */ + type: 'session.update'; + + /** + * Optional client-generated ID used to identify this event. + */ + event_id?: string; +} + +export namespace SessionUpdateEvent { + /** + * Realtime session object configuration. + */ + export interface Session { + /** + * Configuration options for the generated client secret. + */ + client_secret?: Session.ClientSecret; + + /** + * The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For + * `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate, single channel + * (mono), and little-endian byte order. + */ + input_audio_format?: 'pcm16' | 'g711_ulaw' | 'g711_alaw'; + + /** + * Configuration for input audio noise reduction. This can be set to `null` to turn + * off. Noise reduction filters audio added to the input audio buffer before it is + * sent to VAD and the model. Filtering the audio can improve VAD and turn + * detection accuracy (reducing false positives) and model performance by improving + * perception of the input audio. + */ + input_audio_noise_reduction?: Session.InputAudioNoiseReduction; + + /** + * Configuration for input audio transcription, defaults to off and can be set to + * `null` to turn off once on. Input audio transcription is not native to the + * model, since the model consumes audio directly. Transcription runs + * asynchronously through + * [the /audio/transcriptions endpoint](https://platform.openai.com/docs/api-reference/audio/createTranscription) + * and should be treated as guidance of input audio content rather than precisely + * what the model heard. The client can optionally set the language and prompt for + * transcription, these offer additional guidance to the transcription service. + */ + input_audio_transcription?: Session.InputAudioTranscription; + + /** + * The default system instructions (i.e. system message) prepended to model calls. + * This field allows the client to guide the model on desired responses. The model + * can be instructed on response content and format, (e.g. "be extremely succinct", + * "act friendly", "here are examples of good responses") and on audio behavior + * (e.g. "talk quickly", "inject emotion into your voice", "laugh frequently"). The + * instructions are not guaranteed to be followed by the model, but they provide + * guidance to the model on the desired behavior. + * + * Note that the server sets default instructions which will be used if this field + * is not set and are visible in the `session.created` event at the start of the + * session. + */ + instructions?: string; + + /** + * Maximum number of output tokens for a single assistant response, inclusive of + * tool calls. Provide an integer between 1 and 4096 to limit output tokens, or + * `inf` for the maximum available tokens for a given model. Defaults to `inf`. + */ + max_response_output_tokens?: number | 'inf'; + + /** + * The set of modalities the model can respond with. To disable audio, set this to + * ["text"]. + */ + modalities?: Array<'text' | 'audio'>; + + /** + * The Realtime model used for this session. + */ + model?: + | 'gpt-4o-realtime-preview' + | 'gpt-4o-realtime-preview-2024-10-01' + | 'gpt-4o-realtime-preview-2024-12-17' + | 'gpt-4o-realtime-preview-2025-06-03' + | 'gpt-4o-mini-realtime-preview' + | 'gpt-4o-mini-realtime-preview-2024-12-17'; + + /** + * The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. + * For `pcm16`, output audio is sampled at a rate of 24kHz. + */ + output_audio_format?: 'pcm16' | 'g711_ulaw' | 'g711_alaw'; + + /** + * The speed of the model's spoken response. 1.0 is the default speed. 0.25 is the + * minimum speed. 1.5 is the maximum speed. This value can only be changed in + * between model turns, not while a response is in progress. + */ + speed?: number; + + /** + * Sampling temperature for the model, limited to [0.6, 1.2]. For audio models a + * temperature of 0.8 is highly recommended for best performance. + */ + temperature?: number; + + /** + * How the model chooses tools. Options are `auto`, `none`, `required`, or specify + * a function. + */ + tool_choice?: string; + + /** + * Tools (functions) available to the model. + */ + tools?: Array; + + /** + * Configuration options for tracing. Set to null to disable tracing. Once tracing + * is enabled for a session, the configuration cannot be modified. + * + * `auto` will create a trace for the session with default values for the workflow + * name, group id, and metadata. + */ + tracing?: 'auto' | Session.TracingConfiguration; + + /** + * Configuration for turn detection, ether Server VAD or Semantic VAD. This can be + * set to `null` to turn off, in which case the client must manually trigger model + * response. Server VAD means that the model will detect the start and end of + * speech based on audio volume and respond at the end of user speech. Semantic VAD + * is more advanced and uses a turn detection model (in conjunction with VAD) to + * semantically estimate whether the user has finished speaking, then dynamically + * sets a timeout based on this probability. For example, if user audio trails off + * with "uhhm", the model will score a low probability of turn end and wait longer + * for the user to continue speaking. This can be useful for more natural + * conversations, but may have a higher latency. + */ + turn_detection?: Session.TurnDetection; + + /** + * The voice the model uses to respond. Voice cannot be changed during the session + * once the model has responded with audio at least once. Current voice options are + * `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`, `shimmer`, and `verse`. + */ + voice?: (string & {}) | 'alloy' | 'ash' | 'ballad' | 'coral' | 'echo' | 'sage' | 'shimmer' | 'verse'; + } + + export namespace Session { + /** + * Configuration options for the generated client secret. + */ + export interface ClientSecret { + /** + * Configuration for the ephemeral token expiration. + */ + expires_after?: ClientSecret.ExpiresAfter; + } + + export namespace ClientSecret { + /** + * Configuration for the ephemeral token expiration. + */ + export interface ExpiresAfter { + /** + * The anchor point for the ephemeral token expiration. Only `created_at` is + * currently supported. + */ + anchor: 'created_at'; + + /** + * The number of seconds from the anchor point to the expiration. Select a value + * between `10` and `7200`. + */ + seconds?: number; + } + } + + /** + * Configuration for input audio noise reduction. This can be set to `null` to turn + * off. Noise reduction filters audio added to the input audio buffer before it is + * sent to VAD and the model. Filtering the audio can improve VAD and turn + * detection accuracy (reducing false positives) and model performance by improving + * perception of the input audio. + */ + export interface InputAudioNoiseReduction { + /** + * Type of noise reduction. `near_field` is for close-talking microphones such as + * headphones, `far_field` is for far-field microphones such as laptop or + * conference room microphones. + */ + type?: 'near_field' | 'far_field'; + } + + /** + * Configuration for input audio transcription, defaults to off and can be set to + * `null` to turn off once on. Input audio transcription is not native to the + * model, since the model consumes audio directly. Transcription runs + * asynchronously through + * [the /audio/transcriptions endpoint](https://platform.openai.com/docs/api-reference/audio/createTranscription) + * and should be treated as guidance of input audio content rather than precisely + * what the model heard. The client can optionally set the language and prompt for + * transcription, these offer additional guidance to the transcription service. + */ + export interface InputAudioTranscription { + /** + * The language of the input audio. Supplying the input language in + * [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) + * format will improve accuracy and latency. + */ + language?: string; + + /** + * The model to use for transcription, current options are `gpt-4o-transcribe`, + * `gpt-4o-mini-transcribe`, and `whisper-1`. + */ + model?: string; + + /** + * An optional text to guide the model's style or continue a previous audio + * segment. For `whisper-1`, the + * [prompt is a list of keywords](https://platform.openai.com/docs/guides/speech-to-text#prompting). + * For `gpt-4o-transcribe` models, the prompt is a free text string, for example + * "expect words related to technology". + */ + prompt?: string; + } + + export interface Tool { + /** + * The description of the function, including guidance on when and how to call it, + * and guidance about what to tell the user when calling (if anything). + */ + description?: string; + + /** + * The name of the function. + */ + name?: string; + + /** + * Parameters of the function in JSON Schema. + */ + parameters?: unknown; + + /** + * The type of the tool, i.e. `function`. + */ + type?: 'function'; + } + + /** + * Granular configuration for tracing. + */ + export interface TracingConfiguration { + /** + * The group id to attach to this trace to enable filtering and grouping in the + * traces dashboard. + */ + group_id?: string; + + /** + * The arbitrary metadata to attach to this trace to enable filtering in the traces + * dashboard. + */ + metadata?: unknown; + + /** + * The name of the workflow to attach to this trace. This is used to name the trace + * in the traces dashboard. + */ + workflow_name?: string; + } + + /** + * Configuration for turn detection, ether Server VAD or Semantic VAD. This can be + * set to `null` to turn off, in which case the client must manually trigger model + * response. Server VAD means that the model will detect the start and end of + * speech based on audio volume and respond at the end of user speech. Semantic VAD + * is more advanced and uses a turn detection model (in conjunction with VAD) to + * semantically estimate whether the user has finished speaking, then dynamically + * sets a timeout based on this probability. For example, if user audio trails off + * with "uhhm", the model will score a low probability of turn end and wait longer + * for the user to continue speaking. This can be useful for more natural + * conversations, but may have a higher latency. + */ + export interface TurnDetection { + /** + * Whether or not to automatically generate a response when a VAD stop event + * occurs. + */ + create_response?: boolean; + + /** + * Used only for `semantic_vad` mode. The eagerness of the model to respond. `low` + * will wait longer for the user to continue speaking, `high` will respond more + * quickly. `auto` is the default and is equivalent to `medium`. + */ + eagerness?: 'low' | 'medium' | 'high' | 'auto'; + + /** + * Whether or not to automatically interrupt any ongoing response with output to + * the default conversation (i.e. `conversation` of `auto`) when a VAD start event + * occurs. + */ + interrupt_response?: boolean; + + /** + * Used only for `server_vad` mode. Amount of audio to include before the VAD + * detected speech (in milliseconds). Defaults to 300ms. + */ + prefix_padding_ms?: number; + + /** + * Used only for `server_vad` mode. Duration of silence to detect speech stop (in + * milliseconds). Defaults to 500ms. With shorter values the model will respond + * more quickly, but may jump in on short pauses from the user. + */ + silence_duration_ms?: number; + + /** + * Used only for `server_vad` mode. Activation threshold for VAD (0.0 to 1.0), this + * defaults to 0.5. A higher threshold will require louder audio to activate the + * model, and thus might perform better in noisy environments. + */ + threshold?: number; + + /** + * Type of turn detection. + */ + type?: 'server_vad' | 'semantic_vad'; + } + } +} + +/** + * Returned when a session is updated with a `session.update` event, unless there + * is an error. + */ +export interface SessionUpdatedEvent { + /** + * The unique ID of the server event. + */ + event_id: string; + + /** + * Realtime session object configuration. + */ + session: SessionsAPI.Session; + + /** + * The event type, must be `session.updated`. + */ + type: 'session.updated'; +} + +/** + * Send this event to update a transcription session. + */ +export interface TranscriptionSessionUpdate { + /** + * Realtime transcription session object configuration. + */ + session: TranscriptionSessionUpdate.Session; + + /** + * The event type, must be `transcription_session.update`. + */ + type: 'transcription_session.update'; + + /** + * Optional client-generated ID used to identify this event. + */ + event_id?: string; +} + +export namespace TranscriptionSessionUpdate { + /** + * Realtime transcription session object configuration. + */ + export interface Session { + /** + * Configuration options for the generated client secret. + */ + client_secret?: Session.ClientSecret; + + /** + * The set of items to include in the transcription. Current available items are: + * + * - `item.input_audio_transcription.logprobs` + */ + include?: Array; + + /** + * The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For + * `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate, single channel + * (mono), and little-endian byte order. + */ + input_audio_format?: 'pcm16' | 'g711_ulaw' | 'g711_alaw'; + + /** + * Configuration for input audio noise reduction. This can be set to `null` to turn + * off. Noise reduction filters audio added to the input audio buffer before it is + * sent to VAD and the model. Filtering the audio can improve VAD and turn + * detection accuracy (reducing false positives) and model performance by improving + * perception of the input audio. + */ + input_audio_noise_reduction?: Session.InputAudioNoiseReduction; + + /** + * Configuration for input audio transcription. The client can optionally set the + * language and prompt for transcription, these offer additional guidance to the + * transcription service. + */ + input_audio_transcription?: Session.InputAudioTranscription; + + /** + * The set of modalities the model can respond with. To disable audio, set this to + * ["text"]. + */ + modalities?: Array<'text' | 'audio'>; + + /** + * Configuration for turn detection, ether Server VAD or Semantic VAD. This can be + * set to `null` to turn off, in which case the client must manually trigger model + * response. Server VAD means that the model will detect the start and end of + * speech based on audio volume and respond at the end of user speech. Semantic VAD + * is more advanced and uses a turn detection model (in conjunction with VAD) to + * semantically estimate whether the user has finished speaking, then dynamically + * sets a timeout based on this probability. For example, if user audio trails off + * with "uhhm", the model will score a low probability of turn end and wait longer + * for the user to continue speaking. This can be useful for more natural + * conversations, but may have a higher latency. + */ + turn_detection?: Session.TurnDetection; + } + + export namespace Session { + /** + * Configuration options for the generated client secret. + */ + export interface ClientSecret { + /** + * Configuration for the ephemeral token expiration. + */ + expires_at?: ClientSecret.ExpiresAt; + } + + export namespace ClientSecret { + /** + * Configuration for the ephemeral token expiration. + */ + export interface ExpiresAt { + /** + * The anchor point for the ephemeral token expiration. Only `created_at` is + * currently supported. + */ + anchor?: 'created_at'; + + /** + * The number of seconds from the anchor point to the expiration. Select a value + * between `10` and `7200`. + */ + seconds?: number; + } + } + + /** + * Configuration for input audio noise reduction. This can be set to `null` to turn + * off. Noise reduction filters audio added to the input audio buffer before it is + * sent to VAD and the model. Filtering the audio can improve VAD and turn + * detection accuracy (reducing false positives) and model performance by improving + * perception of the input audio. + */ + export interface InputAudioNoiseReduction { + /** + * Type of noise reduction. `near_field` is for close-talking microphones such as + * headphones, `far_field` is for far-field microphones such as laptop or + * conference room microphones. + */ + type?: 'near_field' | 'far_field'; + } + + /** + * Configuration for input audio transcription. The client can optionally set the + * language and prompt for transcription, these offer additional guidance to the + * transcription service. + */ + export interface InputAudioTranscription { + /** + * The language of the input audio. Supplying the input language in + * [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) + * format will improve accuracy and latency. + */ + language?: string; + + /** + * The model to use for transcription, current options are `gpt-4o-transcribe`, + * `gpt-4o-mini-transcribe`, and `whisper-1`. + */ + model?: 'gpt-4o-transcribe' | 'gpt-4o-mini-transcribe' | 'whisper-1'; + + /** + * An optional text to guide the model's style or continue a previous audio + * segment. For `whisper-1`, the + * [prompt is a list of keywords](https://platform.openai.com/docs/guides/speech-to-text#prompting). + * For `gpt-4o-transcribe` models, the prompt is a free text string, for example + * "expect words related to technology". + */ + prompt?: string; + } + + /** + * Configuration for turn detection, ether Server VAD or Semantic VAD. This can be + * set to `null` to turn off, in which case the client must manually trigger model + * response. Server VAD means that the model will detect the start and end of + * speech based on audio volume and respond at the end of user speech. Semantic VAD + * is more advanced and uses a turn detection model (in conjunction with VAD) to + * semantically estimate whether the user has finished speaking, then dynamically + * sets a timeout based on this probability. For example, if user audio trails off + * with "uhhm", the model will score a low probability of turn end and wait longer + * for the user to continue speaking. This can be useful for more natural + * conversations, but may have a higher latency. + */ + export interface TurnDetection { + /** + * Whether or not to automatically generate a response when a VAD stop event + * occurs. Not available for transcription sessions. + */ + create_response?: boolean; + + /** + * Used only for `semantic_vad` mode. The eagerness of the model to respond. `low` + * will wait longer for the user to continue speaking, `high` will respond more + * quickly. `auto` is the default and is equivalent to `medium`. + */ + eagerness?: 'low' | 'medium' | 'high' | 'auto'; + + /** + * Whether or not to automatically interrupt any ongoing response with output to + * the default conversation (i.e. `conversation` of `auto`) when a VAD start event + * occurs. Not available for transcription sessions. + */ + interrupt_response?: boolean; + + /** + * Used only for `server_vad` mode. Amount of audio to include before the VAD + * detected speech (in milliseconds). Defaults to 300ms. + */ + prefix_padding_ms?: number; + + /** + * Used only for `server_vad` mode. Duration of silence to detect speech stop (in + * milliseconds). Defaults to 500ms. With shorter values the model will respond + * more quickly, but may jump in on short pauses from the user. + */ + silence_duration_ms?: number; + + /** + * Used only for `server_vad` mode. Activation threshold for VAD (0.0 to 1.0), this + * defaults to 0.5. A higher threshold will require louder audio to activate the + * model, and thus might perform better in noisy environments. + */ + threshold?: number; + + /** + * Type of turn detection. + */ + type?: 'server_vad' | 'semantic_vad'; + } + } +} + +/** + * Returned when a transcription session is updated with a + * `transcription_session.update` event, unless there is an error. + */ +export interface TranscriptionSessionUpdatedEvent { + /** + * The unique ID of the server event. + */ + event_id: string; + + /** + * A new Realtime transcription session configuration. + * + * When a session is created on the server via REST API, the session object also + * contains an ephemeral key. Default TTL for keys is 10 minutes. This property is + * not present when a session is updated via the WebSocket API. + */ + session: TranscriptionSessionsAPI.TranscriptionSession; + + /** + * The event type, must be `transcription_session.updated`. + */ + type: 'transcription_session.updated'; +} + +Realtime.Sessions = Sessions; +Realtime.TranscriptionSessions = TranscriptionSessions; + +export declare namespace Realtime { + export { + type ConversationCreatedEvent as ConversationCreatedEvent, + type ConversationItem as ConversationItem, + type ConversationItemContent as ConversationItemContent, + type ConversationItemCreateEvent as ConversationItemCreateEvent, + type ConversationItemCreatedEvent as ConversationItemCreatedEvent, + type ConversationItemDeleteEvent as ConversationItemDeleteEvent, + type ConversationItemDeletedEvent as ConversationItemDeletedEvent, + type ConversationItemInputAudioTranscriptionCompletedEvent as ConversationItemInputAudioTranscriptionCompletedEvent, + type ConversationItemInputAudioTranscriptionDeltaEvent as ConversationItemInputAudioTranscriptionDeltaEvent, + type ConversationItemInputAudioTranscriptionFailedEvent as ConversationItemInputAudioTranscriptionFailedEvent, + type ConversationItemRetrieveEvent as ConversationItemRetrieveEvent, + type ConversationItemTruncateEvent as ConversationItemTruncateEvent, + type ConversationItemTruncatedEvent as ConversationItemTruncatedEvent, + type ConversationItemWithReference as ConversationItemWithReference, + type ErrorEvent as ErrorEvent, + type InputAudioBufferAppendEvent as InputAudioBufferAppendEvent, + type InputAudioBufferClearEvent as InputAudioBufferClearEvent, + type InputAudioBufferClearedEvent as InputAudioBufferClearedEvent, + type InputAudioBufferCommitEvent as InputAudioBufferCommitEvent, + type InputAudioBufferCommittedEvent as InputAudioBufferCommittedEvent, + type InputAudioBufferSpeechStartedEvent as InputAudioBufferSpeechStartedEvent, + type InputAudioBufferSpeechStoppedEvent as InputAudioBufferSpeechStoppedEvent, + type RateLimitsUpdatedEvent as RateLimitsUpdatedEvent, + type RealtimeClientEvent as RealtimeClientEvent, + type RealtimeResponse as RealtimeResponse, + type RealtimeResponseStatus as RealtimeResponseStatus, + type RealtimeResponseUsage as RealtimeResponseUsage, + type RealtimeServerEvent as RealtimeServerEvent, + type ResponseAudioDeltaEvent as ResponseAudioDeltaEvent, + type ResponseAudioDoneEvent as ResponseAudioDoneEvent, + type ResponseAudioTranscriptDeltaEvent as ResponseAudioTranscriptDeltaEvent, + type ResponseAudioTranscriptDoneEvent as ResponseAudioTranscriptDoneEvent, + type ResponseCancelEvent as ResponseCancelEvent, + type ResponseContentPartAddedEvent as ResponseContentPartAddedEvent, + type ResponseContentPartDoneEvent as ResponseContentPartDoneEvent, + type ResponseCreateEvent as ResponseCreateEvent, + type ResponseCreatedEvent as ResponseCreatedEvent, + type ResponseDoneEvent as ResponseDoneEvent, + type ResponseFunctionCallArgumentsDeltaEvent as ResponseFunctionCallArgumentsDeltaEvent, + type ResponseFunctionCallArgumentsDoneEvent as ResponseFunctionCallArgumentsDoneEvent, + type ResponseOutputItemAddedEvent as ResponseOutputItemAddedEvent, + type ResponseOutputItemDoneEvent as ResponseOutputItemDoneEvent, + type ResponseTextDeltaEvent as ResponseTextDeltaEvent, + type ResponseTextDoneEvent as ResponseTextDoneEvent, + type SessionCreatedEvent as SessionCreatedEvent, + type SessionUpdateEvent as SessionUpdateEvent, + type SessionUpdatedEvent as SessionUpdatedEvent, + type TranscriptionSessionUpdate as TranscriptionSessionUpdate, + type TranscriptionSessionUpdatedEvent as TranscriptionSessionUpdatedEvent, + }; + + export { + Sessions as Sessions, + type SessionsAPISession as Session, + type SessionCreateResponse as SessionCreateResponse, + type SessionCreateParams as SessionCreateParams, + }; + + export { + TranscriptionSessions as TranscriptionSessions, + type TranscriptionSession as TranscriptionSession, + type TranscriptionSessionCreateParams as TranscriptionSessionCreateParams, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/realtime/sessions.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/realtime/sessions.ts new file mode 100644 index 0000000000000000000000000000000000000000..fbcb23ae1550deea86baff8009262b23be3ff234 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/realtime/sessions.ts @@ -0,0 +1,869 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../../core/resource'; +import { APIPromise } from '../../../core/api-promise'; +import { buildHeaders } from '../../../internal/headers'; +import { RequestOptions } from '../../../internal/request-options'; + +export class Sessions extends APIResource { + /** + * Create an ephemeral API token for use in client-side applications with the + * Realtime API. Can be configured with the same session parameters as the + * `session.update` client event. + * + * It responds with a session object, plus a `client_secret` key which contains a + * usable ephemeral API token that can be used to authenticate browser clients for + * the Realtime API. + * + * @example + * ```ts + * const session = + * await client.beta.realtime.sessions.create(); + * ``` + */ + create(body: SessionCreateParams, options?: RequestOptions): APIPromise { + return this._client.post('/realtime/sessions', { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } +} + +/** + * Realtime session object configuration. + */ +export interface Session { + /** + * Unique identifier for the session that looks like `sess_1234567890abcdef`. + */ + id?: string; + + /** + * The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For + * `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate, single channel + * (mono), and little-endian byte order. + */ + input_audio_format?: 'pcm16' | 'g711_ulaw' | 'g711_alaw'; + + /** + * Configuration for input audio noise reduction. This can be set to `null` to turn + * off. Noise reduction filters audio added to the input audio buffer before it is + * sent to VAD and the model. Filtering the audio can improve VAD and turn + * detection accuracy (reducing false positives) and model performance by improving + * perception of the input audio. + */ + input_audio_noise_reduction?: Session.InputAudioNoiseReduction; + + /** + * Configuration for input audio transcription, defaults to off and can be set to + * `null` to turn off once on. Input audio transcription is not native to the + * model, since the model consumes audio directly. Transcription runs + * asynchronously through + * [the /audio/transcriptions endpoint](https://platform.openai.com/docs/api-reference/audio/createTranscription) + * and should be treated as guidance of input audio content rather than precisely + * what the model heard. The client can optionally set the language and prompt for + * transcription, these offer additional guidance to the transcription service. + */ + input_audio_transcription?: Session.InputAudioTranscription; + + /** + * The default system instructions (i.e. system message) prepended to model calls. + * This field allows the client to guide the model on desired responses. The model + * can be instructed on response content and format, (e.g. "be extremely succinct", + * "act friendly", "here are examples of good responses") and on audio behavior + * (e.g. "talk quickly", "inject emotion into your voice", "laugh frequently"). The + * instructions are not guaranteed to be followed by the model, but they provide + * guidance to the model on the desired behavior. + * + * Note that the server sets default instructions which will be used if this field + * is not set and are visible in the `session.created` event at the start of the + * session. + */ + instructions?: string; + + /** + * Maximum number of output tokens for a single assistant response, inclusive of + * tool calls. Provide an integer between 1 and 4096 to limit output tokens, or + * `inf` for the maximum available tokens for a given model. Defaults to `inf`. + */ + max_response_output_tokens?: number | 'inf'; + + /** + * The set of modalities the model can respond with. To disable audio, set this to + * ["text"]. + */ + modalities?: Array<'text' | 'audio'>; + + /** + * The Realtime model used for this session. + */ + model?: + | 'gpt-4o-realtime-preview' + | 'gpt-4o-realtime-preview-2024-10-01' + | 'gpt-4o-realtime-preview-2024-12-17' + | 'gpt-4o-realtime-preview-2025-06-03' + | 'gpt-4o-mini-realtime-preview' + | 'gpt-4o-mini-realtime-preview-2024-12-17'; + + /** + * The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. + * For `pcm16`, output audio is sampled at a rate of 24kHz. + */ + output_audio_format?: 'pcm16' | 'g711_ulaw' | 'g711_alaw'; + + /** + * The speed of the model's spoken response. 1.0 is the default speed. 0.25 is the + * minimum speed. 1.5 is the maximum speed. This value can only be changed in + * between model turns, not while a response is in progress. + */ + speed?: number; + + /** + * Sampling temperature for the model, limited to [0.6, 1.2]. For audio models a + * temperature of 0.8 is highly recommended for best performance. + */ + temperature?: number; + + /** + * How the model chooses tools. Options are `auto`, `none`, `required`, or specify + * a function. + */ + tool_choice?: string; + + /** + * Tools (functions) available to the model. + */ + tools?: Array; + + /** + * Configuration options for tracing. Set to null to disable tracing. Once tracing + * is enabled for a session, the configuration cannot be modified. + * + * `auto` will create a trace for the session with default values for the workflow + * name, group id, and metadata. + */ + tracing?: 'auto' | Session.TracingConfiguration; + + /** + * Configuration for turn detection, ether Server VAD or Semantic VAD. This can be + * set to `null` to turn off, in which case the client must manually trigger model + * response. Server VAD means that the model will detect the start and end of + * speech based on audio volume and respond at the end of user speech. Semantic VAD + * is more advanced and uses a turn detection model (in conjunction with VAD) to + * semantically estimate whether the user has finished speaking, then dynamically + * sets a timeout based on this probability. For example, if user audio trails off + * with "uhhm", the model will score a low probability of turn end and wait longer + * for the user to continue speaking. This can be useful for more natural + * conversations, but may have a higher latency. + */ + turn_detection?: Session.TurnDetection; + + /** + * The voice the model uses to respond. Voice cannot be changed during the session + * once the model has responded with audio at least once. Current voice options are + * `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`, `shimmer`, and `verse`. + */ + voice?: (string & {}) | 'alloy' | 'ash' | 'ballad' | 'coral' | 'echo' | 'sage' | 'shimmer' | 'verse'; +} + +export namespace Session { + /** + * Configuration for input audio noise reduction. This can be set to `null` to turn + * off. Noise reduction filters audio added to the input audio buffer before it is + * sent to VAD and the model. Filtering the audio can improve VAD and turn + * detection accuracy (reducing false positives) and model performance by improving + * perception of the input audio. + */ + export interface InputAudioNoiseReduction { + /** + * Type of noise reduction. `near_field` is for close-talking microphones such as + * headphones, `far_field` is for far-field microphones such as laptop or + * conference room microphones. + */ + type?: 'near_field' | 'far_field'; + } + + /** + * Configuration for input audio transcription, defaults to off and can be set to + * `null` to turn off once on. Input audio transcription is not native to the + * model, since the model consumes audio directly. Transcription runs + * asynchronously through + * [the /audio/transcriptions endpoint](https://platform.openai.com/docs/api-reference/audio/createTranscription) + * and should be treated as guidance of input audio content rather than precisely + * what the model heard. The client can optionally set the language and prompt for + * transcription, these offer additional guidance to the transcription service. + */ + export interface InputAudioTranscription { + /** + * The language of the input audio. Supplying the input language in + * [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) + * format will improve accuracy and latency. + */ + language?: string; + + /** + * The model to use for transcription, current options are `gpt-4o-transcribe`, + * `gpt-4o-mini-transcribe`, and `whisper-1`. + */ + model?: string; + + /** + * An optional text to guide the model's style or continue a previous audio + * segment. For `whisper-1`, the + * [prompt is a list of keywords](https://platform.openai.com/docs/guides/speech-to-text#prompting). + * For `gpt-4o-transcribe` models, the prompt is a free text string, for example + * "expect words related to technology". + */ + prompt?: string; + } + + export interface Tool { + /** + * The description of the function, including guidance on when and how to call it, + * and guidance about what to tell the user when calling (if anything). + */ + description?: string; + + /** + * The name of the function. + */ + name?: string; + + /** + * Parameters of the function in JSON Schema. + */ + parameters?: unknown; + + /** + * The type of the tool, i.e. `function`. + */ + type?: 'function'; + } + + /** + * Granular configuration for tracing. + */ + export interface TracingConfiguration { + /** + * The group id to attach to this trace to enable filtering and grouping in the + * traces dashboard. + */ + group_id?: string; + + /** + * The arbitrary metadata to attach to this trace to enable filtering in the traces + * dashboard. + */ + metadata?: unknown; + + /** + * The name of the workflow to attach to this trace. This is used to name the trace + * in the traces dashboard. + */ + workflow_name?: string; + } + + /** + * Configuration for turn detection, ether Server VAD or Semantic VAD. This can be + * set to `null` to turn off, in which case the client must manually trigger model + * response. Server VAD means that the model will detect the start and end of + * speech based on audio volume and respond at the end of user speech. Semantic VAD + * is more advanced and uses a turn detection model (in conjunction with VAD) to + * semantically estimate whether the user has finished speaking, then dynamically + * sets a timeout based on this probability. For example, if user audio trails off + * with "uhhm", the model will score a low probability of turn end and wait longer + * for the user to continue speaking. This can be useful for more natural + * conversations, but may have a higher latency. + */ + export interface TurnDetection { + /** + * Whether or not to automatically generate a response when a VAD stop event + * occurs. + */ + create_response?: boolean; + + /** + * Used only for `semantic_vad` mode. The eagerness of the model to respond. `low` + * will wait longer for the user to continue speaking, `high` will respond more + * quickly. `auto` is the default and is equivalent to `medium`. + */ + eagerness?: 'low' | 'medium' | 'high' | 'auto'; + + /** + * Whether or not to automatically interrupt any ongoing response with output to + * the default conversation (i.e. `conversation` of `auto`) when a VAD start event + * occurs. + */ + interrupt_response?: boolean; + + /** + * Used only for `server_vad` mode. Amount of audio to include before the VAD + * detected speech (in milliseconds). Defaults to 300ms. + */ + prefix_padding_ms?: number; + + /** + * Used only for `server_vad` mode. Duration of silence to detect speech stop (in + * milliseconds). Defaults to 500ms. With shorter values the model will respond + * more quickly, but may jump in on short pauses from the user. + */ + silence_duration_ms?: number; + + /** + * Used only for `server_vad` mode. Activation threshold for VAD (0.0 to 1.0), this + * defaults to 0.5. A higher threshold will require louder audio to activate the + * model, and thus might perform better in noisy environments. + */ + threshold?: number; + + /** + * Type of turn detection. + */ + type?: 'server_vad' | 'semantic_vad'; + } +} + +/** + * A new Realtime session configuration, with an ephemeral key. Default TTL for + * keys is one minute. + */ +export interface SessionCreateResponse { + /** + * Ephemeral key returned by the API. + */ + client_secret: SessionCreateResponse.ClientSecret; + + /** + * The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. + */ + input_audio_format?: string; + + /** + * Configuration for input audio transcription, defaults to off and can be set to + * `null` to turn off once on. Input audio transcription is not native to the + * model, since the model consumes audio directly. Transcription runs + * asynchronously and should be treated as rough guidance rather than the + * representation understood by the model. + */ + input_audio_transcription?: SessionCreateResponse.InputAudioTranscription; + + /** + * The default system instructions (i.e. system message) prepended to model calls. + * This field allows the client to guide the model on desired responses. The model + * can be instructed on response content and format, (e.g. "be extremely succinct", + * "act friendly", "here are examples of good responses") and on audio behavior + * (e.g. "talk quickly", "inject emotion into your voice", "laugh frequently"). The + * instructions are not guaranteed to be followed by the model, but they provide + * guidance to the model on the desired behavior. + * + * Note that the server sets default instructions which will be used if this field + * is not set and are visible in the `session.created` event at the start of the + * session. + */ + instructions?: string; + + /** + * Maximum number of output tokens for a single assistant response, inclusive of + * tool calls. Provide an integer between 1 and 4096 to limit output tokens, or + * `inf` for the maximum available tokens for a given model. Defaults to `inf`. + */ + max_response_output_tokens?: number | 'inf'; + + /** + * The set of modalities the model can respond with. To disable audio, set this to + * ["text"]. + */ + modalities?: Array<'text' | 'audio'>; + + /** + * The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. + */ + output_audio_format?: string; + + /** + * The speed of the model's spoken response. 1.0 is the default speed. 0.25 is the + * minimum speed. 1.5 is the maximum speed. This value can only be changed in + * between model turns, not while a response is in progress. + */ + speed?: number; + + /** + * Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8. + */ + temperature?: number; + + /** + * How the model chooses tools. Options are `auto`, `none`, `required`, or specify + * a function. + */ + tool_choice?: string; + + /** + * Tools (functions) available to the model. + */ + tools?: Array; + + /** + * Configuration options for tracing. Set to null to disable tracing. Once tracing + * is enabled for a session, the configuration cannot be modified. + * + * `auto` will create a trace for the session with default values for the workflow + * name, group id, and metadata. + */ + tracing?: 'auto' | SessionCreateResponse.TracingConfiguration; + + /** + * Configuration for turn detection. Can be set to `null` to turn off. Server VAD + * means that the model will detect the start and end of speech based on audio + * volume and respond at the end of user speech. + */ + turn_detection?: SessionCreateResponse.TurnDetection; + + /** + * The voice the model uses to respond. Voice cannot be changed during the session + * once the model has responded with audio at least once. Current voice options are + * `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`, `shimmer`, and `verse`. + */ + voice?: (string & {}) | 'alloy' | 'ash' | 'ballad' | 'coral' | 'echo' | 'sage' | 'shimmer' | 'verse'; +} + +export namespace SessionCreateResponse { + /** + * Ephemeral key returned by the API. + */ + export interface ClientSecret { + /** + * Timestamp for when the token expires. Currently, all tokens expire after one + * minute. + */ + expires_at: number; + + /** + * Ephemeral key usable in client environments to authenticate connections to the + * Realtime API. Use this in client-side environments rather than a standard API + * token, which should only be used server-side. + */ + value: string; + } + + /** + * Configuration for input audio transcription, defaults to off and can be set to + * `null` to turn off once on. Input audio transcription is not native to the + * model, since the model consumes audio directly. Transcription runs + * asynchronously and should be treated as rough guidance rather than the + * representation understood by the model. + */ + export interface InputAudioTranscription { + /** + * The model to use for transcription. + */ + model?: string; + } + + export interface Tool { + /** + * The description of the function, including guidance on when and how to call it, + * and guidance about what to tell the user when calling (if anything). + */ + description?: string; + + /** + * The name of the function. + */ + name?: string; + + /** + * Parameters of the function in JSON Schema. + */ + parameters?: unknown; + + /** + * The type of the tool, i.e. `function`. + */ + type?: 'function'; + } + + /** + * Granular configuration for tracing. + */ + export interface TracingConfiguration { + /** + * The group id to attach to this trace to enable filtering and grouping in the + * traces dashboard. + */ + group_id?: string; + + /** + * The arbitrary metadata to attach to this trace to enable filtering in the traces + * dashboard. + */ + metadata?: unknown; + + /** + * The name of the workflow to attach to this trace. This is used to name the trace + * in the traces dashboard. + */ + workflow_name?: string; + } + + /** + * Configuration for turn detection. Can be set to `null` to turn off. Server VAD + * means that the model will detect the start and end of speech based on audio + * volume and respond at the end of user speech. + */ + export interface TurnDetection { + /** + * Amount of audio to include before the VAD detected speech (in milliseconds). + * Defaults to 300ms. + */ + prefix_padding_ms?: number; + + /** + * Duration of silence to detect speech stop (in milliseconds). Defaults to 500ms. + * With shorter values the model will respond more quickly, but may jump in on + * short pauses from the user. + */ + silence_duration_ms?: number; + + /** + * Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A higher + * threshold will require louder audio to activate the model, and thus might + * perform better in noisy environments. + */ + threshold?: number; + + /** + * Type of turn detection, only `server_vad` is currently supported. + */ + type?: string; + } +} + +export interface SessionCreateParams { + /** + * Configuration options for the generated client secret. + */ + client_secret?: SessionCreateParams.ClientSecret; + + /** + * The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For + * `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate, single channel + * (mono), and little-endian byte order. + */ + input_audio_format?: 'pcm16' | 'g711_ulaw' | 'g711_alaw'; + + /** + * Configuration for input audio noise reduction. This can be set to `null` to turn + * off. Noise reduction filters audio added to the input audio buffer before it is + * sent to VAD and the model. Filtering the audio can improve VAD and turn + * detection accuracy (reducing false positives) and model performance by improving + * perception of the input audio. + */ + input_audio_noise_reduction?: SessionCreateParams.InputAudioNoiseReduction; + + /** + * Configuration for input audio transcription, defaults to off and can be set to + * `null` to turn off once on. Input audio transcription is not native to the + * model, since the model consumes audio directly. Transcription runs + * asynchronously through + * [the /audio/transcriptions endpoint](https://platform.openai.com/docs/api-reference/audio/createTranscription) + * and should be treated as guidance of input audio content rather than precisely + * what the model heard. The client can optionally set the language and prompt for + * transcription, these offer additional guidance to the transcription service. + */ + input_audio_transcription?: SessionCreateParams.InputAudioTranscription; + + /** + * The default system instructions (i.e. system message) prepended to model calls. + * This field allows the client to guide the model on desired responses. The model + * can be instructed on response content and format, (e.g. "be extremely succinct", + * "act friendly", "here are examples of good responses") and on audio behavior + * (e.g. "talk quickly", "inject emotion into your voice", "laugh frequently"). The + * instructions are not guaranteed to be followed by the model, but they provide + * guidance to the model on the desired behavior. + * + * Note that the server sets default instructions which will be used if this field + * is not set and are visible in the `session.created` event at the start of the + * session. + */ + instructions?: string; + + /** + * Maximum number of output tokens for a single assistant response, inclusive of + * tool calls. Provide an integer between 1 and 4096 to limit output tokens, or + * `inf` for the maximum available tokens for a given model. Defaults to `inf`. + */ + max_response_output_tokens?: number | 'inf'; + + /** + * The set of modalities the model can respond with. To disable audio, set this to + * ["text"]. + */ + modalities?: Array<'text' | 'audio'>; + + /** + * The Realtime model used for this session. + */ + model?: + | 'gpt-4o-realtime-preview' + | 'gpt-4o-realtime-preview-2024-10-01' + | 'gpt-4o-realtime-preview-2024-12-17' + | 'gpt-4o-realtime-preview-2025-06-03' + | 'gpt-4o-mini-realtime-preview' + | 'gpt-4o-mini-realtime-preview-2024-12-17'; + + /** + * The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. + * For `pcm16`, output audio is sampled at a rate of 24kHz. + */ + output_audio_format?: 'pcm16' | 'g711_ulaw' | 'g711_alaw'; + + /** + * The speed of the model's spoken response. 1.0 is the default speed. 0.25 is the + * minimum speed. 1.5 is the maximum speed. This value can only be changed in + * between model turns, not while a response is in progress. + */ + speed?: number; + + /** + * Sampling temperature for the model, limited to [0.6, 1.2]. For audio models a + * temperature of 0.8 is highly recommended for best performance. + */ + temperature?: number; + + /** + * How the model chooses tools. Options are `auto`, `none`, `required`, or specify + * a function. + */ + tool_choice?: string; + + /** + * Tools (functions) available to the model. + */ + tools?: Array; + + /** + * Configuration options for tracing. Set to null to disable tracing. Once tracing + * is enabled for a session, the configuration cannot be modified. + * + * `auto` will create a trace for the session with default values for the workflow + * name, group id, and metadata. + */ + tracing?: 'auto' | SessionCreateParams.TracingConfiguration; + + /** + * Configuration for turn detection, ether Server VAD or Semantic VAD. This can be + * set to `null` to turn off, in which case the client must manually trigger model + * response. Server VAD means that the model will detect the start and end of + * speech based on audio volume and respond at the end of user speech. Semantic VAD + * is more advanced and uses a turn detection model (in conjunction with VAD) to + * semantically estimate whether the user has finished speaking, then dynamically + * sets a timeout based on this probability. For example, if user audio trails off + * with "uhhm", the model will score a low probability of turn end and wait longer + * for the user to continue speaking. This can be useful for more natural + * conversations, but may have a higher latency. + */ + turn_detection?: SessionCreateParams.TurnDetection; + + /** + * The voice the model uses to respond. Voice cannot be changed during the session + * once the model has responded with audio at least once. Current voice options are + * `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`, `shimmer`, and `verse`. + */ + voice?: (string & {}) | 'alloy' | 'ash' | 'ballad' | 'coral' | 'echo' | 'sage' | 'shimmer' | 'verse'; +} + +export namespace SessionCreateParams { + /** + * Configuration options for the generated client secret. + */ + export interface ClientSecret { + /** + * Configuration for the ephemeral token expiration. + */ + expires_after?: ClientSecret.ExpiresAfter; + } + + export namespace ClientSecret { + /** + * Configuration for the ephemeral token expiration. + */ + export interface ExpiresAfter { + /** + * The anchor point for the ephemeral token expiration. Only `created_at` is + * currently supported. + */ + anchor: 'created_at'; + + /** + * The number of seconds from the anchor point to the expiration. Select a value + * between `10` and `7200`. + */ + seconds?: number; + } + } + + /** + * Configuration for input audio noise reduction. This can be set to `null` to turn + * off. Noise reduction filters audio added to the input audio buffer before it is + * sent to VAD and the model. Filtering the audio can improve VAD and turn + * detection accuracy (reducing false positives) and model performance by improving + * perception of the input audio. + */ + export interface InputAudioNoiseReduction { + /** + * Type of noise reduction. `near_field` is for close-talking microphones such as + * headphones, `far_field` is for far-field microphones such as laptop or + * conference room microphones. + */ + type?: 'near_field' | 'far_field'; + } + + /** + * Configuration for input audio transcription, defaults to off and can be set to + * `null` to turn off once on. Input audio transcription is not native to the + * model, since the model consumes audio directly. Transcription runs + * asynchronously through + * [the /audio/transcriptions endpoint](https://platform.openai.com/docs/api-reference/audio/createTranscription) + * and should be treated as guidance of input audio content rather than precisely + * what the model heard. The client can optionally set the language and prompt for + * transcription, these offer additional guidance to the transcription service. + */ + export interface InputAudioTranscription { + /** + * The language of the input audio. Supplying the input language in + * [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) + * format will improve accuracy and latency. + */ + language?: string; + + /** + * The model to use for transcription, current options are `gpt-4o-transcribe`, + * `gpt-4o-mini-transcribe`, and `whisper-1`. + */ + model?: string; + + /** + * An optional text to guide the model's style or continue a previous audio + * segment. For `whisper-1`, the + * [prompt is a list of keywords](https://platform.openai.com/docs/guides/speech-to-text#prompting). + * For `gpt-4o-transcribe` models, the prompt is a free text string, for example + * "expect words related to technology". + */ + prompt?: string; + } + + export interface Tool { + /** + * The description of the function, including guidance on when and how to call it, + * and guidance about what to tell the user when calling (if anything). + */ + description?: string; + + /** + * The name of the function. + */ + name?: string; + + /** + * Parameters of the function in JSON Schema. + */ + parameters?: unknown; + + /** + * The type of the tool, i.e. `function`. + */ + type?: 'function'; + } + + /** + * Granular configuration for tracing. + */ + export interface TracingConfiguration { + /** + * The group id to attach to this trace to enable filtering and grouping in the + * traces dashboard. + */ + group_id?: string; + + /** + * The arbitrary metadata to attach to this trace to enable filtering in the traces + * dashboard. + */ + metadata?: unknown; + + /** + * The name of the workflow to attach to this trace. This is used to name the trace + * in the traces dashboard. + */ + workflow_name?: string; + } + + /** + * Configuration for turn detection, ether Server VAD or Semantic VAD. This can be + * set to `null` to turn off, in which case the client must manually trigger model + * response. Server VAD means that the model will detect the start and end of + * speech based on audio volume and respond at the end of user speech. Semantic VAD + * is more advanced and uses a turn detection model (in conjunction with VAD) to + * semantically estimate whether the user has finished speaking, then dynamically + * sets a timeout based on this probability. For example, if user audio trails off + * with "uhhm", the model will score a low probability of turn end and wait longer + * for the user to continue speaking. This can be useful for more natural + * conversations, but may have a higher latency. + */ + export interface TurnDetection { + /** + * Whether or not to automatically generate a response when a VAD stop event + * occurs. + */ + create_response?: boolean; + + /** + * Used only for `semantic_vad` mode. The eagerness of the model to respond. `low` + * will wait longer for the user to continue speaking, `high` will respond more + * quickly. `auto` is the default and is equivalent to `medium`. + */ + eagerness?: 'low' | 'medium' | 'high' | 'auto'; + + /** + * Whether or not to automatically interrupt any ongoing response with output to + * the default conversation (i.e. `conversation` of `auto`) when a VAD start event + * occurs. + */ + interrupt_response?: boolean; + + /** + * Used only for `server_vad` mode. Amount of audio to include before the VAD + * detected speech (in milliseconds). Defaults to 300ms. + */ + prefix_padding_ms?: number; + + /** + * Used only for `server_vad` mode. Duration of silence to detect speech stop (in + * milliseconds). Defaults to 500ms. With shorter values the model will respond + * more quickly, but may jump in on short pauses from the user. + */ + silence_duration_ms?: number; + + /** + * Used only for `server_vad` mode. Activation threshold for VAD (0.0 to 1.0), this + * defaults to 0.5. A higher threshold will require louder audio to activate the + * model, and thus might perform better in noisy environments. + */ + threshold?: number; + + /** + * Type of turn detection. + */ + type?: 'server_vad' | 'semantic_vad'; + } +} + +export declare namespace Sessions { + export { + type Session as Session, + type SessionCreateResponse as SessionCreateResponse, + type SessionCreateParams as SessionCreateParams, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/realtime/transcription-sessions.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/realtime/transcription-sessions.ts new file mode 100644 index 0000000000000000000000000000000000000000..8542f69b6aa885c5437e493c70cf03149b8b0aae --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/realtime/transcription-sessions.ts @@ -0,0 +1,347 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../../core/resource'; +import { APIPromise } from '../../../core/api-promise'; +import { buildHeaders } from '../../../internal/headers'; +import { RequestOptions } from '../../../internal/request-options'; + +export class TranscriptionSessions extends APIResource { + /** + * Create an ephemeral API token for use in client-side applications with the + * Realtime API specifically for realtime transcriptions. Can be configured with + * the same session parameters as the `transcription_session.update` client event. + * + * It responds with a session object, plus a `client_secret` key which contains a + * usable ephemeral API token that can be used to authenticate browser clients for + * the Realtime API. + * + * @example + * ```ts + * const transcriptionSession = + * await client.beta.realtime.transcriptionSessions.create(); + * ``` + */ + create(body: TranscriptionSessionCreateParams, options?: RequestOptions): APIPromise { + return this._client.post('/realtime/transcription_sessions', { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } +} + +/** + * A new Realtime transcription session configuration. + * + * When a session is created on the server via REST API, the session object also + * contains an ephemeral key. Default TTL for keys is 10 minutes. This property is + * not present when a session is updated via the WebSocket API. + */ +export interface TranscriptionSession { + /** + * Ephemeral key returned by the API. Only present when the session is created on + * the server via REST API. + */ + client_secret: TranscriptionSession.ClientSecret; + + /** + * The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. + */ + input_audio_format?: string; + + /** + * Configuration of the transcription model. + */ + input_audio_transcription?: TranscriptionSession.InputAudioTranscription; + + /** + * The set of modalities the model can respond with. To disable audio, set this to + * ["text"]. + */ + modalities?: Array<'text' | 'audio'>; + + /** + * Configuration for turn detection. Can be set to `null` to turn off. Server VAD + * means that the model will detect the start and end of speech based on audio + * volume and respond at the end of user speech. + */ + turn_detection?: TranscriptionSession.TurnDetection; +} + +export namespace TranscriptionSession { + /** + * Ephemeral key returned by the API. Only present when the session is created on + * the server via REST API. + */ + export interface ClientSecret { + /** + * Timestamp for when the token expires. Currently, all tokens expire after one + * minute. + */ + expires_at: number; + + /** + * Ephemeral key usable in client environments to authenticate connections to the + * Realtime API. Use this in client-side environments rather than a standard API + * token, which should only be used server-side. + */ + value: string; + } + + /** + * Configuration of the transcription model. + */ + export interface InputAudioTranscription { + /** + * The language of the input audio. Supplying the input language in + * [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) + * format will improve accuracy and latency. + */ + language?: string; + + /** + * The model to use for transcription. Can be `gpt-4o-transcribe`, + * `gpt-4o-mini-transcribe`, or `whisper-1`. + */ + model?: 'gpt-4o-transcribe' | 'gpt-4o-mini-transcribe' | 'whisper-1'; + + /** + * An optional text to guide the model's style or continue a previous audio + * segment. The + * [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting) + * should match the audio language. + */ + prompt?: string; + } + + /** + * Configuration for turn detection. Can be set to `null` to turn off. Server VAD + * means that the model will detect the start and end of speech based on audio + * volume and respond at the end of user speech. + */ + export interface TurnDetection { + /** + * Amount of audio to include before the VAD detected speech (in milliseconds). + * Defaults to 300ms. + */ + prefix_padding_ms?: number; + + /** + * Duration of silence to detect speech stop (in milliseconds). Defaults to 500ms. + * With shorter values the model will respond more quickly, but may jump in on + * short pauses from the user. + */ + silence_duration_ms?: number; + + /** + * Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A higher + * threshold will require louder audio to activate the model, and thus might + * perform better in noisy environments. + */ + threshold?: number; + + /** + * Type of turn detection, only `server_vad` is currently supported. + */ + type?: string; + } +} + +export interface TranscriptionSessionCreateParams { + /** + * Configuration options for the generated client secret. + */ + client_secret?: TranscriptionSessionCreateParams.ClientSecret; + + /** + * The set of items to include in the transcription. Current available items are: + * + * - `item.input_audio_transcription.logprobs` + */ + include?: Array; + + /** + * The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For + * `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate, single channel + * (mono), and little-endian byte order. + */ + input_audio_format?: 'pcm16' | 'g711_ulaw' | 'g711_alaw'; + + /** + * Configuration for input audio noise reduction. This can be set to `null` to turn + * off. Noise reduction filters audio added to the input audio buffer before it is + * sent to VAD and the model. Filtering the audio can improve VAD and turn + * detection accuracy (reducing false positives) and model performance by improving + * perception of the input audio. + */ + input_audio_noise_reduction?: TranscriptionSessionCreateParams.InputAudioNoiseReduction; + + /** + * Configuration for input audio transcription. The client can optionally set the + * language and prompt for transcription, these offer additional guidance to the + * transcription service. + */ + input_audio_transcription?: TranscriptionSessionCreateParams.InputAudioTranscription; + + /** + * The set of modalities the model can respond with. To disable audio, set this to + * ["text"]. + */ + modalities?: Array<'text' | 'audio'>; + + /** + * Configuration for turn detection, ether Server VAD or Semantic VAD. This can be + * set to `null` to turn off, in which case the client must manually trigger model + * response. Server VAD means that the model will detect the start and end of + * speech based on audio volume and respond at the end of user speech. Semantic VAD + * is more advanced and uses a turn detection model (in conjunction with VAD) to + * semantically estimate whether the user has finished speaking, then dynamically + * sets a timeout based on this probability. For example, if user audio trails off + * with "uhhm", the model will score a low probability of turn end and wait longer + * for the user to continue speaking. This can be useful for more natural + * conversations, but may have a higher latency. + */ + turn_detection?: TranscriptionSessionCreateParams.TurnDetection; +} + +export namespace TranscriptionSessionCreateParams { + /** + * Configuration options for the generated client secret. + */ + export interface ClientSecret { + /** + * Configuration for the ephemeral token expiration. + */ + expires_at?: ClientSecret.ExpiresAt; + } + + export namespace ClientSecret { + /** + * Configuration for the ephemeral token expiration. + */ + export interface ExpiresAt { + /** + * The anchor point for the ephemeral token expiration. Only `created_at` is + * currently supported. + */ + anchor?: 'created_at'; + + /** + * The number of seconds from the anchor point to the expiration. Select a value + * between `10` and `7200`. + */ + seconds?: number; + } + } + + /** + * Configuration for input audio noise reduction. This can be set to `null` to turn + * off. Noise reduction filters audio added to the input audio buffer before it is + * sent to VAD and the model. Filtering the audio can improve VAD and turn + * detection accuracy (reducing false positives) and model performance by improving + * perception of the input audio. + */ + export interface InputAudioNoiseReduction { + /** + * Type of noise reduction. `near_field` is for close-talking microphones such as + * headphones, `far_field` is for far-field microphones such as laptop or + * conference room microphones. + */ + type?: 'near_field' | 'far_field'; + } + + /** + * Configuration for input audio transcription. The client can optionally set the + * language and prompt for transcription, these offer additional guidance to the + * transcription service. + */ + export interface InputAudioTranscription { + /** + * The language of the input audio. Supplying the input language in + * [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) + * format will improve accuracy and latency. + */ + language?: string; + + /** + * The model to use for transcription, current options are `gpt-4o-transcribe`, + * `gpt-4o-mini-transcribe`, and `whisper-1`. + */ + model?: 'gpt-4o-transcribe' | 'gpt-4o-mini-transcribe' | 'whisper-1'; + + /** + * An optional text to guide the model's style or continue a previous audio + * segment. For `whisper-1`, the + * [prompt is a list of keywords](https://platform.openai.com/docs/guides/speech-to-text#prompting). + * For `gpt-4o-transcribe` models, the prompt is a free text string, for example + * "expect words related to technology". + */ + prompt?: string; + } + + /** + * Configuration for turn detection, ether Server VAD or Semantic VAD. This can be + * set to `null` to turn off, in which case the client must manually trigger model + * response. Server VAD means that the model will detect the start and end of + * speech based on audio volume and respond at the end of user speech. Semantic VAD + * is more advanced and uses a turn detection model (in conjunction with VAD) to + * semantically estimate whether the user has finished speaking, then dynamically + * sets a timeout based on this probability. For example, if user audio trails off + * with "uhhm", the model will score a low probability of turn end and wait longer + * for the user to continue speaking. This can be useful for more natural + * conversations, but may have a higher latency. + */ + export interface TurnDetection { + /** + * Whether or not to automatically generate a response when a VAD stop event + * occurs. Not available for transcription sessions. + */ + create_response?: boolean; + + /** + * Used only for `semantic_vad` mode. The eagerness of the model to respond. `low` + * will wait longer for the user to continue speaking, `high` will respond more + * quickly. `auto` is the default and is equivalent to `medium`. + */ + eagerness?: 'low' | 'medium' | 'high' | 'auto'; + + /** + * Whether or not to automatically interrupt any ongoing response with output to + * the default conversation (i.e. `conversation` of `auto`) when a VAD start event + * occurs. Not available for transcription sessions. + */ + interrupt_response?: boolean; + + /** + * Used only for `server_vad` mode. Amount of audio to include before the VAD + * detected speech (in milliseconds). Defaults to 300ms. + */ + prefix_padding_ms?: number; + + /** + * Used only for `server_vad` mode. Duration of silence to detect speech stop (in + * milliseconds). Defaults to 500ms. With shorter values the model will respond + * more quickly, but may jump in on short pauses from the user. + */ + silence_duration_ms?: number; + + /** + * Used only for `server_vad` mode. Activation threshold for VAD (0.0 to 1.0), this + * defaults to 0.5. A higher threshold will require louder audio to activate the + * model, and thus might perform better in noisy environments. + */ + threshold?: number; + + /** + * Type of turn detection. + */ + type?: 'server_vad' | 'semantic_vad'; + } +} + +export declare namespace TranscriptionSessions { + export { + type TranscriptionSession as TranscriptionSession, + type TranscriptionSessionCreateParams as TranscriptionSessionCreateParams, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/threads.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/threads.ts new file mode 100644 index 0000000000000000000000000000000000000000..705f670162ed91a8abf77a10ffdd1639860c718e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/threads.ts @@ -0,0 +1,3 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export * from './threads/index'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/threads/index.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/threads/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..7eefa6553cda1477ced2635ddb1120c6e1bd48a0 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/threads/index.ts @@ -0,0 +1,77 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export { + Messages, + type Annotation, + type AnnotationDelta, + type FileCitationAnnotation, + type FileCitationDeltaAnnotation, + type FilePathAnnotation, + type FilePathDeltaAnnotation, + type ImageFile, + type ImageFileContentBlock, + type ImageFileDelta, + type ImageFileDeltaBlock, + type ImageURL, + type ImageURLContentBlock, + type ImageURLDelta, + type ImageURLDeltaBlock, + type Message, + type MessageContent, + type MessageContentDelta, + type MessageContentPartParam, + type MessageDeleted, + type MessageDelta, + type MessageDeltaEvent, + type RefusalContentBlock, + type RefusalDeltaBlock, + type Text, + type TextContentBlock, + type TextContentBlockParam, + type TextDelta, + type TextDeltaBlock, + type MessageCreateParams, + type MessageRetrieveParams, + type MessageUpdateParams, + type MessageListParams, + type MessageDeleteParams, + type MessagesPage, +} from './messages'; +export { + Runs, + type RequiredActionFunctionToolCall, + type Run, + type RunStatus, + type RunCreateParams, + type RunCreateParamsNonStreaming, + type RunCreateParamsStreaming, + type RunRetrieveParams, + type RunUpdateParams, + type RunListParams, + type RunCancelParams, + type RunSubmitToolOutputsParams, + type RunSubmitToolOutputsParamsNonStreaming, + type RunSubmitToolOutputsParamsStreaming, + type RunsPage, + type RunCreateAndPollParams, + type RunCreateAndStreamParams, + type RunStreamParams, + type RunSubmitToolOutputsAndPollParams, + type RunSubmitToolOutputsStreamParams, +} from './runs/index'; +export { + Threads, + type AssistantResponseFormatOption, + type AssistantToolChoice, + type AssistantToolChoiceFunction, + type AssistantToolChoiceOption, + type Thread, + type ThreadDeleted, + type ThreadCreateParams, + type ThreadUpdateParams, + type ThreadCreateAndRunParams, + type ThreadCreateAndRunParamsNonStreaming, + type ThreadCreateAndRunParamsStreaming, + type ThreadCreateAndRunPollParams, + type ThreadCreateAndRunStreamParams, +} from './threads'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/threads/messages.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/threads/messages.ts new file mode 100644 index 0000000000000000000000000000000000000000..b487d3988a9ee0d25ea02a931b1ee45e91324cd1 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/threads/messages.ts @@ -0,0 +1,792 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../../core/resource'; +import * as Shared from '../../shared'; +import * as AssistantsAPI from '../assistants'; +import { APIPromise } from '../../../core/api-promise'; +import { CursorPage, type CursorPageParams, PagePromise } from '../../../core/pagination'; +import { buildHeaders } from '../../../internal/headers'; +import { RequestOptions } from '../../../internal/request-options'; +import { path } from '../../../internal/utils/path'; + +/** + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ +export class Messages extends APIResource { + /** + * Create a message. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + create(threadID: string, body: MessageCreateParams, options?: RequestOptions): APIPromise { + return this._client.post(path`/threads/${threadID}/messages`, { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + + /** + * Retrieve a message. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + retrieve(messageID: string, params: MessageRetrieveParams, options?: RequestOptions): APIPromise { + const { thread_id } = params; + return this._client.get(path`/threads/${thread_id}/messages/${messageID}`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + + /** + * Modifies a message. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + update(messageID: string, params: MessageUpdateParams, options?: RequestOptions): APIPromise { + const { thread_id, ...body } = params; + return this._client.post(path`/threads/${thread_id}/messages/${messageID}`, { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + + /** + * Returns a list of messages for a given thread. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + list( + threadID: string, + query: MessageListParams | null | undefined = {}, + options?: RequestOptions, + ): PagePromise { + return this._client.getAPIList(path`/threads/${threadID}/messages`, CursorPage, { + query, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + + /** + * Deletes a message. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + delete( + messageID: string, + params: MessageDeleteParams, + options?: RequestOptions, + ): APIPromise { + const { thread_id } = params; + return this._client.delete(path`/threads/${thread_id}/messages/${messageID}`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } +} + +export type MessagesPage = CursorPage; + +/** + * A citation within the message that points to a specific quote from a specific + * File associated with the assistant or the message. Generated when the assistant + * uses the "file_search" tool to search files. + */ +export type Annotation = FileCitationAnnotation | FilePathAnnotation; + +/** + * A citation within the message that points to a specific quote from a specific + * File associated with the assistant or the message. Generated when the assistant + * uses the "file_search" tool to search files. + */ +export type AnnotationDelta = FileCitationDeltaAnnotation | FilePathDeltaAnnotation; + +/** + * A citation within the message that points to a specific quote from a specific + * File associated with the assistant or the message. Generated when the assistant + * uses the "file_search" tool to search files. + */ +export interface FileCitationAnnotation { + end_index: number; + + file_citation: FileCitationAnnotation.FileCitation; + + start_index: number; + + /** + * The text in the message content that needs to be replaced. + */ + text: string; + + /** + * Always `file_citation`. + */ + type: 'file_citation'; +} + +export namespace FileCitationAnnotation { + export interface FileCitation { + /** + * The ID of the specific File the citation is from. + */ + file_id: string; + } +} + +/** + * A citation within the message that points to a specific quote from a specific + * File associated with the assistant or the message. Generated when the assistant + * uses the "file_search" tool to search files. + */ +export interface FileCitationDeltaAnnotation { + /** + * The index of the annotation in the text content part. + */ + index: number; + + /** + * Always `file_citation`. + */ + type: 'file_citation'; + + end_index?: number; + + file_citation?: FileCitationDeltaAnnotation.FileCitation; + + start_index?: number; + + /** + * The text in the message content that needs to be replaced. + */ + text?: string; +} + +export namespace FileCitationDeltaAnnotation { + export interface FileCitation { + /** + * The ID of the specific File the citation is from. + */ + file_id?: string; + + /** + * The specific quote in the file. + */ + quote?: string; + } +} + +/** + * A URL for the file that's generated when the assistant used the + * `code_interpreter` tool to generate a file. + */ +export interface FilePathAnnotation { + end_index: number; + + file_path: FilePathAnnotation.FilePath; + + start_index: number; + + /** + * The text in the message content that needs to be replaced. + */ + text: string; + + /** + * Always `file_path`. + */ + type: 'file_path'; +} + +export namespace FilePathAnnotation { + export interface FilePath { + /** + * The ID of the file that was generated. + */ + file_id: string; + } +} + +/** + * A URL for the file that's generated when the assistant used the + * `code_interpreter` tool to generate a file. + */ +export interface FilePathDeltaAnnotation { + /** + * The index of the annotation in the text content part. + */ + index: number; + + /** + * Always `file_path`. + */ + type: 'file_path'; + + end_index?: number; + + file_path?: FilePathDeltaAnnotation.FilePath; + + start_index?: number; + + /** + * The text in the message content that needs to be replaced. + */ + text?: string; +} + +export namespace FilePathDeltaAnnotation { + export interface FilePath { + /** + * The ID of the file that was generated. + */ + file_id?: string; + } +} + +export interface ImageFile { + /** + * The [File](https://platform.openai.com/docs/api-reference/files) ID of the image + * in the message content. Set `purpose="vision"` when uploading the File if you + * need to later display the file content. + */ + file_id: string; + + /** + * Specifies the detail level of the image if specified by the user. `low` uses + * fewer tokens, you can opt in to high resolution using `high`. + */ + detail?: 'auto' | 'low' | 'high'; +} + +/** + * References an image [File](https://platform.openai.com/docs/api-reference/files) + * in the content of a message. + */ +export interface ImageFileContentBlock { + image_file: ImageFile; + + /** + * Always `image_file`. + */ + type: 'image_file'; +} + +export interface ImageFileDelta { + /** + * Specifies the detail level of the image if specified by the user. `low` uses + * fewer tokens, you can opt in to high resolution using `high`. + */ + detail?: 'auto' | 'low' | 'high'; + + /** + * The [File](https://platform.openai.com/docs/api-reference/files) ID of the image + * in the message content. Set `purpose="vision"` when uploading the File if you + * need to later display the file content. + */ + file_id?: string; +} + +/** + * References an image [File](https://platform.openai.com/docs/api-reference/files) + * in the content of a message. + */ +export interface ImageFileDeltaBlock { + /** + * The index of the content part in the message. + */ + index: number; + + /** + * Always `image_file`. + */ + type: 'image_file'; + + image_file?: ImageFileDelta; +} + +export interface ImageURL { + /** + * The external URL of the image, must be a supported image types: jpeg, jpg, png, + * gif, webp. + */ + url: string; + + /** + * Specifies the detail level of the image. `low` uses fewer tokens, you can opt in + * to high resolution using `high`. Default value is `auto` + */ + detail?: 'auto' | 'low' | 'high'; +} + +/** + * References an image URL in the content of a message. + */ +export interface ImageURLContentBlock { + image_url: ImageURL; + + /** + * The type of the content part. + */ + type: 'image_url'; +} + +export interface ImageURLDelta { + /** + * Specifies the detail level of the image. `low` uses fewer tokens, you can opt in + * to high resolution using `high`. + */ + detail?: 'auto' | 'low' | 'high'; + + /** + * The URL of the image, must be a supported image types: jpeg, jpg, png, gif, + * webp. + */ + url?: string; +} + +/** + * References an image URL in the content of a message. + */ +export interface ImageURLDeltaBlock { + /** + * The index of the content part in the message. + */ + index: number; + + /** + * Always `image_url`. + */ + type: 'image_url'; + + image_url?: ImageURLDelta; +} + +/** + * Represents a message within a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ +export interface Message { + /** + * The identifier, which can be referenced in API endpoints. + */ + id: string; + + /** + * If applicable, the ID of the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) that + * authored this message. + */ + assistant_id: string | null; + + /** + * A list of files attached to the message, and the tools they were added to. + */ + attachments: Array | null; + + /** + * The Unix timestamp (in seconds) for when the message was completed. + */ + completed_at: number | null; + + /** + * The content of the message in array of text and/or images. + */ + content: Array; + + /** + * The Unix timestamp (in seconds) for when the message was created. + */ + created_at: number; + + /** + * The Unix timestamp (in seconds) for when the message was marked as incomplete. + */ + incomplete_at: number | null; + + /** + * On an incomplete message, details about why the message is incomplete. + */ + incomplete_details: Message.IncompleteDetails | null; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata: Shared.Metadata | null; + + /** + * The object type, which is always `thread.message`. + */ + object: 'thread.message'; + + /** + * The entity that produced the message. One of `user` or `assistant`. + */ + role: 'user' | 'assistant'; + + /** + * The ID of the [run](https://platform.openai.com/docs/api-reference/runs) + * associated with the creation of this message. Value is `null` when messages are + * created manually using the create message or create thread endpoints. + */ + run_id: string | null; + + /** + * The status of the message, which can be either `in_progress`, `incomplete`, or + * `completed`. + */ + status: 'in_progress' | 'incomplete' | 'completed'; + + /** + * The [thread](https://platform.openai.com/docs/api-reference/threads) ID that + * this message belongs to. + */ + thread_id: string; +} + +export namespace Message { + export interface Attachment { + /** + * The ID of the file to attach to the message. + */ + file_id?: string; + + /** + * The tools to add this file to. + */ + tools?: Array; + } + + export namespace Attachment { + export interface AssistantToolsFileSearchTypeOnly { + /** + * The type of tool being defined: `file_search` + */ + type: 'file_search'; + } + } + + /** + * On an incomplete message, details about why the message is incomplete. + */ + export interface IncompleteDetails { + /** + * The reason the message is incomplete. + */ + reason: 'content_filter' | 'max_tokens' | 'run_cancelled' | 'run_expired' | 'run_failed'; + } +} + +/** + * References an image [File](https://platform.openai.com/docs/api-reference/files) + * in the content of a message. + */ +export type MessageContent = + | ImageFileContentBlock + | ImageURLContentBlock + | TextContentBlock + | RefusalContentBlock; + +/** + * References an image [File](https://platform.openai.com/docs/api-reference/files) + * in the content of a message. + */ +export type MessageContentDelta = + | ImageFileDeltaBlock + | TextDeltaBlock + | RefusalDeltaBlock + | ImageURLDeltaBlock; + +/** + * References an image [File](https://platform.openai.com/docs/api-reference/files) + * in the content of a message. + */ +export type MessageContentPartParam = ImageFileContentBlock | ImageURLContentBlock | TextContentBlockParam; + +export interface MessageDeleted { + id: string; + + deleted: boolean; + + object: 'thread.message.deleted'; +} + +/** + * The delta containing the fields that have changed on the Message. + */ +export interface MessageDelta { + /** + * The content of the message in array of text and/or images. + */ + content?: Array; + + /** + * The entity that produced the message. One of `user` or `assistant`. + */ + role?: 'user' | 'assistant'; +} + +/** + * Represents a message delta i.e. any changed fields on a message during + * streaming. + */ +export interface MessageDeltaEvent { + /** + * The identifier of the message, which can be referenced in API endpoints. + */ + id: string; + + /** + * The delta containing the fields that have changed on the Message. + */ + delta: MessageDelta; + + /** + * The object type, which is always `thread.message.delta`. + */ + object: 'thread.message.delta'; +} + +/** + * The refusal content generated by the assistant. + */ +export interface RefusalContentBlock { + refusal: string; + + /** + * Always `refusal`. + */ + type: 'refusal'; +} + +/** + * The refusal content that is part of a message. + */ +export interface RefusalDeltaBlock { + /** + * The index of the refusal part in the message. + */ + index: number; + + /** + * Always `refusal`. + */ + type: 'refusal'; + + refusal?: string; +} + +export interface Text { + annotations: Array; + + /** + * The data that makes up the text. + */ + value: string; +} + +/** + * The text content that is part of a message. + */ +export interface TextContentBlock { + text: Text; + + /** + * Always `text`. + */ + type: 'text'; +} + +/** + * The text content that is part of a message. + */ +export interface TextContentBlockParam { + /** + * Text content to be sent to the model + */ + text: string; + + /** + * Always `text`. + */ + type: 'text'; +} + +export interface TextDelta { + annotations?: Array; + + /** + * The data that makes up the text. + */ + value?: string; +} + +/** + * The text content that is part of a message. + */ +export interface TextDeltaBlock { + /** + * The index of the content part in the message. + */ + index: number; + + /** + * Always `text`. + */ + type: 'text'; + + text?: TextDelta; +} + +export interface MessageCreateParams { + /** + * The text contents of the message. + */ + content: string | Array; + + /** + * The role of the entity that is creating the message. Allowed values include: + * + * - `user`: Indicates the message is sent by an actual user and should be used in + * most cases to represent user-generated messages. + * - `assistant`: Indicates the message is generated by the assistant. Use this + * value to insert messages from the assistant into the conversation. + */ + role: 'user' | 'assistant'; + + /** + * A list of files attached to the message, and the tools they should be added to. + */ + attachments?: Array | null; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; +} + +export namespace MessageCreateParams { + export interface Attachment { + /** + * The ID of the file to attach to the message. + */ + file_id?: string; + + /** + * The tools to add this file to. + */ + tools?: Array; + } + + export namespace Attachment { + export interface FileSearch { + /** + * The type of tool being defined: `file_search` + */ + type: 'file_search'; + } + } +} + +export interface MessageRetrieveParams { + /** + * The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) + * to which this message belongs. + */ + thread_id: string; +} + +export interface MessageUpdateParams { + /** + * Path param: The ID of the thread to which this message belongs. + */ + thread_id: string; + + /** + * Body param: Set of 16 key-value pairs that can be attached to an object. This + * can be useful for storing additional information about the object in a + * structured format, and querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; +} + +export interface MessageListParams extends CursorPageParams { + /** + * A cursor for use in pagination. `before` is an object ID that defines your place + * in the list. For instance, if you make a list request and receive 100 objects, + * starting with obj_foo, your subsequent call can include before=obj_foo in order + * to fetch the previous page of the list. + */ + before?: string; + + /** + * Sort order by the `created_at` timestamp of the objects. `asc` for ascending + * order and `desc` for descending order. + */ + order?: 'asc' | 'desc'; + + /** + * Filter messages by the run ID that generated them. + */ + run_id?: string; +} + +export interface MessageDeleteParams { + /** + * The ID of the thread to which this message belongs. + */ + thread_id: string; +} + +export declare namespace Messages { + export { + type Annotation as Annotation, + type AnnotationDelta as AnnotationDelta, + type FileCitationAnnotation as FileCitationAnnotation, + type FileCitationDeltaAnnotation as FileCitationDeltaAnnotation, + type FilePathAnnotation as FilePathAnnotation, + type FilePathDeltaAnnotation as FilePathDeltaAnnotation, + type ImageFile as ImageFile, + type ImageFileContentBlock as ImageFileContentBlock, + type ImageFileDelta as ImageFileDelta, + type ImageFileDeltaBlock as ImageFileDeltaBlock, + type ImageURL as ImageURL, + type ImageURLContentBlock as ImageURLContentBlock, + type ImageURLDelta as ImageURLDelta, + type ImageURLDeltaBlock as ImageURLDeltaBlock, + type Message as Message, + type MessageContent as MessageContent, + type MessageContentDelta as MessageContentDelta, + type MessageContentPartParam as MessageContentPartParam, + type MessageDeleted as MessageDeleted, + type MessageDelta as MessageDelta, + type MessageDeltaEvent as MessageDeltaEvent, + type RefusalContentBlock as RefusalContentBlock, + type RefusalDeltaBlock as RefusalDeltaBlock, + type Text as Text, + type TextContentBlock as TextContentBlock, + type TextContentBlockParam as TextContentBlockParam, + type TextDelta as TextDelta, + type TextDeltaBlock as TextDeltaBlock, + type MessagesPage as MessagesPage, + type MessageCreateParams as MessageCreateParams, + type MessageRetrieveParams as MessageRetrieveParams, + type MessageUpdateParams as MessageUpdateParams, + type MessageListParams as MessageListParams, + type MessageDeleteParams as MessageDeleteParams, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/threads/runs.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/threads/runs.ts new file mode 100644 index 0000000000000000000000000000000000000000..a3cc2bc7f368c9e74629deeeca3dadf838472172 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/threads/runs.ts @@ -0,0 +1,3 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export * from './runs/index'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/threads/runs/index.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/threads/runs/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..59c6a186c7bfae2a167aa1f94dcb6d3b31f343c0 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/threads/runs/index.ts @@ -0,0 +1,48 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export { + Runs, + type RequiredActionFunctionToolCall, + type Run, + type RunStatus, + type RunCreateParams, + type RunCreateParamsNonStreaming, + type RunCreateParamsStreaming, + type RunRetrieveParams, + type RunUpdateParams, + type RunListParams, + type RunCancelParams, + type RunSubmitToolOutputsParams, + type RunSubmitToolOutputsParamsNonStreaming, + type RunSubmitToolOutputsParamsStreaming, + type RunsPage, + type RunCreateAndPollParams, + type RunCreateAndStreamParams, + type RunStreamParams, + type RunSubmitToolOutputsAndPollParams, + type RunSubmitToolOutputsStreamParams, +} from './runs'; +export { + Steps, + type CodeInterpreterLogs, + type CodeInterpreterOutputImage, + type CodeInterpreterToolCall, + type CodeInterpreterToolCallDelta, + type FileSearchToolCall, + type FileSearchToolCallDelta, + type FunctionToolCall, + type FunctionToolCallDelta, + type MessageCreationStepDetails, + type RunStep, + type RunStepInclude, + type RunStepDelta, + type RunStepDeltaEvent, + type RunStepDeltaMessageDelta, + type ToolCall, + type ToolCallDelta, + type ToolCallDeltaObject, + type ToolCallsStepDetails, + type StepRetrieveParams, + type StepListParams, + type RunStepsPage, +} from './steps'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/threads/runs/runs.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/threads/runs/runs.ts new file mode 100644 index 0000000000000000000000000000000000000000..2b0ef987bdc38ae2aee296ee926ad8b088bc5c2e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/threads/runs/runs.ts @@ -0,0 +1,1072 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../../../core/resource'; +import * as RunsAPI from './runs'; +import * as Shared from '../../../shared'; +import * as AssistantsAPI from '../../assistants'; +import * as MessagesAPI from '../messages'; +import * as ThreadsAPI from '../threads'; +import * as StepsAPI from './steps'; +import { + CodeInterpreterLogs, + CodeInterpreterOutputImage, + CodeInterpreterToolCall, + CodeInterpreterToolCallDelta, + FileSearchToolCall, + FileSearchToolCallDelta, + FunctionToolCall, + FunctionToolCallDelta, + MessageCreationStepDetails, + RunStep, + RunStepDelta, + RunStepDeltaEvent, + RunStepDeltaMessageDelta, + RunStepInclude, + RunStepsPage, + StepListParams, + StepRetrieveParams, + Steps, + ToolCall, + ToolCallDelta, + ToolCallDeltaObject, + ToolCallsStepDetails, +} from './steps'; +import { APIPromise } from '../../../../core/api-promise'; +import { CursorPage, type CursorPageParams, PagePromise } from '../../../../core/pagination'; +import { Stream } from '../../../../core/streaming'; +import { buildHeaders } from '../../../../internal/headers'; +import { RequestOptions } from '../../../../internal/request-options'; +import { AssistantStream, RunCreateParamsBaseStream } from '../../../../lib/AssistantStream'; +import { sleep } from '../../../../internal/utils/sleep'; +import { RunSubmitToolOutputsParamsStream } from '../../../../lib/AssistantStream'; +import { path } from '../../../../internal/utils/path'; + +/** + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ +export class Runs extends APIResource { + steps: StepsAPI.Steps = new StepsAPI.Steps(this._client); + + /** + * Create a run. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + create(threadID: string, params: RunCreateParamsNonStreaming, options?: RequestOptions): APIPromise; + create( + threadID: string, + params: RunCreateParamsStreaming, + options?: RequestOptions, + ): APIPromise>; + create( + threadID: string, + params: RunCreateParamsBase, + options?: RequestOptions, + ): APIPromise | Run>; + create( + threadID: string, + params: RunCreateParams, + options?: RequestOptions, + ): APIPromise | APIPromise> { + const { include, ...body } = params; + return this._client.post(path`/threads/${threadID}/runs`, { + query: { include }, + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + stream: params.stream ?? false, + }) as APIPromise | APIPromise>; + } + + /** + * Retrieves a run. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + retrieve(runID: string, params: RunRetrieveParams, options?: RequestOptions): APIPromise { + const { thread_id } = params; + return this._client.get(path`/threads/${thread_id}/runs/${runID}`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + + /** + * Modifies a run. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + update(runID: string, params: RunUpdateParams, options?: RequestOptions): APIPromise { + const { thread_id, ...body } = params; + return this._client.post(path`/threads/${thread_id}/runs/${runID}`, { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + + /** + * Returns a list of runs belonging to a thread. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + list( + threadID: string, + query: RunListParams | null | undefined = {}, + options?: RequestOptions, + ): PagePromise { + return this._client.getAPIList(path`/threads/${threadID}/runs`, CursorPage, { + query, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + + /** + * Cancels a run that is `in_progress`. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + cancel(runID: string, params: RunCancelParams, options?: RequestOptions): APIPromise { + const { thread_id } = params; + return this._client.post(path`/threads/${thread_id}/runs/${runID}/cancel`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + + /** + * A helper to create a run an poll for a terminal state. More information on Run + * lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + async createAndPoll( + threadId: string, + body: RunCreateParamsNonStreaming, + options?: RequestOptions & { pollIntervalMs?: number }, + ): Promise { + const run = await this.create(threadId, body, options); + return await this.poll(run.id, { thread_id: threadId }, options); + } + + /** + * Create a Run stream + * + * @deprecated use `stream` instead + */ + createAndStream( + threadId: string, + body: RunCreateParamsBaseStream, + options?: RequestOptions, + ): AssistantStream { + return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options); + } + + /** + * A helper to poll a run status until it reaches a terminal state. More + * information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + async poll( + runId: string, + params: RunRetrieveParams, + options?: RequestOptions & { pollIntervalMs?: number }, + ): Promise { + const headers = buildHeaders([ + options?.headers, + { + 'X-Stainless-Poll-Helper': 'true', + 'X-Stainless-Custom-Poll-Interval': options?.pollIntervalMs?.toString() ?? undefined, + }, + ]); + + while (true) { + const { data: run, response } = await this.retrieve(runId, params, { + ...options, + headers: { ...options?.headers, ...headers }, + }).withResponse(); + + switch (run.status) { + //If we are in any sort of intermediate state we poll + case 'queued': + case 'in_progress': + case 'cancelling': + let sleepInterval = 5000; + + if (options?.pollIntervalMs) { + sleepInterval = options.pollIntervalMs; + } else { + const headerInterval = response.headers.get('openai-poll-after-ms'); + if (headerInterval) { + const headerIntervalMs = parseInt(headerInterval); + if (!isNaN(headerIntervalMs)) { + sleepInterval = headerIntervalMs; + } + } + } + await sleep(sleepInterval); + break; + //We return the run in any terminal state. + case 'requires_action': + case 'incomplete': + case 'cancelled': + case 'completed': + case 'failed': + case 'expired': + return run; + } + } + } + + /** + * Create a Run stream + */ + stream(threadId: string, body: RunCreateParamsBaseStream, options?: RequestOptions): AssistantStream { + return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options); + } + + /** + * When a run has the `status: "requires_action"` and `required_action.type` is + * `submit_tool_outputs`, this endpoint can be used to submit the outputs from the + * tool calls once they're all completed. All outputs must be submitted in a single + * request. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + submitToolOutputs( + runID: string, + params: RunSubmitToolOutputsParamsNonStreaming, + options?: RequestOptions, + ): APIPromise; + submitToolOutputs( + runID: string, + params: RunSubmitToolOutputsParamsStreaming, + options?: RequestOptions, + ): APIPromise>; + submitToolOutputs( + runID: string, + params: RunSubmitToolOutputsParamsBase, + options?: RequestOptions, + ): APIPromise | Run>; + submitToolOutputs( + runID: string, + params: RunSubmitToolOutputsParams, + options?: RequestOptions, + ): APIPromise | APIPromise> { + const { thread_id, ...body } = params; + return this._client.post(path`/threads/${thread_id}/runs/${runID}/submit_tool_outputs`, { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + stream: params.stream ?? false, + }) as APIPromise | APIPromise>; + } + + /** + * A helper to submit a tool output to a run and poll for a terminal run state. + * More information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + async submitToolOutputsAndPoll( + runId: string, + params: RunSubmitToolOutputsParamsNonStreaming, + options?: RequestOptions & { pollIntervalMs?: number }, + ): Promise { + const run = await this.submitToolOutputs(runId, params, options); + return await this.poll(run.id, params, options); + } + + /** + * Submit the tool outputs from a previous run and stream the run to a terminal + * state. More information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + submitToolOutputsStream( + runId: string, + params: RunSubmitToolOutputsParamsStream, + options?: RequestOptions, + ): AssistantStream { + return AssistantStream.createToolAssistantStream(runId, this._client.beta.threads.runs, params, options); + } +} + +export type RunsPage = CursorPage; + +/** + * Tool call objects + */ +export interface RequiredActionFunctionToolCall { + /** + * The ID of the tool call. This ID must be referenced when you submit the tool + * outputs in using the + * [Submit tool outputs to run](https://platform.openai.com/docs/api-reference/runs/submitToolOutputs) + * endpoint. + */ + id: string; + + /** + * The function definition. + */ + function: RequiredActionFunctionToolCall.Function; + + /** + * The type of tool call the output is required for. For now, this is always + * `function`. + */ + type: 'function'; +} + +export namespace RequiredActionFunctionToolCall { + /** + * The function definition. + */ + export interface Function { + /** + * The arguments that the model expects you to pass to the function. + */ + arguments: string; + + /** + * The name of the function. + */ + name: string; + } +} + +/** + * Represents an execution run on a + * [thread](https://platform.openai.com/docs/api-reference/threads). + */ +export interface Run { + /** + * The identifier, which can be referenced in API endpoints. + */ + id: string; + + /** + * The ID of the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) used for + * execution of this run. + */ + assistant_id: string; + + /** + * The Unix timestamp (in seconds) for when the run was cancelled. + */ + cancelled_at: number | null; + + /** + * The Unix timestamp (in seconds) for when the run was completed. + */ + completed_at: number | null; + + /** + * The Unix timestamp (in seconds) for when the run was created. + */ + created_at: number; + + /** + * The Unix timestamp (in seconds) for when the run will expire. + */ + expires_at: number | null; + + /** + * The Unix timestamp (in seconds) for when the run failed. + */ + failed_at: number | null; + + /** + * Details on why the run is incomplete. Will be `null` if the run is not + * incomplete. + */ + incomplete_details: Run.IncompleteDetails | null; + + /** + * The instructions that the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) used for + * this run. + */ + instructions: string; + + /** + * The last error associated with this run. Will be `null` if there are no errors. + */ + last_error: Run.LastError | null; + + /** + * The maximum number of completion tokens specified to have been used over the + * course of the run. + */ + max_completion_tokens: number | null; + + /** + * The maximum number of prompt tokens specified to have been used over the course + * of the run. + */ + max_prompt_tokens: number | null; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata: Shared.Metadata | null; + + /** + * The model that the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) used for + * this run. + */ + model: string; + + /** + * The object type, which is always `thread.run`. + */ + object: 'thread.run'; + + /** + * Whether to enable + * [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) + * during tool use. + */ + parallel_tool_calls: boolean; + + /** + * Details on the action required to continue the run. Will be `null` if no action + * is required. + */ + required_action: Run.RequiredAction | null; + + /** + * Specifies the format that the model must output. Compatible with + * [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), + * [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), + * and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + * + * Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + * Outputs which ensures the model will match your supplied JSON schema. Learn more + * in the + * [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + * + * Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the + * message the model generates is valid JSON. + * + * **Important:** when using JSON mode, you **must** also instruct the model to + * produce JSON yourself via a system or user message. Without this, the model may + * generate an unending stream of whitespace until the generation reaches the token + * limit, resulting in a long-running and seemingly "stuck" request. Also note that + * the message content may be partially cut off if `finish_reason="length"`, which + * indicates the generation exceeded `max_tokens` or the conversation exceeded the + * max context length. + */ + response_format: ThreadsAPI.AssistantResponseFormatOption | null; + + /** + * The Unix timestamp (in seconds) for when the run was started. + */ + started_at: number | null; + + /** + * The status of the run, which can be either `queued`, `in_progress`, + * `requires_action`, `cancelling`, `cancelled`, `failed`, `completed`, + * `incomplete`, or `expired`. + */ + status: RunStatus; + + /** + * The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) + * that was executed on as a part of this run. + */ + thread_id: string; + + /** + * Controls which (if any) tool is called by the model. `none` means the model will + * not call any tools and instead generates a message. `auto` is the default value + * and means the model can pick between generating a message or calling one or more + * tools. `required` means the model must call one or more tools before responding + * to the user. Specifying a particular tool like `{"type": "file_search"}` or + * `{"type": "function", "function": {"name": "my_function"}}` forces the model to + * call that tool. + */ + tool_choice: ThreadsAPI.AssistantToolChoiceOption | null; + + /** + * The list of tools that the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) used for + * this run. + */ + tools: Array; + + /** + * Controls for how a thread will be truncated prior to the run. Use this to + * control the initial context window of the run. + */ + truncation_strategy: Run.TruncationStrategy | null; + + /** + * Usage statistics related to the run. This value will be `null` if the run is not + * in a terminal state (i.e. `in_progress`, `queued`, etc.). + */ + usage: Run.Usage | null; + + /** + * The sampling temperature used for this run. If not set, defaults to 1. + */ + temperature?: number | null; + + /** + * The nucleus sampling value used for this run. If not set, defaults to 1. + */ + top_p?: number | null; +} + +export namespace Run { + /** + * Details on why the run is incomplete. Will be `null` if the run is not + * incomplete. + */ + export interface IncompleteDetails { + /** + * The reason why the run is incomplete. This will point to which specific token + * limit was reached over the course of the run. + */ + reason?: 'max_completion_tokens' | 'max_prompt_tokens'; + } + + /** + * The last error associated with this run. Will be `null` if there are no errors. + */ + export interface LastError { + /** + * One of `server_error`, `rate_limit_exceeded`, or `invalid_prompt`. + */ + code: 'server_error' | 'rate_limit_exceeded' | 'invalid_prompt'; + + /** + * A human-readable description of the error. + */ + message: string; + } + + /** + * Details on the action required to continue the run. Will be `null` if no action + * is required. + */ + export interface RequiredAction { + /** + * Details on the tool outputs needed for this run to continue. + */ + submit_tool_outputs: RequiredAction.SubmitToolOutputs; + + /** + * For now, this is always `submit_tool_outputs`. + */ + type: 'submit_tool_outputs'; + } + + export namespace RequiredAction { + /** + * Details on the tool outputs needed for this run to continue. + */ + export interface SubmitToolOutputs { + /** + * A list of the relevant tool calls. + */ + tool_calls: Array; + } + } + + /** + * Controls for how a thread will be truncated prior to the run. Use this to + * control the initial context window of the run. + */ + export interface TruncationStrategy { + /** + * The truncation strategy to use for the thread. The default is `auto`. If set to + * `last_messages`, the thread will be truncated to the n most recent messages in + * the thread. When set to `auto`, messages in the middle of the thread will be + * dropped to fit the context length of the model, `max_prompt_tokens`. + */ + type: 'auto' | 'last_messages'; + + /** + * The number of most recent messages from the thread when constructing the context + * for the run. + */ + last_messages?: number | null; + } + + /** + * Usage statistics related to the run. This value will be `null` if the run is not + * in a terminal state (i.e. `in_progress`, `queued`, etc.). + */ + export interface Usage { + /** + * Number of completion tokens used over the course of the run. + */ + completion_tokens: number; + + /** + * Number of prompt tokens used over the course of the run. + */ + prompt_tokens: number; + + /** + * Total number of tokens used (prompt + completion). + */ + total_tokens: number; + } +} + +/** + * The status of the run, which can be either `queued`, `in_progress`, + * `requires_action`, `cancelling`, `cancelled`, `failed`, `completed`, + * `incomplete`, or `expired`. + */ +export type RunStatus = + | 'queued' + | 'in_progress' + | 'requires_action' + | 'cancelling' + | 'cancelled' + | 'failed' + | 'completed' + | 'incomplete' + | 'expired'; + +export type RunCreateParams = RunCreateParamsNonStreaming | RunCreateParamsStreaming; + +export interface RunCreateParamsBase { + /** + * Body param: The ID of the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to + * execute this run. + */ + assistant_id: string; + + /** + * Query param: A list of additional fields to include in the response. Currently + * the only supported value is + * `step_details.tool_calls[*].file_search.results[*].content` to fetch the file + * search result content. + * + * See the + * [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) + * for more information. + */ + include?: Array; + + /** + * Body param: Appends additional instructions at the end of the instructions for + * the run. This is useful for modifying the behavior on a per-run basis without + * overriding other instructions. + */ + additional_instructions?: string | null; + + /** + * Body param: Adds additional messages to the thread before creating the run. + */ + additional_messages?: Array | null; + + /** + * Body param: Overrides the + * [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) + * of the assistant. This is useful for modifying the behavior on a per-run basis. + */ + instructions?: string | null; + + /** + * Body param: The maximum number of completion tokens that may be used over the + * course of the run. The run will make a best effort to use only the number of + * completion tokens specified, across multiple turns of the run. If the run + * exceeds the number of completion tokens specified, the run will end with status + * `incomplete`. See `incomplete_details` for more info. + */ + max_completion_tokens?: number | null; + + /** + * Body param: The maximum number of prompt tokens that may be used over the course + * of the run. The run will make a best effort to use only the number of prompt + * tokens specified, across multiple turns of the run. If the run exceeds the + * number of prompt tokens specified, the run will end with status `incomplete`. + * See `incomplete_details` for more info. + */ + max_prompt_tokens?: number | null; + + /** + * Body param: Set of 16 key-value pairs that can be attached to an object. This + * can be useful for storing additional information about the object in a + * structured format, and querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; + + /** + * Body param: The ID of the + * [Model](https://platform.openai.com/docs/api-reference/models) to be used to + * execute this run. If a value is provided here, it will override the model + * associated with the assistant. If not, the model associated with the assistant + * will be used. + */ + model?: (string & {}) | Shared.ChatModel | null; + + /** + * Body param: Whether to enable + * [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) + * during tool use. + */ + parallel_tool_calls?: boolean; + + /** + * Body param: Constrains effort on reasoning for + * [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently + * supported values are `minimal`, `low`, `medium`, and `high`. Reducing reasoning + * effort can result in faster responses and fewer tokens used on reasoning in a + * response. + */ + reasoning_effort?: Shared.ReasoningEffort | null; + + /** + * Body param: Specifies the format that the model must output. Compatible with + * [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), + * [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), + * and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + * + * Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + * Outputs which ensures the model will match your supplied JSON schema. Learn more + * in the + * [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + * + * Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the + * message the model generates is valid JSON. + * + * **Important:** when using JSON mode, you **must** also instruct the model to + * produce JSON yourself via a system or user message. Without this, the model may + * generate an unending stream of whitespace until the generation reaches the token + * limit, resulting in a long-running and seemingly "stuck" request. Also note that + * the message content may be partially cut off if `finish_reason="length"`, which + * indicates the generation exceeded `max_tokens` or the conversation exceeded the + * max context length. + */ + response_format?: ThreadsAPI.AssistantResponseFormatOption | null; + + /** + * Body param: If `true`, returns a stream of events that happen during the Run as + * server-sent events, terminating when the Run enters a terminal state with a + * `data: [DONE]` message. + */ + stream?: boolean | null; + + /** + * Body param: What sampling temperature to use, between 0 and 2. Higher values + * like 0.8 will make the output more random, while lower values like 0.2 will make + * it more focused and deterministic. + */ + temperature?: number | null; + + /** + * Body param: Controls which (if any) tool is called by the model. `none` means + * the model will not call any tools and instead generates a message. `auto` is the + * default value and means the model can pick between generating a message or + * calling one or more tools. `required` means the model must call one or more + * tools before responding to the user. Specifying a particular tool like + * `{"type": "file_search"}` or + * `{"type": "function", "function": {"name": "my_function"}}` forces the model to + * call that tool. + */ + tool_choice?: ThreadsAPI.AssistantToolChoiceOption | null; + + /** + * Body param: Override the tools the assistant can use for this run. This is + * useful for modifying the behavior on a per-run basis. + */ + tools?: Array | null; + + /** + * Body param: An alternative to sampling with temperature, called nucleus + * sampling, where the model considers the results of the tokens with top_p + * probability mass. So 0.1 means only the tokens comprising the top 10% + * probability mass are considered. + * + * We generally recommend altering this or temperature but not both. + */ + top_p?: number | null; + + /** + * Body param: Controls for how a thread will be truncated prior to the run. Use + * this to control the initial context window of the run. + */ + truncation_strategy?: RunCreateParams.TruncationStrategy | null; +} + +export namespace RunCreateParams { + export interface AdditionalMessage { + /** + * The text contents of the message. + */ + content: string | Array; + + /** + * The role of the entity that is creating the message. Allowed values include: + * + * - `user`: Indicates the message is sent by an actual user and should be used in + * most cases to represent user-generated messages. + * - `assistant`: Indicates the message is generated by the assistant. Use this + * value to insert messages from the assistant into the conversation. + */ + role: 'user' | 'assistant'; + + /** + * A list of files attached to the message, and the tools they should be added to. + */ + attachments?: Array | null; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; + } + + export namespace AdditionalMessage { + export interface Attachment { + /** + * The ID of the file to attach to the message. + */ + file_id?: string; + + /** + * The tools to add this file to. + */ + tools?: Array; + } + + export namespace Attachment { + export interface FileSearch { + /** + * The type of tool being defined: `file_search` + */ + type: 'file_search'; + } + } + } + + /** + * Controls for how a thread will be truncated prior to the run. Use this to + * control the initial context window of the run. + */ + export interface TruncationStrategy { + /** + * The truncation strategy to use for the thread. The default is `auto`. If set to + * `last_messages`, the thread will be truncated to the n most recent messages in + * the thread. When set to `auto`, messages in the middle of the thread will be + * dropped to fit the context length of the model, `max_prompt_tokens`. + */ + type: 'auto' | 'last_messages'; + + /** + * The number of most recent messages from the thread when constructing the context + * for the run. + */ + last_messages?: number | null; + } + + export type RunCreateParamsNonStreaming = RunsAPI.RunCreateParamsNonStreaming; + export type RunCreateParamsStreaming = RunsAPI.RunCreateParamsStreaming; +} + +export interface RunCreateParamsNonStreaming extends RunCreateParamsBase { + /** + * Body param: If `true`, returns a stream of events that happen during the Run as + * server-sent events, terminating when the Run enters a terminal state with a + * `data: [DONE]` message. + */ + stream?: false | null; +} + +export interface RunCreateParamsStreaming extends RunCreateParamsBase { + /** + * Body param: If `true`, returns a stream of events that happen during the Run as + * server-sent events, terminating when the Run enters a terminal state with a + * `data: [DONE]` message. + */ + stream: true; +} + +export interface RunRetrieveParams { + /** + * The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) + * that was run. + */ + thread_id: string; +} + +export interface RunUpdateParams { + /** + * Path param: The ID of the + * [thread](https://platform.openai.com/docs/api-reference/threads) that was run. + */ + thread_id: string; + + /** + * Body param: Set of 16 key-value pairs that can be attached to an object. This + * can be useful for storing additional information about the object in a + * structured format, and querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; +} + +export interface RunListParams extends CursorPageParams { + /** + * A cursor for use in pagination. `before` is an object ID that defines your place + * in the list. For instance, if you make a list request and receive 100 objects, + * starting with obj_foo, your subsequent call can include before=obj_foo in order + * to fetch the previous page of the list. + */ + before?: string; + + /** + * Sort order by the `created_at` timestamp of the objects. `asc` for ascending + * order and `desc` for descending order. + */ + order?: 'asc' | 'desc'; +} + +export interface RunCancelParams { + /** + * The ID of the thread to which this run belongs. + */ + thread_id: string; +} + +export type RunCreateAndPollParams = ThreadsAPI.ThreadCreateAndRunParamsNonStreaming; + +export type RunCreateAndStreamParams = RunCreateParamsBaseStream; + +export type RunStreamParams = RunCreateParamsBaseStream; + +export type RunSubmitToolOutputsParams = + | RunSubmitToolOutputsParamsNonStreaming + | RunSubmitToolOutputsParamsStreaming; + +export interface RunSubmitToolOutputsParamsBase { + /** + * Path param: The ID of the + * [thread](https://platform.openai.com/docs/api-reference/threads) to which this + * run belongs. + */ + thread_id: string; + + /** + * Body param: A list of tools for which the outputs are being submitted. + */ + tool_outputs: Array; + + /** + * Body param: If `true`, returns a stream of events that happen during the Run as + * server-sent events, terminating when the Run enters a terminal state with a + * `data: [DONE]` message. + */ + stream?: boolean | null; +} + +export namespace RunSubmitToolOutputsParams { + export interface ToolOutput { + /** + * The output of the tool call to be submitted to continue the run. + */ + output?: string; + + /** + * The ID of the tool call in the `required_action` object within the run object + * the output is being submitted for. + */ + tool_call_id?: string; + } + + export type RunSubmitToolOutputsParamsNonStreaming = RunsAPI.RunSubmitToolOutputsParamsNonStreaming; + export type RunSubmitToolOutputsParamsStreaming = RunsAPI.RunSubmitToolOutputsParamsStreaming; +} + +export interface RunSubmitToolOutputsParamsNonStreaming extends RunSubmitToolOutputsParamsBase { + /** + * Body param: If `true`, returns a stream of events that happen during the Run as + * server-sent events, terminating when the Run enters a terminal state with a + * `data: [DONE]` message. + */ + stream?: false | null; +} + +export interface RunSubmitToolOutputsParamsStreaming extends RunSubmitToolOutputsParamsBase { + /** + * Body param: If `true`, returns a stream of events that happen during the Run as + * server-sent events, terminating when the Run enters a terminal state with a + * `data: [DONE]` message. + */ + stream: true; +} + +export type RunSubmitToolOutputsAndPollParams = RunSubmitToolOutputsParamsNonStreaming; +export type RunSubmitToolOutputsStreamParams = RunSubmitToolOutputsParamsStream; + +Runs.Steps = Steps; + +export declare namespace Runs { + export { + type RequiredActionFunctionToolCall as RequiredActionFunctionToolCall, + type Run as Run, + type RunStatus as RunStatus, + type RunsPage as RunsPage, + type RunCreateParams as RunCreateParams, + type RunCreateParamsNonStreaming as RunCreateParamsNonStreaming, + type RunCreateParamsStreaming as RunCreateParamsStreaming, + type RunRetrieveParams as RunRetrieveParams, + type RunUpdateParams as RunUpdateParams, + type RunListParams as RunListParams, + type RunCreateAndPollParams, + type RunCreateAndStreamParams, + type RunStreamParams, + type RunSubmitToolOutputsParams as RunSubmitToolOutputsParams, + type RunSubmitToolOutputsParamsNonStreaming as RunSubmitToolOutputsParamsNonStreaming, + type RunSubmitToolOutputsParamsStreaming as RunSubmitToolOutputsParamsStreaming, + type RunSubmitToolOutputsAndPollParams, + type RunSubmitToolOutputsStreamParams, + }; + + export { + Steps as Steps, + type CodeInterpreterLogs as CodeInterpreterLogs, + type CodeInterpreterOutputImage as CodeInterpreterOutputImage, + type CodeInterpreterToolCall as CodeInterpreterToolCall, + type CodeInterpreterToolCallDelta as CodeInterpreterToolCallDelta, + type FileSearchToolCall as FileSearchToolCall, + type FileSearchToolCallDelta as FileSearchToolCallDelta, + type FunctionToolCall as FunctionToolCall, + type FunctionToolCallDelta as FunctionToolCallDelta, + type MessageCreationStepDetails as MessageCreationStepDetails, + type RunStep as RunStep, + type RunStepDelta as RunStepDelta, + type RunStepDeltaEvent as RunStepDeltaEvent, + type RunStepDeltaMessageDelta as RunStepDeltaMessageDelta, + type RunStepInclude as RunStepInclude, + type ToolCall as ToolCall, + type ToolCallDelta as ToolCallDelta, + type ToolCallDeltaObject as ToolCallDeltaObject, + type ToolCallsStepDetails as ToolCallsStepDetails, + type RunStepsPage as RunStepsPage, + type StepRetrieveParams as StepRetrieveParams, + type StepListParams as StepListParams, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/threads/runs/steps.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/threads/runs/steps.ts new file mode 100644 index 0000000000000000000000000000000000000000..bbbafb54346656efa48fea8df4e2202825eefafd --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/threads/runs/steps.ts @@ -0,0 +1,756 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../../../core/resource'; +import * as StepsAPI from './steps'; +import * as Shared from '../../../shared'; +import { APIPromise } from '../../../../core/api-promise'; +import { CursorPage, type CursorPageParams, PagePromise } from '../../../../core/pagination'; +import { buildHeaders } from '../../../../internal/headers'; +import { RequestOptions } from '../../../../internal/request-options'; +import { path } from '../../../../internal/utils/path'; + +/** + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ +export class Steps extends APIResource { + /** + * Retrieves a run step. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + retrieve(stepID: string, params: StepRetrieveParams, options?: RequestOptions): APIPromise { + const { thread_id, run_id, ...query } = params; + return this._client.get(path`/threads/${thread_id}/runs/${run_id}/steps/${stepID}`, { + query, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + + /** + * Returns a list of run steps belonging to a run. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + list(runID: string, params: StepListParams, options?: RequestOptions): PagePromise { + const { thread_id, ...query } = params; + return this._client.getAPIList(path`/threads/${thread_id}/runs/${runID}/steps`, CursorPage, { + query, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } +} + +export type RunStepsPage = CursorPage; + +/** + * Text output from the Code Interpreter tool call as part of a run step. + */ +export interface CodeInterpreterLogs { + /** + * The index of the output in the outputs array. + */ + index: number; + + /** + * Always `logs`. + */ + type: 'logs'; + + /** + * The text output from the Code Interpreter tool call. + */ + logs?: string; +} + +export interface CodeInterpreterOutputImage { + /** + * The index of the output in the outputs array. + */ + index: number; + + /** + * Always `image`. + */ + type: 'image'; + + image?: CodeInterpreterOutputImage.Image; +} + +export namespace CodeInterpreterOutputImage { + export interface Image { + /** + * The [file](https://platform.openai.com/docs/api-reference/files) ID of the + * image. + */ + file_id?: string; + } +} + +/** + * Details of the Code Interpreter tool call the run step was involved in. + */ +export interface CodeInterpreterToolCall { + /** + * The ID of the tool call. + */ + id: string; + + /** + * The Code Interpreter tool call definition. + */ + code_interpreter: CodeInterpreterToolCall.CodeInterpreter; + + /** + * The type of tool call. This is always going to be `code_interpreter` for this + * type of tool call. + */ + type: 'code_interpreter'; +} + +export namespace CodeInterpreterToolCall { + /** + * The Code Interpreter tool call definition. + */ + export interface CodeInterpreter { + /** + * The input to the Code Interpreter tool call. + */ + input: string; + + /** + * The outputs from the Code Interpreter tool call. Code Interpreter can output one + * or more items, including text (`logs`) or images (`image`). Each of these are + * represented by a different object type. + */ + outputs: Array; + } + + export namespace CodeInterpreter { + /** + * Text output from the Code Interpreter tool call as part of a run step. + */ + export interface Logs { + /** + * The text output from the Code Interpreter tool call. + */ + logs: string; + + /** + * Always `logs`. + */ + type: 'logs'; + } + + export interface Image { + image: Image.Image; + + /** + * Always `image`. + */ + type: 'image'; + } + + export namespace Image { + export interface Image { + /** + * The [file](https://platform.openai.com/docs/api-reference/files) ID of the + * image. + */ + file_id: string; + } + } + } +} + +/** + * Details of the Code Interpreter tool call the run step was involved in. + */ +export interface CodeInterpreterToolCallDelta { + /** + * The index of the tool call in the tool calls array. + */ + index: number; + + /** + * The type of tool call. This is always going to be `code_interpreter` for this + * type of tool call. + */ + type: 'code_interpreter'; + + /** + * The ID of the tool call. + */ + id?: string; + + /** + * The Code Interpreter tool call definition. + */ + code_interpreter?: CodeInterpreterToolCallDelta.CodeInterpreter; +} + +export namespace CodeInterpreterToolCallDelta { + /** + * The Code Interpreter tool call definition. + */ + export interface CodeInterpreter { + /** + * The input to the Code Interpreter tool call. + */ + input?: string; + + /** + * The outputs from the Code Interpreter tool call. Code Interpreter can output one + * or more items, including text (`logs`) or images (`image`). Each of these are + * represented by a different object type. + */ + outputs?: Array; + } +} + +export interface FileSearchToolCall { + /** + * The ID of the tool call object. + */ + id: string; + + /** + * For now, this is always going to be an empty object. + */ + file_search: FileSearchToolCall.FileSearch; + + /** + * The type of tool call. This is always going to be `file_search` for this type of + * tool call. + */ + type: 'file_search'; +} + +export namespace FileSearchToolCall { + /** + * For now, this is always going to be an empty object. + */ + export interface FileSearch { + /** + * The ranking options for the file search. + */ + ranking_options?: FileSearch.RankingOptions; + + /** + * The results of the file search. + */ + results?: Array; + } + + export namespace FileSearch { + /** + * The ranking options for the file search. + */ + export interface RankingOptions { + /** + * The ranker to use for the file search. If not specified will use the `auto` + * ranker. + */ + ranker: 'auto' | 'default_2024_08_21'; + + /** + * The score threshold for the file search. All values must be a floating point + * number between 0 and 1. + */ + score_threshold: number; + } + + /** + * A result instance of the file search. + */ + export interface Result { + /** + * The ID of the file that result was found in. + */ + file_id: string; + + /** + * The name of the file that result was found in. + */ + file_name: string; + + /** + * The score of the result. All values must be a floating point number between 0 + * and 1. + */ + score: number; + + /** + * The content of the result that was found. The content is only included if + * requested via the include query parameter. + */ + content?: Array; + } + + export namespace Result { + export interface Content { + /** + * The text content of the file. + */ + text?: string; + + /** + * The type of the content. + */ + type?: 'text'; + } + } + } +} + +export interface FileSearchToolCallDelta { + /** + * For now, this is always going to be an empty object. + */ + file_search: unknown; + + /** + * The index of the tool call in the tool calls array. + */ + index: number; + + /** + * The type of tool call. This is always going to be `file_search` for this type of + * tool call. + */ + type: 'file_search'; + + /** + * The ID of the tool call object. + */ + id?: string; +} + +export interface FunctionToolCall { + /** + * The ID of the tool call object. + */ + id: string; + + /** + * The definition of the function that was called. + */ + function: FunctionToolCall.Function; + + /** + * The type of tool call. This is always going to be `function` for this type of + * tool call. + */ + type: 'function'; +} + +export namespace FunctionToolCall { + /** + * The definition of the function that was called. + */ + export interface Function { + /** + * The arguments passed to the function. + */ + arguments: string; + + /** + * The name of the function. + */ + name: string; + + /** + * The output of the function. This will be `null` if the outputs have not been + * [submitted](https://platform.openai.com/docs/api-reference/runs/submitToolOutputs) + * yet. + */ + output: string | null; + } +} + +export interface FunctionToolCallDelta { + /** + * The index of the tool call in the tool calls array. + */ + index: number; + + /** + * The type of tool call. This is always going to be `function` for this type of + * tool call. + */ + type: 'function'; + + /** + * The ID of the tool call object. + */ + id?: string; + + /** + * The definition of the function that was called. + */ + function?: FunctionToolCallDelta.Function; +} + +export namespace FunctionToolCallDelta { + /** + * The definition of the function that was called. + */ + export interface Function { + /** + * The arguments passed to the function. + */ + arguments?: string; + + /** + * The name of the function. + */ + name?: string; + + /** + * The output of the function. This will be `null` if the outputs have not been + * [submitted](https://platform.openai.com/docs/api-reference/runs/submitToolOutputs) + * yet. + */ + output?: string | null; + } +} + +/** + * Details of the message creation by the run step. + */ +export interface MessageCreationStepDetails { + message_creation: MessageCreationStepDetails.MessageCreation; + + /** + * Always `message_creation`. + */ + type: 'message_creation'; +} + +export namespace MessageCreationStepDetails { + export interface MessageCreation { + /** + * The ID of the message that was created by this run step. + */ + message_id: string; + } +} + +/** + * Represents a step in execution of a run. + */ +export interface RunStep { + /** + * The identifier of the run step, which can be referenced in API endpoints. + */ + id: string; + + /** + * The ID of the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) + * associated with the run step. + */ + assistant_id: string; + + /** + * The Unix timestamp (in seconds) for when the run step was cancelled. + */ + cancelled_at: number | null; + + /** + * The Unix timestamp (in seconds) for when the run step completed. + */ + completed_at: number | null; + + /** + * The Unix timestamp (in seconds) for when the run step was created. + */ + created_at: number; + + /** + * The Unix timestamp (in seconds) for when the run step expired. A step is + * considered expired if the parent run is expired. + */ + expired_at: number | null; + + /** + * The Unix timestamp (in seconds) for when the run step failed. + */ + failed_at: number | null; + + /** + * The last error associated with this run step. Will be `null` if there are no + * errors. + */ + last_error: RunStep.LastError | null; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata: Shared.Metadata | null; + + /** + * The object type, which is always `thread.run.step`. + */ + object: 'thread.run.step'; + + /** + * The ID of the [run](https://platform.openai.com/docs/api-reference/runs) that + * this run step is a part of. + */ + run_id: string; + + /** + * The status of the run step, which can be either `in_progress`, `cancelled`, + * `failed`, `completed`, or `expired`. + */ + status: 'in_progress' | 'cancelled' | 'failed' | 'completed' | 'expired'; + + /** + * The details of the run step. + */ + step_details: MessageCreationStepDetails | ToolCallsStepDetails; + + /** + * The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) + * that was run. + */ + thread_id: string; + + /** + * The type of run step, which can be either `message_creation` or `tool_calls`. + */ + type: 'message_creation' | 'tool_calls'; + + /** + * Usage statistics related to the run step. This value will be `null` while the + * run step's status is `in_progress`. + */ + usage: RunStep.Usage | null; +} + +export namespace RunStep { + /** + * The last error associated with this run step. Will be `null` if there are no + * errors. + */ + export interface LastError { + /** + * One of `server_error` or `rate_limit_exceeded`. + */ + code: 'server_error' | 'rate_limit_exceeded'; + + /** + * A human-readable description of the error. + */ + message: string; + } + + /** + * Usage statistics related to the run step. This value will be `null` while the + * run step's status is `in_progress`. + */ + export interface Usage { + /** + * Number of completion tokens used over the course of the run step. + */ + completion_tokens: number; + + /** + * Number of prompt tokens used over the course of the run step. + */ + prompt_tokens: number; + + /** + * Total number of tokens used (prompt + completion). + */ + total_tokens: number; + } +} + +/** + * The delta containing the fields that have changed on the run step. + */ +export interface RunStepDelta { + /** + * The details of the run step. + */ + step_details?: RunStepDeltaMessageDelta | ToolCallDeltaObject; +} + +/** + * Represents a run step delta i.e. any changed fields on a run step during + * streaming. + */ +export interface RunStepDeltaEvent { + /** + * The identifier of the run step, which can be referenced in API endpoints. + */ + id: string; + + /** + * The delta containing the fields that have changed on the run step. + */ + delta: RunStepDelta; + + /** + * The object type, which is always `thread.run.step.delta`. + */ + object: 'thread.run.step.delta'; +} + +/** + * Details of the message creation by the run step. + */ +export interface RunStepDeltaMessageDelta { + /** + * Always `message_creation`. + */ + type: 'message_creation'; + + message_creation?: RunStepDeltaMessageDelta.MessageCreation; +} + +export namespace RunStepDeltaMessageDelta { + export interface MessageCreation { + /** + * The ID of the message that was created by this run step. + */ + message_id?: string; + } +} + +export type RunStepInclude = 'step_details.tool_calls[*].file_search.results[*].content'; + +/** + * Details of the Code Interpreter tool call the run step was involved in. + */ +export type ToolCall = CodeInterpreterToolCall | FileSearchToolCall | FunctionToolCall; + +/** + * Details of the Code Interpreter tool call the run step was involved in. + */ +export type ToolCallDelta = CodeInterpreterToolCallDelta | FileSearchToolCallDelta | FunctionToolCallDelta; + +/** + * Details of the tool call. + */ +export interface ToolCallDeltaObject { + /** + * Always `tool_calls`. + */ + type: 'tool_calls'; + + /** + * An array of tool calls the run step was involved in. These can be associated + * with one of three types of tools: `code_interpreter`, `file_search`, or + * `function`. + */ + tool_calls?: Array; +} + +/** + * Details of the tool call. + */ +export interface ToolCallsStepDetails { + /** + * An array of tool calls the run step was involved in. These can be associated + * with one of three types of tools: `code_interpreter`, `file_search`, or + * `function`. + */ + tool_calls: Array; + + /** + * Always `tool_calls`. + */ + type: 'tool_calls'; +} + +export interface StepRetrieveParams { + /** + * Path param: The ID of the thread to which the run and run step belongs. + */ + thread_id: string; + + /** + * Path param: The ID of the run to which the run step belongs. + */ + run_id: string; + + /** + * Query param: A list of additional fields to include in the response. Currently + * the only supported value is + * `step_details.tool_calls[*].file_search.results[*].content` to fetch the file + * search result content. + * + * See the + * [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) + * for more information. + */ + include?: Array; +} + +export interface StepListParams extends CursorPageParams { + /** + * Path param: The ID of the thread the run and run steps belong to. + */ + thread_id: string; + + /** + * Query param: A cursor for use in pagination. `before` is an object ID that + * defines your place in the list. For instance, if you make a list request and + * receive 100 objects, starting with obj_foo, your subsequent call can include + * before=obj_foo in order to fetch the previous page of the list. + */ + before?: string; + + /** + * Query param: A list of additional fields to include in the response. Currently + * the only supported value is + * `step_details.tool_calls[*].file_search.results[*].content` to fetch the file + * search result content. + * + * See the + * [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) + * for more information. + */ + include?: Array; + + /** + * Query param: Sort order by the `created_at` timestamp of the objects. `asc` for + * ascending order and `desc` for descending order. + */ + order?: 'asc' | 'desc'; +} + +export declare namespace Steps { + export { + type CodeInterpreterLogs as CodeInterpreterLogs, + type CodeInterpreterOutputImage as CodeInterpreterOutputImage, + type CodeInterpreterToolCall as CodeInterpreterToolCall, + type CodeInterpreterToolCallDelta as CodeInterpreterToolCallDelta, + type FileSearchToolCall as FileSearchToolCall, + type FileSearchToolCallDelta as FileSearchToolCallDelta, + type FunctionToolCall as FunctionToolCall, + type FunctionToolCallDelta as FunctionToolCallDelta, + type MessageCreationStepDetails as MessageCreationStepDetails, + type RunStep as RunStep, + type RunStepDelta as RunStepDelta, + type RunStepDeltaEvent as RunStepDeltaEvent, + type RunStepDeltaMessageDelta as RunStepDeltaMessageDelta, + type RunStepInclude as RunStepInclude, + type ToolCall as ToolCall, + type ToolCallDelta as ToolCallDelta, + type ToolCallDeltaObject as ToolCallDeltaObject, + type ToolCallsStepDetails as ToolCallsStepDetails, + type RunStepsPage as RunStepsPage, + type StepRetrieveParams as StepRetrieveParams, + type StepListParams as StepListParams, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/threads/threads.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/threads/threads.ts new file mode 100644 index 0000000000000000000000000000000000000000..cc2313b1e938a5be663bc729ffb0b423d3a6b09c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/beta/threads/threads.ts @@ -0,0 +1,1397 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../../core/resource'; +import * as ThreadsAPI from './threads'; +import * as Shared from '../../shared'; +import * as AssistantsAPI from '../assistants'; +import * as MessagesAPI from './messages'; +import { + Annotation, + AnnotationDelta, + FileCitationAnnotation, + FileCitationDeltaAnnotation, + FilePathAnnotation, + FilePathDeltaAnnotation, + ImageFile, + ImageFileContentBlock, + ImageFileDelta, + ImageFileDeltaBlock, + ImageURL, + ImageURLContentBlock, + ImageURLDelta, + ImageURLDeltaBlock, + Message as MessagesAPIMessage, + MessageContent, + MessageContentDelta, + MessageContentPartParam, + MessageCreateParams, + MessageDeleteParams, + MessageDeleted, + MessageDelta, + MessageDeltaEvent, + MessageListParams, + MessageRetrieveParams, + MessageUpdateParams, + Messages, + MessagesPage, + RefusalContentBlock, + RefusalDeltaBlock, + Text, + TextContentBlock, + TextContentBlockParam, + TextDelta, + TextDeltaBlock, +} from './messages'; +import * as RunsAPI from './runs/runs'; +import { + RequiredActionFunctionToolCall, + Run, + RunCreateAndPollParams, + RunCreateAndStreamParams, + RunCancelParams, + RunCreateParams, + RunCreateParamsNonStreaming, + RunCreateParamsStreaming, + RunListParams, + RunRetrieveParams, + RunStatus, + RunStreamParams, + RunSubmitToolOutputsAndPollParams, + RunSubmitToolOutputsParams, + RunSubmitToolOutputsParamsNonStreaming, + RunSubmitToolOutputsParamsStreaming, + RunSubmitToolOutputsStreamParams, + RunUpdateParams, + Runs, + RunsPage, +} from './runs/runs'; +import { APIPromise } from '../../../core/api-promise'; +import { Stream } from '../../../core/streaming'; +import { buildHeaders } from '../../../internal/headers'; +import { RequestOptions } from '../../../internal/request-options'; +import { AssistantStream, ThreadCreateAndRunParamsBaseStream } from '../../../lib/AssistantStream'; +import { path } from '../../../internal/utils/path'; + +/** + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ +export class Threads extends APIResource { + runs: RunsAPI.Runs = new RunsAPI.Runs(this._client); + messages: MessagesAPI.Messages = new MessagesAPI.Messages(this._client); + + /** + * Create a thread. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + create(body: ThreadCreateParams | null | undefined = {}, options?: RequestOptions): APIPromise { + return this._client.post('/threads', { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + + /** + * Retrieves a thread. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + retrieve(threadID: string, options?: RequestOptions): APIPromise { + return this._client.get(path`/threads/${threadID}`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + + /** + * Modifies a thread. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + update(threadID: string, body: ThreadUpdateParams, options?: RequestOptions): APIPromise { + return this._client.post(path`/threads/${threadID}`, { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + + /** + * Delete a thread. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + delete(threadID: string, options?: RequestOptions): APIPromise { + return this._client.delete(path`/threads/${threadID}`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + + /** + * Create a thread and run it in one request. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + createAndRun(body: ThreadCreateAndRunParamsNonStreaming, options?: RequestOptions): APIPromise; + createAndRun( + body: ThreadCreateAndRunParamsStreaming, + options?: RequestOptions, + ): APIPromise>; + createAndRun( + body: ThreadCreateAndRunParamsBase, + options?: RequestOptions, + ): APIPromise | RunsAPI.Run>; + createAndRun( + body: ThreadCreateAndRunParams, + options?: RequestOptions, + ): APIPromise | APIPromise> { + return this._client.post('/threads/runs', { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + stream: body.stream ?? false, + }) as APIPromise | APIPromise>; + } + + /** + * A helper to create a thread, start a run and then poll for a terminal state. + * More information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + async createAndRunPoll( + body: ThreadCreateAndRunParamsNonStreaming, + options?: RequestOptions & { pollIntervalMs?: number }, + ): Promise { + const run = await this.createAndRun(body, options); + return await this.runs.poll(run.id, { thread_id: run.thread_id }, options); + } + + /** + * Create a thread and stream the run back + */ + createAndRunStream(body: ThreadCreateAndRunParamsBaseStream, options?: RequestOptions): AssistantStream { + return AssistantStream.createThreadAssistantStream(body, this._client.beta.threads, options); + } +} + +/** + * Specifies the format that the model must output. Compatible with + * [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), + * [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), + * and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + * + * Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + * Outputs which ensures the model will match your supplied JSON schema. Learn more + * in the + * [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + * + * Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the + * message the model generates is valid JSON. + * + * **Important:** when using JSON mode, you **must** also instruct the model to + * produce JSON yourself via a system or user message. Without this, the model may + * generate an unending stream of whitespace until the generation reaches the token + * limit, resulting in a long-running and seemingly "stuck" request. Also note that + * the message content may be partially cut off if `finish_reason="length"`, which + * indicates the generation exceeded `max_tokens` or the conversation exceeded the + * max context length. + */ +export type AssistantResponseFormatOption = + | 'auto' + | Shared.ResponseFormatText + | Shared.ResponseFormatJSONObject + | Shared.ResponseFormatJSONSchema; + +/** + * Specifies a tool the model should use. Use to force the model to call a specific + * tool. + */ +export interface AssistantToolChoice { + /** + * The type of the tool. If type is `function`, the function name must be set + */ + type: 'function' | 'code_interpreter' | 'file_search'; + + function?: AssistantToolChoiceFunction; +} + +export interface AssistantToolChoiceFunction { + /** + * The name of the function to call. + */ + name: string; +} + +/** + * Controls which (if any) tool is called by the model. `none` means the model will + * not call any tools and instead generates a message. `auto` is the default value + * and means the model can pick between generating a message or calling one or more + * tools. `required` means the model must call one or more tools before responding + * to the user. Specifying a particular tool like `{"type": "file_search"}` or + * `{"type": "function", "function": {"name": "my_function"}}` forces the model to + * call that tool. + */ +export type AssistantToolChoiceOption = 'none' | 'auto' | 'required' | AssistantToolChoice; + +/** + * Represents a thread that contains + * [messages](https://platform.openai.com/docs/api-reference/messages). + */ +export interface Thread { + /** + * The identifier, which can be referenced in API endpoints. + */ + id: string; + + /** + * The Unix timestamp (in seconds) for when the thread was created. + */ + created_at: number; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata: Shared.Metadata | null; + + /** + * The object type, which is always `thread`. + */ + object: 'thread'; + + /** + * A set of resources that are made available to the assistant's tools in this + * thread. The resources are specific to the type of tool. For example, the + * `code_interpreter` tool requires a list of file IDs, while the `file_search` + * tool requires a list of vector store IDs. + */ + tool_resources: Thread.ToolResources | null; +} + +export namespace Thread { + /** + * A set of resources that are made available to the assistant's tools in this + * thread. The resources are specific to the type of tool. For example, the + * `code_interpreter` tool requires a list of file IDs, while the `file_search` + * tool requires a list of vector store IDs. + */ + export interface ToolResources { + code_interpreter?: ToolResources.CodeInterpreter; + + file_search?: ToolResources.FileSearch; + } + + export namespace ToolResources { + export interface CodeInterpreter { + /** + * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made + * available to the `code_interpreter` tool. There can be a maximum of 20 files + * associated with the tool. + */ + file_ids?: Array; + } + + export interface FileSearch { + /** + * The + * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) + * attached to this thread. There can be a maximum of 1 vector store attached to + * the thread. + */ + vector_store_ids?: Array; + } + } +} + +export interface ThreadDeleted { + id: string; + + deleted: boolean; + + object: 'thread.deleted'; +} + +export interface ThreadCreateParams { + /** + * A list of [messages](https://platform.openai.com/docs/api-reference/messages) to + * start the thread with. + */ + messages?: Array; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; + + /** + * A set of resources that are made available to the assistant's tools in this + * thread. The resources are specific to the type of tool. For example, the + * `code_interpreter` tool requires a list of file IDs, while the `file_search` + * tool requires a list of vector store IDs. + */ + tool_resources?: ThreadCreateParams.ToolResources | null; +} + +export namespace ThreadCreateParams { + export interface Message { + /** + * The text contents of the message. + */ + content: string | Array; + + /** + * The role of the entity that is creating the message. Allowed values include: + * + * - `user`: Indicates the message is sent by an actual user and should be used in + * most cases to represent user-generated messages. + * - `assistant`: Indicates the message is generated by the assistant. Use this + * value to insert messages from the assistant into the conversation. + */ + role: 'user' | 'assistant'; + + /** + * A list of files attached to the message, and the tools they should be added to. + */ + attachments?: Array | null; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; + } + + export namespace Message { + export interface Attachment { + /** + * The ID of the file to attach to the message. + */ + file_id?: string; + + /** + * The tools to add this file to. + */ + tools?: Array; + } + + export namespace Attachment { + export interface FileSearch { + /** + * The type of tool being defined: `file_search` + */ + type: 'file_search'; + } + } + } + + /** + * A set of resources that are made available to the assistant's tools in this + * thread. The resources are specific to the type of tool. For example, the + * `code_interpreter` tool requires a list of file IDs, while the `file_search` + * tool requires a list of vector store IDs. + */ + export interface ToolResources { + code_interpreter?: ToolResources.CodeInterpreter; + + file_search?: ToolResources.FileSearch; + } + + export namespace ToolResources { + export interface CodeInterpreter { + /** + * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made + * available to the `code_interpreter` tool. There can be a maximum of 20 files + * associated with the tool. + */ + file_ids?: Array; + } + + export interface FileSearch { + /** + * The + * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) + * attached to this thread. There can be a maximum of 1 vector store attached to + * the thread. + */ + vector_store_ids?: Array; + + /** + * A helper to create a + * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) + * with file_ids and attach it to this thread. There can be a maximum of 1 vector + * store attached to the thread. + */ + vector_stores?: Array; + } + + export namespace FileSearch { + export interface VectorStore { + /** + * The chunking strategy used to chunk the file(s). If not set, will use the `auto` + * strategy. + */ + chunking_strategy?: VectorStore.Auto | VectorStore.Static; + + /** + * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs to + * add to the vector store. There can be a maximum of 10000 files in a vector + * store. + */ + file_ids?: Array; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; + } + + export namespace VectorStore { + /** + * The default strategy. This strategy currently uses a `max_chunk_size_tokens` of + * `800` and `chunk_overlap_tokens` of `400`. + */ + export interface Auto { + /** + * Always `auto`. + */ + type: 'auto'; + } + + export interface Static { + static: Static.Static; + + /** + * Always `static`. + */ + type: 'static'; + } + + export namespace Static { + export interface Static { + /** + * The number of tokens that overlap between chunks. The default value is `400`. + * + * Note that the overlap must not exceed half of `max_chunk_size_tokens`. + */ + chunk_overlap_tokens: number; + + /** + * The maximum number of tokens in each chunk. The default value is `800`. The + * minimum value is `100` and the maximum value is `4096`. + */ + max_chunk_size_tokens: number; + } + } + } + } + } +} + +export interface ThreadUpdateParams { + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; + + /** + * A set of resources that are made available to the assistant's tools in this + * thread. The resources are specific to the type of tool. For example, the + * `code_interpreter` tool requires a list of file IDs, while the `file_search` + * tool requires a list of vector store IDs. + */ + tool_resources?: ThreadUpdateParams.ToolResources | null; +} + +export namespace ThreadUpdateParams { + /** + * A set of resources that are made available to the assistant's tools in this + * thread. The resources are specific to the type of tool. For example, the + * `code_interpreter` tool requires a list of file IDs, while the `file_search` + * tool requires a list of vector store IDs. + */ + export interface ToolResources { + code_interpreter?: ToolResources.CodeInterpreter; + + file_search?: ToolResources.FileSearch; + } + + export namespace ToolResources { + export interface CodeInterpreter { + /** + * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made + * available to the `code_interpreter` tool. There can be a maximum of 20 files + * associated with the tool. + */ + file_ids?: Array; + } + + export interface FileSearch { + /** + * The + * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) + * attached to this thread. There can be a maximum of 1 vector store attached to + * the thread. + */ + vector_store_ids?: Array; + } + } +} + +export type ThreadCreateAndRunParams = + | ThreadCreateAndRunParamsNonStreaming + | ThreadCreateAndRunParamsStreaming; + +export interface ThreadCreateAndRunParamsBase { + /** + * The ID of the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to + * execute this run. + */ + assistant_id: string; + + /** + * Override the default system message of the assistant. This is useful for + * modifying the behavior on a per-run basis. + */ + instructions?: string | null; + + /** + * The maximum number of completion tokens that may be used over the course of the + * run. The run will make a best effort to use only the number of completion tokens + * specified, across multiple turns of the run. If the run exceeds the number of + * completion tokens specified, the run will end with status `incomplete`. See + * `incomplete_details` for more info. + */ + max_completion_tokens?: number | null; + + /** + * The maximum number of prompt tokens that may be used over the course of the run. + * The run will make a best effort to use only the number of prompt tokens + * specified, across multiple turns of the run. If the run exceeds the number of + * prompt tokens specified, the run will end with status `incomplete`. See + * `incomplete_details` for more info. + */ + max_prompt_tokens?: number | null; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; + + /** + * The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to + * be used to execute this run. If a value is provided here, it will override the + * model associated with the assistant. If not, the model associated with the + * assistant will be used. + */ + model?: (string & {}) | Shared.ChatModel | null; + + /** + * Whether to enable + * [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) + * during tool use. + */ + parallel_tool_calls?: boolean; + + /** + * Specifies the format that the model must output. Compatible with + * [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), + * [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), + * and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + * + * Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + * Outputs which ensures the model will match your supplied JSON schema. Learn more + * in the + * [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + * + * Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the + * message the model generates is valid JSON. + * + * **Important:** when using JSON mode, you **must** also instruct the model to + * produce JSON yourself via a system or user message. Without this, the model may + * generate an unending stream of whitespace until the generation reaches the token + * limit, resulting in a long-running and seemingly "stuck" request. Also note that + * the message content may be partially cut off if `finish_reason="length"`, which + * indicates the generation exceeded `max_tokens` or the conversation exceeded the + * max context length. + */ + response_format?: AssistantResponseFormatOption | null; + + /** + * If `true`, returns a stream of events that happen during the Run as server-sent + * events, terminating when the Run enters a terminal state with a `data: [DONE]` + * message. + */ + stream?: boolean | null; + + /** + * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + * make the output more random, while lower values like 0.2 will make it more + * focused and deterministic. + */ + temperature?: number | null; + + /** + * Options to create a new thread. If no thread is provided when running a request, + * an empty thread will be created. + */ + thread?: ThreadCreateAndRunParams.Thread; + + /** + * Controls which (if any) tool is called by the model. `none` means the model will + * not call any tools and instead generates a message. `auto` is the default value + * and means the model can pick between generating a message or calling one or more + * tools. `required` means the model must call one or more tools before responding + * to the user. Specifying a particular tool like `{"type": "file_search"}` or + * `{"type": "function", "function": {"name": "my_function"}}` forces the model to + * call that tool. + */ + tool_choice?: AssistantToolChoiceOption | null; + + /** + * A set of resources that are used by the assistant's tools. The resources are + * specific to the type of tool. For example, the `code_interpreter` tool requires + * a list of file IDs, while the `file_search` tool requires a list of vector store + * IDs. + */ + tool_resources?: ThreadCreateAndRunParams.ToolResources | null; + + /** + * Override the tools the assistant can use for this run. This is useful for + * modifying the behavior on a per-run basis. + */ + tools?: Array | null; + + /** + * An alternative to sampling with temperature, called nucleus sampling, where the + * model considers the results of the tokens with top_p probability mass. So 0.1 + * means only the tokens comprising the top 10% probability mass are considered. + * + * We generally recommend altering this or temperature but not both. + */ + top_p?: number | null; + + /** + * Controls for how a thread will be truncated prior to the run. Use this to + * control the initial context window of the run. + */ + truncation_strategy?: ThreadCreateAndRunParams.TruncationStrategy | null; +} + +export namespace ThreadCreateAndRunParams { + /** + * Options to create a new thread. If no thread is provided when running a request, + * an empty thread will be created. + */ + export interface Thread { + /** + * A list of [messages](https://platform.openai.com/docs/api-reference/messages) to + * start the thread with. + */ + messages?: Array; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; + + /** + * A set of resources that are made available to the assistant's tools in this + * thread. The resources are specific to the type of tool. For example, the + * `code_interpreter` tool requires a list of file IDs, while the `file_search` + * tool requires a list of vector store IDs. + */ + tool_resources?: Thread.ToolResources | null; + } + + export namespace Thread { + export interface Message { + /** + * The text contents of the message. + */ + content: string | Array; + + /** + * The role of the entity that is creating the message. Allowed values include: + * + * - `user`: Indicates the message is sent by an actual user and should be used in + * most cases to represent user-generated messages. + * - `assistant`: Indicates the message is generated by the assistant. Use this + * value to insert messages from the assistant into the conversation. + */ + role: 'user' | 'assistant'; + + /** + * A list of files attached to the message, and the tools they should be added to. + */ + attachments?: Array | null; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; + } + + export namespace Message { + export interface Attachment { + /** + * The ID of the file to attach to the message. + */ + file_id?: string; + + /** + * The tools to add this file to. + */ + tools?: Array; + } + + export namespace Attachment { + export interface FileSearch { + /** + * The type of tool being defined: `file_search` + */ + type: 'file_search'; + } + } + } + + /** + * A set of resources that are made available to the assistant's tools in this + * thread. The resources are specific to the type of tool. For example, the + * `code_interpreter` tool requires a list of file IDs, while the `file_search` + * tool requires a list of vector store IDs. + */ + export interface ToolResources { + code_interpreter?: ToolResources.CodeInterpreter; + + file_search?: ToolResources.FileSearch; + } + + export namespace ToolResources { + export interface CodeInterpreter { + /** + * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made + * available to the `code_interpreter` tool. There can be a maximum of 20 files + * associated with the tool. + */ + file_ids?: Array; + } + + export interface FileSearch { + /** + * The + * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) + * attached to this thread. There can be a maximum of 1 vector store attached to + * the thread. + */ + vector_store_ids?: Array; + + /** + * A helper to create a + * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) + * with file_ids and attach it to this thread. There can be a maximum of 1 vector + * store attached to the thread. + */ + vector_stores?: Array; + } + + export namespace FileSearch { + export interface VectorStore { + /** + * The chunking strategy used to chunk the file(s). If not set, will use the `auto` + * strategy. + */ + chunking_strategy?: VectorStore.Auto | VectorStore.Static; + + /** + * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs to + * add to the vector store. There can be a maximum of 10000 files in a vector + * store. + */ + file_ids?: Array; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; + } + + export namespace VectorStore { + /** + * The default strategy. This strategy currently uses a `max_chunk_size_tokens` of + * `800` and `chunk_overlap_tokens` of `400`. + */ + export interface Auto { + /** + * Always `auto`. + */ + type: 'auto'; + } + + export interface Static { + static: Static.Static; + + /** + * Always `static`. + */ + type: 'static'; + } + + export namespace Static { + export interface Static { + /** + * The number of tokens that overlap between chunks. The default value is `400`. + * + * Note that the overlap must not exceed half of `max_chunk_size_tokens`. + */ + chunk_overlap_tokens: number; + + /** + * The maximum number of tokens in each chunk. The default value is `800`. The + * minimum value is `100` and the maximum value is `4096`. + */ + max_chunk_size_tokens: number; + } + } + } + } + } + } + + /** + * A set of resources that are used by the assistant's tools. The resources are + * specific to the type of tool. For example, the `code_interpreter` tool requires + * a list of file IDs, while the `file_search` tool requires a list of vector store + * IDs. + */ + export interface ToolResources { + code_interpreter?: ToolResources.CodeInterpreter; + + file_search?: ToolResources.FileSearch; + } + + export namespace ToolResources { + export interface CodeInterpreter { + /** + * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made + * available to the `code_interpreter` tool. There can be a maximum of 20 files + * associated with the tool. + */ + file_ids?: Array; + } + + export interface FileSearch { + /** + * The ID of the + * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) + * attached to this assistant. There can be a maximum of 1 vector store attached to + * the assistant. + */ + vector_store_ids?: Array; + } + } + + /** + * Controls for how a thread will be truncated prior to the run. Use this to + * control the initial context window of the run. + */ + export interface TruncationStrategy { + /** + * The truncation strategy to use for the thread. The default is `auto`. If set to + * `last_messages`, the thread will be truncated to the n most recent messages in + * the thread. When set to `auto`, messages in the middle of the thread will be + * dropped to fit the context length of the model, `max_prompt_tokens`. + */ + type: 'auto' | 'last_messages'; + + /** + * The number of most recent messages from the thread when constructing the context + * for the run. + */ + last_messages?: number | null; + } + + export type ThreadCreateAndRunParamsNonStreaming = ThreadsAPI.ThreadCreateAndRunParamsNonStreaming; + export type ThreadCreateAndRunParamsStreaming = ThreadsAPI.ThreadCreateAndRunParamsStreaming; +} + +export interface ThreadCreateAndRunParamsNonStreaming extends ThreadCreateAndRunParamsBase { + /** + * If `true`, returns a stream of events that happen during the Run as server-sent + * events, terminating when the Run enters a terminal state with a `data: [DONE]` + * message. + */ + stream?: false | null; +} + +export interface ThreadCreateAndRunParamsStreaming extends ThreadCreateAndRunParamsBase { + /** + * If `true`, returns a stream of events that happen during the Run as server-sent + * events, terminating when the Run enters a terminal state with a `data: [DONE]` + * message. + */ + stream: true; +} + +export interface ThreadCreateAndRunPollParams { + /** + * The ID of the + * [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to + * execute this run. + */ + assistant_id: string; + + /** + * Override the default system message of the assistant. This is useful for + * modifying the behavior on a per-run basis. + */ + instructions?: string | null; + + /** + * The maximum number of completion tokens that may be used over the course of the + * run. The run will make a best effort to use only the number of completion tokens + * specified, across multiple turns of the run. If the run exceeds the number of + * completion tokens specified, the run will end with status `incomplete`. See + * `incomplete_details` for more info. + */ + max_completion_tokens?: number | null; + + /** + * The maximum number of prompt tokens that may be used over the course of the run. + * The run will make a best effort to use only the number of prompt tokens + * specified, across multiple turns of the run. If the run exceeds the number of + * prompt tokens specified, the run will end with status `incomplete`. See + * `incomplete_details` for more info. + */ + max_prompt_tokens?: number | null; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + + /** + * The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to + * be used to execute this run. If a value is provided here, it will override the + * model associated with the assistant. If not, the model associated with the + * assistant will be used. + */ + model?: + | (string & {}) + | 'gpt-4o' + | 'gpt-4o-2024-05-13' + | 'gpt-4-turbo' + | 'gpt-4-turbo-2024-04-09' + | 'gpt-4-0125-preview' + | 'gpt-4-turbo-preview' + | 'gpt-4-1106-preview' + | 'gpt-4-vision-preview' + | 'gpt-4' + | 'gpt-4-0314' + | 'gpt-4-0613' + | 'gpt-4-32k' + | 'gpt-4-32k-0314' + | 'gpt-4-32k-0613' + | 'gpt-3.5-turbo' + | 'gpt-3.5-turbo-16k' + | 'gpt-3.5-turbo-0613' + | 'gpt-3.5-turbo-1106' + | 'gpt-3.5-turbo-0125' + | 'gpt-3.5-turbo-16k-0613' + | null; + + /** + * Specifies the format that the model must output. Compatible with + * [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), + * [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + * and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + * + * Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + * message the model generates is valid JSON. + * + * **Important:** when using JSON mode, you **must** also instruct the model to + * produce JSON yourself via a system or user message. Without this, the model may + * generate an unending stream of whitespace until the generation reaches the token + * limit, resulting in a long-running and seemingly "stuck" request. Also note that + * the message content may be partially cut off if `finish_reason="length"`, which + * indicates the generation exceeded `max_tokens` or the conversation exceeded the + * max context length. + */ + response_format?: AssistantResponseFormatOption | null; + + /** + * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + * make the output more random, while lower values like 0.2 will make it more + * focused and deterministic. + */ + temperature?: number | null; + + /** + * If no thread is provided, an empty thread will be created. + */ + thread?: ThreadCreateAndRunPollParams.Thread; + + /** + * Controls which (if any) tool is called by the model. `none` means the model will + * not call any tools and instead generates a message. `auto` is the default value + * and means the model can pick between generating a message or calling one or more + * tools. `required` means the model must call one or more tools before responding + * to the user. Specifying a particular tool like `{"type": "file_search"}` or + * `{"type": "function", "function": {"name": "my_function"}}` forces the model to + * call that tool. + */ + tool_choice?: AssistantToolChoiceOption | null; + + /** + * A set of resources that are used by the assistant's tools. The resources are + * specific to the type of tool. For example, the `code_interpreter` tool requires + * a list of file IDs, while the `file_search` tool requires a list of vector store + * IDs. + */ + tool_resources?: ThreadCreateAndRunPollParams.ToolResources | null; + + /** + * Override the tools the assistant can use for this run. This is useful for + * modifying the behavior on a per-run basis. + */ + tools?: Array< + AssistantsAPI.CodeInterpreterTool | AssistantsAPI.FileSearchTool | AssistantsAPI.FunctionTool + > | null; + + /** + * An alternative to sampling with temperature, called nucleus sampling, where the + * model considers the results of the tokens with top_p probability mass. So 0.1 + * means only the tokens comprising the top 10% probability mass are considered. + * + * We generally recommend altering this or temperature but not both. + */ + top_p?: number | null; + + /** + * Controls for how a thread will be truncated prior to the run. Use this to + * control the intial context window of the run. + */ + truncation_strategy?: ThreadCreateAndRunPollParams.TruncationStrategy | null; +} + +export namespace ThreadCreateAndRunPollParams { + /** + * If no thread is provided, an empty thread will be created. + */ + export interface Thread { + /** + * A list of [messages](https://platform.openai.com/docs/api-reference/messages) to + * start the thread with. + */ + messages?: Array; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + + /** + * A set of resources that are made available to the assistant's tools in this + * thread. The resources are specific to the type of tool. For example, the + * `code_interpreter` tool requires a list of file IDs, while the `file_search` + * tool requires a list of vector store IDs. + */ + tool_resources?: Thread.ToolResources | null; + } + + export namespace Thread { + export interface Message { + /** + * The text contents of the message. + */ + content: string | Array; + + /** + * The role of the entity that is creating the message. Allowed values include: + * + * - `user`: Indicates the message is sent by an actual user and should be used in + * most cases to represent user-generated messages. + * - `assistant`: Indicates the message is generated by the assistant. Use this + * value to insert messages from the assistant into the conversation. + */ + role: 'user' | 'assistant'; + + /** + * A list of files attached to the message, and the tools they should be added to. + */ + attachments?: Array | null; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format. Keys + * can be a maximum of 64 characters long and values can be a maxium of 512 + * characters long. + */ + metadata?: unknown | null; + } + + export namespace Message { + export interface Attachment { + /** + * The ID of the file to attach to the message. + */ + file_id?: string; + + /** + * The tools to add this file to. + */ + tools?: Array; + } + } + + /** + * A set of resources that are made available to the assistant's tools in this + * thread. The resources are specific to the type of tool. For example, the + * `code_interpreter` tool requires a list of file IDs, while the `file_search` + * tool requires a list of vector store IDs. + */ + export interface ToolResources { + code_interpreter?: ToolResources.CodeInterpreter; + + file_search?: ToolResources.FileSearch; + } + + export namespace ToolResources { + export interface CodeInterpreter { + /** + * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made + * available to the `code_interpreter` tool. There can be a maximum of 20 files + * associated with the tool. + */ + file_ids?: Array; + } + + export interface FileSearch { + /** + * The + * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) + * attached to this thread. There can be a maximum of 1 vector store attached to + * the thread. + */ + vector_store_ids?: Array; + + /** + * A helper to create a + * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) + * with file_ids and attach it to this thread. There can be a maximum of 1 vector + * store attached to the thread. + */ + vector_stores?: Array; + } + + export namespace FileSearch { + export interface VectorStore { + /** + * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs to + * add to the vector store. There can be a maximum of 10000 files in a vector + * store. + */ + file_ids?: Array; + + /** + * Set of 16 key-value pairs that can be attached to a vector store. This can be + * useful for storing additional information about the vector store in a structured + * format. Keys can be a maximum of 64 characters long and values can be a maxium + * of 512 characters long. + */ + metadata?: unknown; + } + } + } + } + + /** + * A set of resources that are used by the assistant's tools. The resources are + * specific to the type of tool. For example, the `code_interpreter` tool requires + * a list of file IDs, while the `file_search` tool requires a list of vector store + * IDs. + */ + export interface ToolResources { + code_interpreter?: ToolResources.CodeInterpreter; + + file_search?: ToolResources.FileSearch; + } + + export namespace ToolResources { + export interface CodeInterpreter { + /** + * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made + * available to the `code_interpreter` tool. There can be a maximum of 20 files + * associated with the tool. + */ + file_ids?: Array; + } + + export interface FileSearch { + /** + * The ID of the + * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) + * attached to this assistant. There can be a maximum of 1 vector store attached to + * the assistant. + */ + vector_store_ids?: Array; + } + } + + /** + * Controls for how a thread will be truncated prior to the run. Use this to + * control the intial context window of the run. + */ + export interface TruncationStrategy { + /** + * The truncation strategy to use for the thread. The default is `auto`. If set to + * `last_messages`, the thread will be truncated to the n most recent messages in + * the thread. When set to `auto`, messages in the middle of the thread will be + * dropped to fit the context length of the model, `max_prompt_tokens`. + */ + type: 'auto' | 'last_messages'; + + /** + * The number of most recent messages from the thread when constructing the context + * for the run. + */ + last_messages?: number | null; + } +} + +export type ThreadCreateAndRunStreamParams = ThreadCreateAndRunParamsBaseStream; + +Threads.Runs = Runs; +Threads.Messages = Messages; + +export declare namespace Threads { + export { + type AssistantResponseFormatOption as AssistantResponseFormatOption, + type AssistantToolChoice as AssistantToolChoice, + type AssistantToolChoiceFunction as AssistantToolChoiceFunction, + type AssistantToolChoiceOption as AssistantToolChoiceOption, + type Thread as Thread, + type ThreadDeleted as ThreadDeleted, + type ThreadCreateParams as ThreadCreateParams, + type ThreadUpdateParams as ThreadUpdateParams, + type ThreadCreateAndRunParams as ThreadCreateAndRunParams, + type ThreadCreateAndRunParamsNonStreaming as ThreadCreateAndRunParamsNonStreaming, + type ThreadCreateAndRunParamsStreaming as ThreadCreateAndRunParamsStreaming, + type ThreadCreateAndRunPollParams, + type ThreadCreateAndRunStreamParams, + }; + + export { + Runs as Runs, + type RequiredActionFunctionToolCall as RequiredActionFunctionToolCall, + type Run as Run, + type RunStatus as RunStatus, + type RunsPage as RunsPage, + type RunCreateParams as RunCreateParams, + type RunCreateParamsNonStreaming as RunCreateParamsNonStreaming, + type RunCreateParamsStreaming as RunCreateParamsStreaming, + type RunRetrieveParams as RunRetrieveParams, + type RunUpdateParams as RunUpdateParams, + type RunListParams as RunListParams, + type RunCancelParams as RunCancelParams, + type RunCreateAndPollParams, + type RunCreateAndStreamParams, + type RunStreamParams, + type RunSubmitToolOutputsParams as RunSubmitToolOutputsParams, + type RunSubmitToolOutputsParamsNonStreaming as RunSubmitToolOutputsParamsNonStreaming, + type RunSubmitToolOutputsParamsStreaming as RunSubmitToolOutputsParamsStreaming, + type RunSubmitToolOutputsAndPollParams, + type RunSubmitToolOutputsStreamParams, + }; + + export { + Messages as Messages, + type Annotation as Annotation, + type AnnotationDelta as AnnotationDelta, + type FileCitationAnnotation as FileCitationAnnotation, + type FileCitationDeltaAnnotation as FileCitationDeltaAnnotation, + type FilePathAnnotation as FilePathAnnotation, + type FilePathDeltaAnnotation as FilePathDeltaAnnotation, + type ImageFile as ImageFile, + type ImageFileContentBlock as ImageFileContentBlock, + type ImageFileDelta as ImageFileDelta, + type ImageFileDeltaBlock as ImageFileDeltaBlock, + type ImageURL as ImageURL, + type ImageURLContentBlock as ImageURLContentBlock, + type ImageURLDelta as ImageURLDelta, + type ImageURLDeltaBlock as ImageURLDeltaBlock, + type MessagesAPIMessage as Message, + type MessageContent as MessageContent, + type MessageContentDelta as MessageContentDelta, + type MessageContentPartParam as MessageContentPartParam, + type MessageDeleted as MessageDeleted, + type MessageDelta as MessageDelta, + type MessageDeltaEvent as MessageDeltaEvent, + type RefusalContentBlock as RefusalContentBlock, + type RefusalDeltaBlock as RefusalDeltaBlock, + type Text as Text, + type TextContentBlock as TextContentBlock, + type TextContentBlockParam as TextContentBlockParam, + type TextDelta as TextDelta, + type TextDeltaBlock as TextDeltaBlock, + type MessagesPage as MessagesPage, + type MessageCreateParams as MessageCreateParams, + type MessageRetrieveParams as MessageRetrieveParams, + type MessageUpdateParams as MessageUpdateParams, + type MessageListParams as MessageListParams, + type MessageDeleteParams as MessageDeleteParams, + }; + + export { AssistantStream }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/chat.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/chat.ts new file mode 100644 index 0000000000000000000000000000000000000000..b3dd87a90bf6f4b85c71368f92103789094597be --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/chat.ts @@ -0,0 +1,3 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export * from './chat/index'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/chat/chat.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/chat/chat.ts new file mode 100644 index 0000000000000000000000000000000000000000..e770d9ecda213eab818adbb6a39e018291f7e2a2 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/chat/chat.ts @@ -0,0 +1,110 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../core/resource'; +import * as Shared from '../shared'; +import * as CompletionsAPI from './completions/completions'; +import { + ChatCompletion, + ChatCompletionAllowedToolChoice, + ChatCompletionAllowedTools, + ChatCompletionAssistantMessageParam, + ChatCompletionAudio, + ChatCompletionAudioParam, + ChatCompletionChunk, + ChatCompletionContentPart, + ChatCompletionContentPartImage, + ChatCompletionContentPartInputAudio, + ChatCompletionContentPartRefusal, + ChatCompletionContentPartText, + ChatCompletionCreateParams, + ChatCompletionCreateParamsNonStreaming, + ChatCompletionCreateParamsStreaming, + ChatCompletionCustomTool, + ChatCompletionDeleted, + ChatCompletionDeveloperMessageParam, + ChatCompletionFunctionCallOption, + ChatCompletionFunctionMessageParam, + ChatCompletionFunctionTool, + ChatCompletionListParams, + ChatCompletionMessage, + ChatCompletionMessageCustomToolCall, + ChatCompletionMessageFunctionToolCall, + ChatCompletionMessageParam, + ChatCompletionMessageToolCall, + ChatCompletionModality, + ChatCompletionNamedToolChoice, + ChatCompletionNamedToolChoiceCustom, + ChatCompletionPredictionContent, + ChatCompletionReasoningEffort, + ChatCompletionRole, + ChatCompletionStoreMessage, + ChatCompletionStreamOptions, + ChatCompletionSystemMessageParam, + ChatCompletionTokenLogprob, + ChatCompletionTool, + ChatCompletionToolChoiceOption, + ChatCompletionToolMessageParam, + ChatCompletionUpdateParams, + ChatCompletionUserMessageParam, + ChatCompletionsPage, + Completions, +} from './completions/completions'; + +export class Chat extends APIResource { + completions: CompletionsAPI.Completions = new CompletionsAPI.Completions(this._client); +} + +export type ChatModel = Shared.ChatModel; + +Chat.Completions = Completions; + +export declare namespace Chat { + export { type ChatModel as ChatModel }; + + export { + Completions as Completions, + type ChatCompletion as ChatCompletion, + type ChatCompletionAllowedToolChoice as ChatCompletionAllowedToolChoice, + type ChatCompletionAssistantMessageParam as ChatCompletionAssistantMessageParam, + type ChatCompletionAudio as ChatCompletionAudio, + type ChatCompletionAudioParam as ChatCompletionAudioParam, + type ChatCompletionChunk as ChatCompletionChunk, + type ChatCompletionContentPart as ChatCompletionContentPart, + type ChatCompletionContentPartImage as ChatCompletionContentPartImage, + type ChatCompletionContentPartInputAudio as ChatCompletionContentPartInputAudio, + type ChatCompletionContentPartRefusal as ChatCompletionContentPartRefusal, + type ChatCompletionContentPartText as ChatCompletionContentPartText, + type ChatCompletionCustomTool as ChatCompletionCustomTool, + type ChatCompletionDeleted as ChatCompletionDeleted, + type ChatCompletionDeveloperMessageParam as ChatCompletionDeveloperMessageParam, + type ChatCompletionFunctionCallOption as ChatCompletionFunctionCallOption, + type ChatCompletionFunctionMessageParam as ChatCompletionFunctionMessageParam, + type ChatCompletionFunctionTool as ChatCompletionFunctionTool, + type ChatCompletionMessage as ChatCompletionMessage, + type ChatCompletionMessageCustomToolCall as ChatCompletionMessageCustomToolCall, + type ChatCompletionMessageFunctionToolCall as ChatCompletionMessageFunctionToolCall, + type ChatCompletionMessageParam as ChatCompletionMessageParam, + type ChatCompletionMessageToolCall as ChatCompletionMessageToolCall, + type ChatCompletionModality as ChatCompletionModality, + type ChatCompletionNamedToolChoice as ChatCompletionNamedToolChoice, + type ChatCompletionNamedToolChoiceCustom as ChatCompletionNamedToolChoiceCustom, + type ChatCompletionPredictionContent as ChatCompletionPredictionContent, + type ChatCompletionRole as ChatCompletionRole, + type ChatCompletionStoreMessage as ChatCompletionStoreMessage, + type ChatCompletionStreamOptions as ChatCompletionStreamOptions, + type ChatCompletionSystemMessageParam as ChatCompletionSystemMessageParam, + type ChatCompletionTokenLogprob as ChatCompletionTokenLogprob, + type ChatCompletionTool as ChatCompletionTool, + type ChatCompletionToolChoiceOption as ChatCompletionToolChoiceOption, + type ChatCompletionToolMessageParam as ChatCompletionToolMessageParam, + type ChatCompletionUserMessageParam as ChatCompletionUserMessageParam, + type ChatCompletionAllowedTools as ChatCompletionAllowedTools, + type ChatCompletionReasoningEffort as ChatCompletionReasoningEffort, + type ChatCompletionsPage as ChatCompletionsPage, + type ChatCompletionCreateParams as ChatCompletionCreateParams, + type ChatCompletionCreateParamsNonStreaming as ChatCompletionCreateParamsNonStreaming, + type ChatCompletionCreateParamsStreaming as ChatCompletionCreateParamsStreaming, + type ChatCompletionUpdateParams as ChatCompletionUpdateParams, + type ChatCompletionListParams as ChatCompletionListParams, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/chat/completions.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/chat/completions.ts new file mode 100644 index 0000000000000000000000000000000000000000..fe7033a9492317be00f59e52f2e78ee5b8d8a9bc --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/chat/completions.ts @@ -0,0 +1,3 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export * from './completions/index'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/chat/completions/completions.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/chat/completions/completions.ts new file mode 100644 index 0000000000000000000000000000000000000000..a71e574e9e41cfc9f67ab05229c2f1676cd9d584 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/chat/completions/completions.ts @@ -0,0 +1,2006 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../../core/resource'; +import * as CompletionsCompletionsAPI from './completions'; +import * as CompletionsAPI from '../../completions'; +import * as Shared from '../../shared'; +import * as MessagesAPI from './messages'; +import { MessageListParams, Messages } from './messages'; +import { APIPromise } from '../../../core/api-promise'; +import { CursorPage, type CursorPageParams, PagePromise } from '../../../core/pagination'; +import { Stream } from '../../../core/streaming'; +import { RequestOptions } from '../../../internal/request-options'; +import { path } from '../../../internal/utils/path'; + +import { ChatCompletionRunner } from '../../../lib/ChatCompletionRunner'; +import { ChatCompletionStreamingRunner } from '../../../lib/ChatCompletionStreamingRunner'; +import { RunnerOptions } from '../../../lib/AbstractChatCompletionRunner'; +import { ChatCompletionToolRunnerParams } from '../../../lib/ChatCompletionRunner'; +import { ChatCompletionStreamingToolRunnerParams } from '../../../lib/ChatCompletionStreamingRunner'; +import { ChatCompletionStream, type ChatCompletionStreamParams } from '../../../lib/ChatCompletionStream'; +import { ExtractParsedContentFromParams, parseChatCompletion, validateInputTools } from '../../../lib/parser'; + +export class Completions extends APIResource { + messages: MessagesAPI.Messages = new MessagesAPI.Messages(this._client); + + /** + * **Starting a new project?** We recommend trying + * [Responses](https://platform.openai.com/docs/api-reference/responses) to take + * advantage of the latest OpenAI platform features. Compare + * [Chat Completions with Responses](https://platform.openai.com/docs/guides/responses-vs-chat-completions?api-mode=responses). + * + * --- + * + * Creates a model response for the given chat conversation. Learn more in the + * [text generation](https://platform.openai.com/docs/guides/text-generation), + * [vision](https://platform.openai.com/docs/guides/vision), and + * [audio](https://platform.openai.com/docs/guides/audio) guides. + * + * Parameter support can differ depending on the model used to generate the + * response, particularly for newer reasoning models. Parameters that are only + * supported for reasoning models are noted below. For the current state of + * unsupported parameters in reasoning models, + * [refer to the reasoning guide](https://platform.openai.com/docs/guides/reasoning). + * + * @example + * ```ts + * const chatCompletion = await client.chat.completions.create( + * { + * messages: [{ content: 'string', role: 'developer' }], + * model: 'gpt-4o', + * }, + * ); + * ``` + */ + create(body: ChatCompletionCreateParamsNonStreaming, options?: RequestOptions): APIPromise; + create( + body: ChatCompletionCreateParamsStreaming, + options?: RequestOptions, + ): APIPromise>; + create( + body: ChatCompletionCreateParamsBase, + options?: RequestOptions, + ): APIPromise | ChatCompletion>; + create( + body: ChatCompletionCreateParams, + options?: RequestOptions, + ): APIPromise | APIPromise> { + return this._client.post('/chat/completions', { body, ...options, stream: body.stream ?? false }) as + | APIPromise + | APIPromise>; + } + + /** + * Get a stored chat completion. Only Chat Completions that have been created with + * the `store` parameter set to `true` will be returned. + * + * @example + * ```ts + * const chatCompletion = + * await client.chat.completions.retrieve('completion_id'); + * ``` + */ + retrieve(completionID: string, options?: RequestOptions): APIPromise { + return this._client.get(path`/chat/completions/${completionID}`, options); + } + + /** + * Modify a stored chat completion. Only Chat Completions that have been created + * with the `store` parameter set to `true` can be modified. Currently, the only + * supported modification is to update the `metadata` field. + * + * @example + * ```ts + * const chatCompletion = await client.chat.completions.update( + * 'completion_id', + * { metadata: { foo: 'string' } }, + * ); + * ``` + */ + update( + completionID: string, + body: ChatCompletionUpdateParams, + options?: RequestOptions, + ): APIPromise { + return this._client.post(path`/chat/completions/${completionID}`, { body, ...options }); + } + + /** + * List stored Chat Completions. Only Chat Completions that have been stored with + * the `store` parameter set to `true` will be returned. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const chatCompletion of client.chat.completions.list()) { + * // ... + * } + * ``` + */ + list( + query: ChatCompletionListParams | null | undefined = {}, + options?: RequestOptions, + ): PagePromise { + return this._client.getAPIList('/chat/completions', CursorPage, { query, ...options }); + } + + /** + * Delete a stored chat completion. Only Chat Completions that have been created + * with the `store` parameter set to `true` can be deleted. + * + * @example + * ```ts + * const chatCompletionDeleted = + * await client.chat.completions.delete('completion_id'); + * ``` + */ + delete(completionID: string, options?: RequestOptions): APIPromise { + return this._client.delete(path`/chat/completions/${completionID}`, options); + } + + parse>( + body: Params, + options?: RequestOptions, + ): APIPromise> { + validateInputTools(body.tools); + + return this._client.chat.completions + .create(body, { + ...options, + headers: { + ...options?.headers, + 'X-Stainless-Helper-Method': 'chat.completions.parse', + }, + }) + ._thenUnwrap((completion) => parseChatCompletion(completion, body)); + } + + /** + * A convenience helper for using tool calls with the /chat/completions endpoint + * which automatically calls the JavaScript functions you provide and sends their + * results back to the /chat/completions endpoint, looping as long as the model + * requests function calls. + * + * For more details and examples, see + * [the docs](https://github.com/openai/openai-node#automated-function-calls) + */ + runTools< + Params extends ChatCompletionToolRunnerParams, + ParsedT = ExtractParsedContentFromParams, + >(body: Params, options?: RunnerOptions): ChatCompletionRunner; + + runTools< + Params extends ChatCompletionStreamingToolRunnerParams, + ParsedT = ExtractParsedContentFromParams, + >(body: Params, options?: RunnerOptions): ChatCompletionStreamingRunner; + + runTools< + Params extends ChatCompletionToolRunnerParams | ChatCompletionStreamingToolRunnerParams, + ParsedT = ExtractParsedContentFromParams, + >( + body: Params, + options?: RunnerOptions, + ): ChatCompletionRunner | ChatCompletionStreamingRunner { + if (body.stream) { + return ChatCompletionStreamingRunner.runTools( + this._client, + body as ChatCompletionStreamingToolRunnerParams, + options, + ); + } + + return ChatCompletionRunner.runTools(this._client, body as ChatCompletionToolRunnerParams, options); + } + + /** + * Creates a chat completion stream + */ + stream>( + body: Params, + options?: RequestOptions, + ): ChatCompletionStream { + return ChatCompletionStream.createChatCompletion(this._client, body, options); + } +} + +export interface ParsedFunction extends ChatCompletionMessageFunctionToolCall.Function { + parsed_arguments?: unknown; +} + +export interface ParsedFunctionToolCall extends ChatCompletionMessageFunctionToolCall { + function: ParsedFunction; +} + +export interface ParsedChatCompletionMessage extends ChatCompletionMessage { + parsed: ParsedT | null; + tool_calls?: Array; +} + +export interface ParsedChoice extends ChatCompletion.Choice { + message: ParsedChatCompletionMessage; +} + +export interface ParsedChatCompletion extends ChatCompletion { + choices: Array>; +} + +export type ChatCompletionParseParams = ChatCompletionCreateParamsNonStreaming; + +export { ChatCompletionStreamingRunner } from '../../../lib/ChatCompletionStreamingRunner'; +export { + type RunnableFunctionWithParse, + type RunnableFunctionWithoutParse, + ParsingToolFunction, +} from '../../../lib/RunnableFunction'; +export { type ChatCompletionToolRunnerParams } from '../../../lib/ChatCompletionRunner'; +export { type ChatCompletionStreamingToolRunnerParams } from '../../../lib/ChatCompletionStreamingRunner'; +export { ChatCompletionStream, type ChatCompletionStreamParams } from '../../../lib/ChatCompletionStream'; +export { ChatCompletionRunner } from '../../../lib/ChatCompletionRunner'; + +export type ChatCompletionsPage = CursorPage; + +export type ChatCompletionStoreMessagesPage = CursorPage; + +/** + * Represents a chat completion response returned by model, based on the provided + * input. + */ +export interface ChatCompletion { + /** + * A unique identifier for the chat completion. + */ + id: string; + + /** + * A list of chat completion choices. Can be more than one if `n` is greater + * than 1. + */ + choices: Array; + + /** + * The Unix timestamp (in seconds) of when the chat completion was created. + */ + created: number; + + /** + * The model used for the chat completion. + */ + model: string; + + /** + * The object type, which is always `chat.completion`. + */ + object: 'chat.completion'; + + /** + * Specifies the processing type used for serving the request. + * + * - If set to 'auto', then the request will be processed with the service tier + * configured in the Project settings. Unless otherwise configured, the Project + * will use 'default'. + * - If set to 'default', then the request will be processed with the standard + * pricing and performance for the selected model. + * - If set to '[flex](https://platform.openai.com/docs/guides/flex-processing)' or + * '[priority](https://openai.com/api-priority-processing/)', then the request + * will be processed with the corresponding service tier. + * - When not set, the default behavior is 'auto'. + * + * When the `service_tier` parameter is set, the response body will include the + * `service_tier` value based on the processing mode actually used to serve the + * request. This response value may be different from the value set in the + * parameter. + */ + service_tier?: 'auto' | 'default' | 'flex' | 'scale' | 'priority' | null; + + /** + * @deprecated This fingerprint represents the backend configuration that the model + * runs with. + * + * Can be used in conjunction with the `seed` request parameter to understand when + * backend changes have been made that might impact determinism. + */ + system_fingerprint?: string; + + /** + * Usage statistics for the completion request. + */ + usage?: CompletionsAPI.CompletionUsage; +} + +export namespace ChatCompletion { + export interface Choice { + /** + * The reason the model stopped generating tokens. This will be `stop` if the model + * hit a natural stop point or a provided stop sequence, `length` if the maximum + * number of tokens specified in the request was reached, `content_filter` if + * content was omitted due to a flag from our content filters, `tool_calls` if the + * model called a tool, or `function_call` (deprecated) if the model called a + * function. + */ + finish_reason: 'stop' | 'length' | 'tool_calls' | 'content_filter' | 'function_call'; + + /** + * The index of the choice in the list of choices. + */ + index: number; + + /** + * Log probability information for the choice. + */ + logprobs: Choice.Logprobs | null; + + /** + * A chat completion message generated by the model. + */ + message: CompletionsCompletionsAPI.ChatCompletionMessage; + } + + export namespace Choice { + /** + * Log probability information for the choice. + */ + export interface Logprobs { + /** + * A list of message content tokens with log probability information. + */ + content: Array | null; + + /** + * A list of message refusal tokens with log probability information. + */ + refusal: Array | null; + } + } +} + +/** + * Constrains the tools available to the model to a pre-defined set. + */ +export interface ChatCompletionAllowedToolChoice { + /** + * Constrains the tools available to the model to a pre-defined set. + */ + allowed_tools: ChatCompletionAllowedTools; + + /** + * Allowed tool configuration type. Always `allowed_tools`. + */ + type: 'allowed_tools'; +} + +/** + * Messages sent by the model in response to user messages. + */ +export interface ChatCompletionAssistantMessageParam { + /** + * The role of the messages author, in this case `assistant`. + */ + role: 'assistant'; + + /** + * Data about a previous audio response from the model. + * [Learn more](https://platform.openai.com/docs/guides/audio). + */ + audio?: ChatCompletionAssistantMessageParam.Audio | null; + + /** + * The contents of the assistant message. Required unless `tool_calls` or + * `function_call` is specified. + */ + content?: string | Array | null; + + /** + * @deprecated Deprecated and replaced by `tool_calls`. The name and arguments of a + * function that should be called, as generated by the model. + */ + function_call?: ChatCompletionAssistantMessageParam.FunctionCall | null; + + /** + * An optional name for the participant. Provides the model information to + * differentiate between participants of the same role. + */ + name?: string; + + /** + * The refusal message by the assistant. + */ + refusal?: string | null; + + /** + * The tool calls generated by the model, such as function calls. + */ + tool_calls?: Array; +} + +export namespace ChatCompletionAssistantMessageParam { + /** + * Data about a previous audio response from the model. + * [Learn more](https://platform.openai.com/docs/guides/audio). + */ + export interface Audio { + /** + * Unique identifier for a previous audio response from the model. + */ + id: string; + } + + /** + * @deprecated Deprecated and replaced by `tool_calls`. The name and arguments of a + * function that should be called, as generated by the model. + */ + export interface FunctionCall { + /** + * The arguments to call the function with, as generated by the model in JSON + * format. Note that the model does not always generate valid JSON, and may + * hallucinate parameters not defined by your function schema. Validate the + * arguments in your code before calling your function. + */ + arguments: string; + + /** + * The name of the function to call. + */ + name: string; + } +} + +/** + * If the audio output modality is requested, this object contains data about the + * audio response from the model. + * [Learn more](https://platform.openai.com/docs/guides/audio). + */ +export interface ChatCompletionAudio { + /** + * Unique identifier for this audio response. + */ + id: string; + + /** + * Base64 encoded audio bytes generated by the model, in the format specified in + * the request. + */ + data: string; + + /** + * The Unix timestamp (in seconds) for when this audio response will no longer be + * accessible on the server for use in multi-turn conversations. + */ + expires_at: number; + + /** + * Transcript of the audio generated by the model. + */ + transcript: string; +} + +/** + * Parameters for audio output. Required when audio output is requested with + * `modalities: ["audio"]`. + * [Learn more](https://platform.openai.com/docs/guides/audio). + */ +export interface ChatCompletionAudioParam { + /** + * Specifies the output audio format. Must be one of `wav`, `mp3`, `flac`, `opus`, + * or `pcm16`. + */ + format: 'wav' | 'aac' | 'mp3' | 'flac' | 'opus' | 'pcm16'; + + /** + * The voice the model uses to respond. Supported voices are `alloy`, `ash`, + * `ballad`, `coral`, `echo`, `fable`, `nova`, `onyx`, `sage`, and `shimmer`. + */ + voice: (string & {}) | 'alloy' | 'ash' | 'ballad' | 'coral' | 'echo' | 'sage' | 'shimmer' | 'verse'; +} + +/** + * Represents a streamed chunk of a chat completion response returned by the model, + * based on the provided input. + * [Learn more](https://platform.openai.com/docs/guides/streaming-responses). + */ +export interface ChatCompletionChunk { + /** + * A unique identifier for the chat completion. Each chunk has the same ID. + */ + id: string; + + /** + * A list of chat completion choices. Can contain more than one elements if `n` is + * greater than 1. Can also be empty for the last chunk if you set + * `stream_options: {"include_usage": true}`. + */ + choices: Array; + + /** + * The Unix timestamp (in seconds) of when the chat completion was created. Each + * chunk has the same timestamp. + */ + created: number; + + /** + * The model to generate the completion. + */ + model: string; + + /** + * The object type, which is always `chat.completion.chunk`. + */ + object: 'chat.completion.chunk'; + + /** + * Specifies the processing type used for serving the request. + * + * - If set to 'auto', then the request will be processed with the service tier + * configured in the Project settings. Unless otherwise configured, the Project + * will use 'default'. + * - If set to 'default', then the request will be processed with the standard + * pricing and performance for the selected model. + * - If set to '[flex](https://platform.openai.com/docs/guides/flex-processing)' or + * '[priority](https://openai.com/api-priority-processing/)', then the request + * will be processed with the corresponding service tier. + * - When not set, the default behavior is 'auto'. + * + * When the `service_tier` parameter is set, the response body will include the + * `service_tier` value based on the processing mode actually used to serve the + * request. This response value may be different from the value set in the + * parameter. + */ + service_tier?: 'auto' | 'default' | 'flex' | 'scale' | 'priority' | null; + + /** + * @deprecated This fingerprint represents the backend configuration that the model + * runs with. Can be used in conjunction with the `seed` request parameter to + * understand when backend changes have been made that might impact determinism. + */ + system_fingerprint?: string; + + /** + * An optional field that will only be present when you set + * `stream_options: {"include_usage": true}` in your request. When present, it + * contains a null value **except for the last chunk** which contains the token + * usage statistics for the entire request. + * + * **NOTE:** If the stream is interrupted or cancelled, you may not receive the + * final usage chunk which contains the total token usage for the request. + */ + usage?: CompletionsAPI.CompletionUsage | null; +} + +export namespace ChatCompletionChunk { + export interface Choice { + /** + * A chat completion delta generated by streamed model responses. + */ + delta: Choice.Delta; + + /** + * The reason the model stopped generating tokens. This will be `stop` if the model + * hit a natural stop point or a provided stop sequence, `length` if the maximum + * number of tokens specified in the request was reached, `content_filter` if + * content was omitted due to a flag from our content filters, `tool_calls` if the + * model called a tool, or `function_call` (deprecated) if the model called a + * function. + */ + finish_reason: 'stop' | 'length' | 'tool_calls' | 'content_filter' | 'function_call' | null; + + /** + * The index of the choice in the list of choices. + */ + index: number; + + /** + * Log probability information for the choice. + */ + logprobs?: Choice.Logprobs | null; + } + + export namespace Choice { + /** + * A chat completion delta generated by streamed model responses. + */ + export interface Delta { + /** + * The contents of the chunk message. + */ + content?: string | null; + + /** + * @deprecated Deprecated and replaced by `tool_calls`. The name and arguments of a + * function that should be called, as generated by the model. + */ + function_call?: Delta.FunctionCall; + + /** + * The refusal message generated by the model. + */ + refusal?: string | null; + + /** + * The role of the author of this message. + */ + role?: 'developer' | 'system' | 'user' | 'assistant' | 'tool'; + + tool_calls?: Array; + } + + export namespace Delta { + /** + * @deprecated Deprecated and replaced by `tool_calls`. The name and arguments of a + * function that should be called, as generated by the model. + */ + export interface FunctionCall { + /** + * The arguments to call the function with, as generated by the model in JSON + * format. Note that the model does not always generate valid JSON, and may + * hallucinate parameters not defined by your function schema. Validate the + * arguments in your code before calling your function. + */ + arguments?: string; + + /** + * The name of the function to call. + */ + name?: string; + } + + export interface ToolCall { + index: number; + + /** + * The ID of the tool call. + */ + id?: string; + + function?: ToolCall.Function; + + /** + * The type of the tool. Currently, only `function` is supported. + */ + type?: 'function'; + } + + export namespace ToolCall { + export interface Function { + /** + * The arguments to call the function with, as generated by the model in JSON + * format. Note that the model does not always generate valid JSON, and may + * hallucinate parameters not defined by your function schema. Validate the + * arguments in your code before calling your function. + */ + arguments?: string; + + /** + * The name of the function to call. + */ + name?: string; + } + } + } + + /** + * Log probability information for the choice. + */ + export interface Logprobs { + /** + * A list of message content tokens with log probability information. + */ + content: Array | null; + + /** + * A list of message refusal tokens with log probability information. + */ + refusal: Array | null; + } + } +} + +/** + * Learn about + * [text inputs](https://platform.openai.com/docs/guides/text-generation). + */ +export type ChatCompletionContentPart = + | ChatCompletionContentPartText + | ChatCompletionContentPartImage + | ChatCompletionContentPartInputAudio + | ChatCompletionContentPart.File; + +export namespace ChatCompletionContentPart { + /** + * Learn about [file inputs](https://platform.openai.com/docs/guides/text) for text + * generation. + */ + export interface File { + file: File.File; + + /** + * The type of the content part. Always `file`. + */ + type: 'file'; + } + + export namespace File { + export interface File { + /** + * The base64 encoded file data, used when passing the file to the model as a + * string. + */ + file_data?: string; + + /** + * The ID of an uploaded file to use as input. + */ + file_id?: string; + + /** + * The name of the file, used when passing the file to the model as a string. + */ + filename?: string; + } + } +} + +/** + * Learn about [image inputs](https://platform.openai.com/docs/guides/vision). + */ +export interface ChatCompletionContentPartImage { + image_url: ChatCompletionContentPartImage.ImageURL; + + /** + * The type of the content part. + */ + type: 'image_url'; +} + +export namespace ChatCompletionContentPartImage { + export interface ImageURL { + /** + * Either a URL of the image or the base64 encoded image data. + */ + url: string; + + /** + * Specifies the detail level of the image. Learn more in the + * [Vision guide](https://platform.openai.com/docs/guides/vision#low-or-high-fidelity-image-understanding). + */ + detail?: 'auto' | 'low' | 'high'; + } +} + +/** + * Learn about [audio inputs](https://platform.openai.com/docs/guides/audio). + */ +export interface ChatCompletionContentPartInputAudio { + input_audio: ChatCompletionContentPartInputAudio.InputAudio; + + /** + * The type of the content part. Always `input_audio`. + */ + type: 'input_audio'; +} + +export namespace ChatCompletionContentPartInputAudio { + export interface InputAudio { + /** + * Base64 encoded audio data. + */ + data: string; + + /** + * The format of the encoded audio data. Currently supports "wav" and "mp3". + */ + format: 'wav' | 'mp3'; + } +} + +export interface ChatCompletionContentPartRefusal { + /** + * The refusal message generated by the model. + */ + refusal: string; + + /** + * The type of the content part. + */ + type: 'refusal'; +} + +/** + * Learn about + * [text inputs](https://platform.openai.com/docs/guides/text-generation). + */ +export interface ChatCompletionContentPartText { + /** + * The text content. + */ + text: string; + + /** + * The type of the content part. + */ + type: 'text'; +} + +/** + * A custom tool that processes input using a specified format. + */ +export interface ChatCompletionCustomTool { + /** + * Properties of the custom tool. + */ + custom: ChatCompletionCustomTool.Custom; + + /** + * The type of the custom tool. Always `custom`. + */ + type: 'custom'; +} + +export namespace ChatCompletionCustomTool { + /** + * Properties of the custom tool. + */ + export interface Custom { + /** + * The name of the custom tool, used to identify it in tool calls. + */ + name: string; + + /** + * Optional description of the custom tool, used to provide more context. + */ + description?: string; + + /** + * The input format for the custom tool. Default is unconstrained text. + */ + format?: Custom.Text | Custom.Grammar; + } + + export namespace Custom { + /** + * Unconstrained free-form text. + */ + export interface Text { + /** + * Unconstrained text format. Always `text`. + */ + type: 'text'; + } + + /** + * A grammar defined by the user. + */ + export interface Grammar { + /** + * Your chosen grammar. + */ + grammar: Grammar.Grammar; + + /** + * Grammar format. Always `grammar`. + */ + type: 'grammar'; + } + + export namespace Grammar { + /** + * Your chosen grammar. + */ + export interface Grammar { + /** + * The grammar definition. + */ + definition: string; + + /** + * The syntax of the grammar definition. One of `lark` or `regex`. + */ + syntax: 'lark' | 'regex'; + } + } + } +} + +export interface ChatCompletionDeleted { + /** + * The ID of the chat completion that was deleted. + */ + id: string; + + /** + * Whether the chat completion was deleted. + */ + deleted: boolean; + + /** + * The type of object being deleted. + */ + object: 'chat.completion.deleted'; +} + +/** + * Developer-provided instructions that the model should follow, regardless of + * messages sent by the user. With o1 models and newer, `developer` messages + * replace the previous `system` messages. + */ +export interface ChatCompletionDeveloperMessageParam { + /** + * The contents of the developer message. + */ + content: string | Array; + + /** + * The role of the messages author, in this case `developer`. + */ + role: 'developer'; + + /** + * An optional name for the participant. Provides the model information to + * differentiate between participants of the same role. + */ + name?: string; +} + +/** + * Specifying a particular function via `{"name": "my_function"}` forces the model + * to call that function. + */ +export interface ChatCompletionFunctionCallOption { + /** + * The name of the function to call. + */ + name: string; +} + +/** + * @deprecated + */ +export interface ChatCompletionFunctionMessageParam { + /** + * The contents of the function message. + */ + content: string | null; + + /** + * The name of the function to call. + */ + name: string; + + /** + * The role of the messages author, in this case `function`. + */ + role: 'function'; +} + +/** + * A function tool that can be used to generate a response. + */ +export interface ChatCompletionFunctionTool { + function: Shared.FunctionDefinition; + + /** + * The type of the tool. Currently, only `function` is supported. + */ + type: 'function'; +} + +/** + * A chat completion message generated by the model. + */ +export interface ChatCompletionMessage { + /** + * The contents of the message. + */ + content: string | null; + + /** + * The refusal message generated by the model. + */ + refusal: string | null; + + /** + * The role of the author of this message. + */ + role: 'assistant'; + + /** + * Annotations for the message, when applicable, as when using the + * [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat). + */ + annotations?: Array; + + /** + * If the audio output modality is requested, this object contains data about the + * audio response from the model. + * [Learn more](https://platform.openai.com/docs/guides/audio). + */ + audio?: ChatCompletionAudio | null; + + /** + * @deprecated Deprecated and replaced by `tool_calls`. The name and arguments of a + * function that should be called, as generated by the model. + */ + function_call?: ChatCompletionMessage.FunctionCall | null; + + /** + * The tool calls generated by the model, such as function calls. + */ + tool_calls?: Array; +} + +export namespace ChatCompletionMessage { + /** + * A URL citation when using web search. + */ + export interface Annotation { + /** + * The type of the URL citation. Always `url_citation`. + */ + type: 'url_citation'; + + /** + * A URL citation when using web search. + */ + url_citation: Annotation.URLCitation; + } + + export namespace Annotation { + /** + * A URL citation when using web search. + */ + export interface URLCitation { + /** + * The index of the last character of the URL citation in the message. + */ + end_index: number; + + /** + * The index of the first character of the URL citation in the message. + */ + start_index: number; + + /** + * The title of the web resource. + */ + title: string; + + /** + * The URL of the web resource. + */ + url: string; + } + } + + /** + * @deprecated Deprecated and replaced by `tool_calls`. The name and arguments of a + * function that should be called, as generated by the model. + */ + export interface FunctionCall { + /** + * The arguments to call the function with, as generated by the model in JSON + * format. Note that the model does not always generate valid JSON, and may + * hallucinate parameters not defined by your function schema. Validate the + * arguments in your code before calling your function. + */ + arguments: string; + + /** + * The name of the function to call. + */ + name: string; + } +} + +/** + * A call to a custom tool created by the model. + */ +export interface ChatCompletionMessageCustomToolCall { + /** + * The ID of the tool call. + */ + id: string; + + /** + * The custom tool that the model called. + */ + custom: ChatCompletionMessageCustomToolCall.Custom; + + /** + * The type of the tool. Always `custom`. + */ + type: 'custom'; +} + +export namespace ChatCompletionMessageCustomToolCall { + /** + * The custom tool that the model called. + */ + export interface Custom { + /** + * The input for the custom tool call generated by the model. + */ + input: string; + + /** + * The name of the custom tool to call. + */ + name: string; + } +} + +/** + * A call to a function tool created by the model. + */ +export interface ChatCompletionMessageFunctionToolCall { + /** + * The ID of the tool call. + */ + id: string; + + /** + * The function that the model called. + */ + function: ChatCompletionMessageFunctionToolCall.Function; + + /** + * The type of the tool. Currently, only `function` is supported. + */ + type: 'function'; +} + +export namespace ChatCompletionMessageFunctionToolCall { + /** + * The function that the model called. + */ + export interface Function { + /** + * The arguments to call the function with, as generated by the model in JSON + * format. Note that the model does not always generate valid JSON, and may + * hallucinate parameters not defined by your function schema. Validate the + * arguments in your code before calling your function. + */ + arguments: string; + + /** + * The name of the function to call. + */ + name: string; + } +} + +/** + * Developer-provided instructions that the model should follow, regardless of + * messages sent by the user. With o1 models and newer, `developer` messages + * replace the previous `system` messages. + */ +export type ChatCompletionMessageParam = + | ChatCompletionDeveloperMessageParam + | ChatCompletionSystemMessageParam + | ChatCompletionUserMessageParam + | ChatCompletionAssistantMessageParam + | ChatCompletionToolMessageParam + | ChatCompletionFunctionMessageParam; + +/** + * A call to a function tool created by the model. + */ +export type ChatCompletionMessageToolCall = + | ChatCompletionMessageFunctionToolCall + | ChatCompletionMessageCustomToolCall; + +export type ChatCompletionModality = 'text' | 'audio'; + +/** + * Specifies a tool the model should use. Use to force the model to call a specific + * function. + */ +export interface ChatCompletionNamedToolChoice { + function: ChatCompletionNamedToolChoice.Function; + + /** + * For function calling, the type is always `function`. + */ + type: 'function'; +} + +export namespace ChatCompletionNamedToolChoice { + export interface Function { + /** + * The name of the function to call. + */ + name: string; + } +} + +/** + * Specifies a tool the model should use. Use to force the model to call a specific + * custom tool. + */ +export interface ChatCompletionNamedToolChoiceCustom { + custom: ChatCompletionNamedToolChoiceCustom.Custom; + + /** + * For custom tool calling, the type is always `custom`. + */ + type: 'custom'; +} + +export namespace ChatCompletionNamedToolChoiceCustom { + export interface Custom { + /** + * The name of the custom tool to call. + */ + name: string; + } +} + +/** + * Static predicted output content, such as the content of a text file that is + * being regenerated. + */ +export interface ChatCompletionPredictionContent { + /** + * The content that should be matched when generating a model response. If + * generated tokens would match this content, the entire model response can be + * returned much more quickly. + */ + content: string | Array; + + /** + * The type of the predicted content you want to provide. This type is currently + * always `content`. + */ + type: 'content'; +} + +/** + * The role of the author of a message + */ +export type ChatCompletionRole = 'developer' | 'system' | 'user' | 'assistant' | 'tool' | 'function'; + +/** + * A chat completion message generated by the model. + */ +export interface ChatCompletionStoreMessage extends ChatCompletionMessage { + /** + * The identifier of the chat message. + */ + id: string; + + /** + * If a content parts array was provided, this is an array of `text` and + * `image_url` parts. Otherwise, null. + */ + content_parts?: Array | null; +} + +/** + * Options for streaming response. Only set this when you set `stream: true`. + */ +export interface ChatCompletionStreamOptions { + /** + * When true, stream obfuscation will be enabled. Stream obfuscation adds random + * characters to an `obfuscation` field on streaming delta events to normalize + * payload sizes as a mitigation to certain side-channel attacks. These obfuscation + * fields are included by default, but add a small amount of overhead to the data + * stream. You can set `include_obfuscation` to false to optimize for bandwidth if + * you trust the network links between your application and the OpenAI API. + */ + include_obfuscation?: boolean; + + /** + * If set, an additional chunk will be streamed before the `data: [DONE]` message. + * The `usage` field on this chunk shows the token usage statistics for the entire + * request, and the `choices` field will always be an empty array. + * + * All other chunks will also include a `usage` field, but with a null value. + * **NOTE:** If the stream is interrupted, you may not receive the final usage + * chunk which contains the total token usage for the request. + */ + include_usage?: boolean; +} + +/** + * Developer-provided instructions that the model should follow, regardless of + * messages sent by the user. With o1 models and newer, use `developer` messages + * for this purpose instead. + */ +export interface ChatCompletionSystemMessageParam { + /** + * The contents of the system message. + */ + content: string | Array; + + /** + * The role of the messages author, in this case `system`. + */ + role: 'system'; + + /** + * An optional name for the participant. Provides the model information to + * differentiate between participants of the same role. + */ + name?: string; +} + +export interface ChatCompletionTokenLogprob { + /** + * The token. + */ + token: string; + + /** + * A list of integers representing the UTF-8 bytes representation of the token. + * Useful in instances where characters are represented by multiple tokens and + * their byte representations must be combined to generate the correct text + * representation. Can be `null` if there is no bytes representation for the token. + */ + bytes: Array | null; + + /** + * The log probability of this token, if it is within the top 20 most likely + * tokens. Otherwise, the value `-9999.0` is used to signify that the token is very + * unlikely. + */ + logprob: number; + + /** + * List of the most likely tokens and their log probability, at this token + * position. In rare cases, there may be fewer than the number of requested + * `top_logprobs` returned. + */ + top_logprobs: Array; +} + +export namespace ChatCompletionTokenLogprob { + export interface TopLogprob { + /** + * The token. + */ + token: string; + + /** + * A list of integers representing the UTF-8 bytes representation of the token. + * Useful in instances where characters are represented by multiple tokens and + * their byte representations must be combined to generate the correct text + * representation. Can be `null` if there is no bytes representation for the token. + */ + bytes: Array | null; + + /** + * The log probability of this token, if it is within the top 20 most likely + * tokens. Otherwise, the value `-9999.0` is used to signify that the token is very + * unlikely. + */ + logprob: number; + } +} + +/** + * A function tool that can be used to generate a response. + */ +export type ChatCompletionTool = ChatCompletionFunctionTool | ChatCompletionCustomTool; + +/** + * Controls which (if any) tool is called by the model. `none` means the model will + * not call any tool and instead generates a message. `auto` means the model can + * pick between generating a message or calling one or more tools. `required` means + * the model must call one or more tools. Specifying a particular tool via + * `{"type": "function", "function": {"name": "my_function"}}` forces the model to + * call that tool. + * + * `none` is the default when no tools are present. `auto` is the default if tools + * are present. + */ +export type ChatCompletionToolChoiceOption = + | 'none' + | 'auto' + | 'required' + | ChatCompletionAllowedToolChoice + | ChatCompletionNamedToolChoice + | ChatCompletionNamedToolChoiceCustom; + +export interface ChatCompletionToolMessageParam { + /** + * The contents of the tool message. + */ + content: string | Array; + + /** + * The role of the messages author, in this case `tool`. + */ + role: 'tool'; + + /** + * Tool call that this message is responding to. + */ + tool_call_id: string; +} + +/** + * Messages sent by an end user, containing prompts or additional context + * information. + */ +export interface ChatCompletionUserMessageParam { + /** + * The contents of the user message. + */ + content: string | Array; + + /** + * The role of the messages author, in this case `user`. + */ + role: 'user'; + + /** + * An optional name for the participant. Provides the model information to + * differentiate between participants of the same role. + */ + name?: string; +} + +/** + * Constrains the tools available to the model to a pre-defined set. + */ +export interface ChatCompletionAllowedTools { + /** + * Constrains the tools available to the model to a pre-defined set. + * + * `auto` allows the model to pick from among the allowed tools and generate a + * message. + * + * `required` requires the model to call one or more of the allowed tools. + */ + mode: 'auto' | 'required'; + + /** + * A list of tool definitions that the model should be allowed to call. + * + * For the Chat Completions API, the list of tool definitions might look like: + * + * ```json + * [ + * { "type": "function", "function": { "name": "get_weather" } }, + * { "type": "function", "function": { "name": "get_time" } } + * ] + * ``` + */ + tools: Array<{ [key: string]: unknown }>; +} + +export type ChatCompletionReasoningEffort = Shared.ReasoningEffort | null; + +export type ChatCompletionCreateParams = + | ChatCompletionCreateParamsNonStreaming + | ChatCompletionCreateParamsStreaming; + +export interface ChatCompletionCreateParamsBase { + /** + * A list of messages comprising the conversation so far. Depending on the + * [model](https://platform.openai.com/docs/models) you use, different message + * types (modalities) are supported, like + * [text](https://platform.openai.com/docs/guides/text-generation), + * [images](https://platform.openai.com/docs/guides/vision), and + * [audio](https://platform.openai.com/docs/guides/audio). + */ + messages: Array; + + /** + * Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI offers a + * wide range of models with different capabilities, performance characteristics, + * and price points. Refer to the + * [model guide](https://platform.openai.com/docs/models) to browse and compare + * available models. + */ + model: (string & {}) | Shared.ChatModel; + + /** + * Parameters for audio output. Required when audio output is requested with + * `modalities: ["audio"]`. + * [Learn more](https://platform.openai.com/docs/guides/audio). + */ + audio?: ChatCompletionAudioParam | null; + + /** + * Number between -2.0 and 2.0. Positive values penalize new tokens based on their + * existing frequency in the text so far, decreasing the model's likelihood to + * repeat the same line verbatim. + */ + frequency_penalty?: number | null; + + /** + * @deprecated Deprecated in favor of `tool_choice`. + * + * Controls which (if any) function is called by the model. + * + * `none` means the model will not call a function and instead generates a message. + * + * `auto` means the model can pick between generating a message or calling a + * function. + * + * Specifying a particular function via `{"name": "my_function"}` forces the model + * to call that function. + * + * `none` is the default when no functions are present. `auto` is the default if + * functions are present. + */ + function_call?: 'none' | 'auto' | ChatCompletionFunctionCallOption; + + /** + * @deprecated Deprecated in favor of `tools`. + * + * A list of functions the model may generate JSON inputs for. + */ + functions?: Array; + + /** + * Modify the likelihood of specified tokens appearing in the completion. + * + * Accepts a JSON object that maps tokens (specified by their token ID in the + * tokenizer) to an associated bias value from -100 to 100. Mathematically, the + * bias is added to the logits generated by the model prior to sampling. The exact + * effect will vary per model, but values between -1 and 1 should decrease or + * increase likelihood of selection; values like -100 or 100 should result in a ban + * or exclusive selection of the relevant token. + */ + logit_bias?: { [key: string]: number } | null; + + /** + * Whether to return log probabilities of the output tokens or not. If true, + * returns the log probabilities of each output token returned in the `content` of + * `message`. + */ + logprobs?: boolean | null; + + /** + * An upper bound for the number of tokens that can be generated for a completion, + * including visible output tokens and + * [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). + */ + max_completion_tokens?: number | null; + + /** + * @deprecated The maximum number of [tokens](/tokenizer) that can be generated in + * the chat completion. This value can be used to control + * [costs](https://openai.com/api/pricing/) for text generated via API. + * + * This value is now deprecated in favor of `max_completion_tokens`, and is not + * compatible with + * [o-series models](https://platform.openai.com/docs/guides/reasoning). + */ + max_tokens?: number | null; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; + + /** + * Output types that you would like the model to generate. Most models are capable + * of generating text, which is the default: + * + * `["text"]` + * + * The `gpt-4o-audio-preview` model can also be used to + * [generate audio](https://platform.openai.com/docs/guides/audio). To request that + * this model generate both text and audio responses, you can use: + * + * `["text", "audio"]` + */ + modalities?: Array<'text' | 'audio'> | null; + + /** + * How many chat completion choices to generate for each input message. Note that + * you will be charged based on the number of generated tokens across all of the + * choices. Keep `n` as `1` to minimize costs. + */ + n?: number | null; + + /** + * Whether to enable + * [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) + * during tool use. + */ + parallel_tool_calls?: boolean; + + /** + * Static predicted output content, such as the content of a text file that is + * being regenerated. + */ + prediction?: ChatCompletionPredictionContent | null; + + /** + * Number between -2.0 and 2.0. Positive values penalize new tokens based on + * whether they appear in the text so far, increasing the model's likelihood to + * talk about new topics. + */ + presence_penalty?: number | null; + + /** + * Used by OpenAI to cache responses for similar requests to optimize your cache + * hit rates. Replaces the `user` field. + * [Learn more](https://platform.openai.com/docs/guides/prompt-caching). + */ + prompt_cache_key?: string; + + /** + * Constrains effort on reasoning for + * [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently + * supported values are `minimal`, `low`, `medium`, and `high`. Reducing reasoning + * effort can result in faster responses and fewer tokens used on reasoning in a + * response. + */ + reasoning_effort?: Shared.ReasoningEffort | null; + + /** + * An object specifying the format that the model must output. + * + * Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + * Outputs which ensures the model will match your supplied JSON schema. Learn more + * in the + * [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + * + * Setting to `{ "type": "json_object" }` enables the older JSON mode, which + * ensures the message the model generates is valid JSON. Using `json_schema` is + * preferred for models that support it. + */ + response_format?: + | Shared.ResponseFormatText + | Shared.ResponseFormatJSONSchema + | Shared.ResponseFormatJSONObject; + + /** + * A stable identifier used to help detect users of your application that may be + * violating OpenAI's usage policies. The IDs should be a string that uniquely + * identifies each user. We recommend hashing their username or email address, in + * order to avoid sending us any identifying information. + * [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers). + */ + safety_identifier?: string; + + /** + * @deprecated This feature is in Beta. If specified, our system will make a best + * effort to sample deterministically, such that repeated requests with the same + * `seed` and parameters should return the same result. Determinism is not + * guaranteed, and you should refer to the `system_fingerprint` response parameter + * to monitor changes in the backend. + */ + seed?: number | null; + + /** + * Specifies the processing type used for serving the request. + * + * - If set to 'auto', then the request will be processed with the service tier + * configured in the Project settings. Unless otherwise configured, the Project + * will use 'default'. + * - If set to 'default', then the request will be processed with the standard + * pricing and performance for the selected model. + * - If set to '[flex](https://platform.openai.com/docs/guides/flex-processing)' or + * '[priority](https://openai.com/api-priority-processing/)', then the request + * will be processed with the corresponding service tier. + * - When not set, the default behavior is 'auto'. + * + * When the `service_tier` parameter is set, the response body will include the + * `service_tier` value based on the processing mode actually used to serve the + * request. This response value may be different from the value set in the + * parameter. + */ + service_tier?: 'auto' | 'default' | 'flex' | 'scale' | 'priority' | null; + + /** + * Not supported with latest reasoning models `o3` and `o4-mini`. + * + * Up to 4 sequences where the API will stop generating further tokens. The + * returned text will not contain the stop sequence. + */ + stop?: string | null | Array; + + /** + * Whether or not to store the output of this chat completion request for use in + * our [model distillation](https://platform.openai.com/docs/guides/distillation) + * or [evals](https://platform.openai.com/docs/guides/evals) products. + * + * Supports text and image inputs. Note: image inputs over 8MB will be dropped. + */ + store?: boolean | null; + + /** + * If set to true, the model response data will be streamed to the client as it is + * generated using + * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + * See the + * [Streaming section below](https://platform.openai.com/docs/api-reference/chat/streaming) + * for more information, along with the + * [streaming responses](https://platform.openai.com/docs/guides/streaming-responses) + * guide for more information on how to handle the streaming events. + */ + stream?: boolean | null; + + /** + * Options for streaming response. Only set this when you set `stream: true`. + */ + stream_options?: ChatCompletionStreamOptions | null; + + /** + * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + * make the output more random, while lower values like 0.2 will make it more + * focused and deterministic. We generally recommend altering this or `top_p` but + * not both. + */ + temperature?: number | null; + + /** + * Controls which (if any) tool is called by the model. `none` means the model will + * not call any tool and instead generates a message. `auto` means the model can + * pick between generating a message or calling one or more tools. `required` means + * the model must call one or more tools. Specifying a particular tool via + * `{"type": "function", "function": {"name": "my_function"}}` forces the model to + * call that tool. + * + * `none` is the default when no tools are present. `auto` is the default if tools + * are present. + */ + tool_choice?: ChatCompletionToolChoiceOption; + + /** + * A list of tools the model may call. You can provide either + * [custom tools](https://platform.openai.com/docs/guides/function-calling#custom-tools) + * or [function tools](https://platform.openai.com/docs/guides/function-calling). + */ + tools?: Array; + + /** + * An integer between 0 and 20 specifying the number of most likely tokens to + * return at each token position, each with an associated log probability. + * `logprobs` must be set to `true` if this parameter is used. + */ + top_logprobs?: number | null; + + /** + * An alternative to sampling with temperature, called nucleus sampling, where the + * model considers the results of the tokens with top_p probability mass. So 0.1 + * means only the tokens comprising the top 10% probability mass are considered. + * + * We generally recommend altering this or `temperature` but not both. + */ + top_p?: number | null; + + /** + * @deprecated This field is being replaced by `safety_identifier` and + * `prompt_cache_key`. Use `prompt_cache_key` instead to maintain caching + * optimizations. A stable identifier for your end-users. Used to boost cache hit + * rates by better bucketing similar requests and to help OpenAI detect and prevent + * abuse. + * [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers). + */ + user?: string; + + /** + * Constrains the verbosity of the model's response. Lower values will result in + * more concise responses, while higher values will result in more verbose + * responses. Currently supported values are `low`, `medium`, and `high`. + */ + verbosity?: 'low' | 'medium' | 'high' | null; + + /** + * This tool searches the web for relevant results to use in a response. Learn more + * about the + * [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat). + */ + web_search_options?: ChatCompletionCreateParams.WebSearchOptions; +} + +export namespace ChatCompletionCreateParams { + /** + * @deprecated + */ + export interface Function { + /** + * The name of the function to be called. Must be a-z, A-Z, 0-9, or contain + * underscores and dashes, with a maximum length of 64. + */ + name: string; + + /** + * A description of what the function does, used by the model to choose when and + * how to call the function. + */ + description?: string; + + /** + * The parameters the functions accepts, described as a JSON Schema object. See the + * [guide](https://platform.openai.com/docs/guides/function-calling) for examples, + * and the + * [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for + * documentation about the format. + * + * Omitting `parameters` defines a function with an empty parameter list. + */ + parameters?: Shared.FunctionParameters; + } + + /** + * This tool searches the web for relevant results to use in a response. Learn more + * about the + * [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat). + */ + export interface WebSearchOptions { + /** + * High level guidance for the amount of context window space to use for the + * search. One of `low`, `medium`, or `high`. `medium` is the default. + */ + search_context_size?: 'low' | 'medium' | 'high'; + + /** + * Approximate location parameters for the search. + */ + user_location?: WebSearchOptions.UserLocation | null; + } + + export namespace WebSearchOptions { + /** + * Approximate location parameters for the search. + */ + export interface UserLocation { + /** + * Approximate location parameters for the search. + */ + approximate: UserLocation.Approximate; + + /** + * The type of location approximation. Always `approximate`. + */ + type: 'approximate'; + } + + export namespace UserLocation { + /** + * Approximate location parameters for the search. + */ + export interface Approximate { + /** + * Free text input for the city of the user, e.g. `San Francisco`. + */ + city?: string; + + /** + * The two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of + * the user, e.g. `US`. + */ + country?: string; + + /** + * Free text input for the region of the user, e.g. `California`. + */ + region?: string; + + /** + * The [IANA timezone](https://timeapi.io/documentation/iana-timezones) of the + * user, e.g. `America/Los_Angeles`. + */ + timezone?: string; + } + } + } + + export type ChatCompletionCreateParamsNonStreaming = + CompletionsCompletionsAPI.ChatCompletionCreateParamsNonStreaming; + export type ChatCompletionCreateParamsStreaming = + CompletionsCompletionsAPI.ChatCompletionCreateParamsStreaming; +} + +export interface ChatCompletionCreateParamsNonStreaming extends ChatCompletionCreateParamsBase { + /** + * If set to true, the model response data will be streamed to the client as it is + * generated using + * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + * See the + * [Streaming section below](https://platform.openai.com/docs/api-reference/chat/streaming) + * for more information, along with the + * [streaming responses](https://platform.openai.com/docs/guides/streaming-responses) + * guide for more information on how to handle the streaming events. + */ + stream?: false | null; +} + +export interface ChatCompletionCreateParamsStreaming extends ChatCompletionCreateParamsBase { + /** + * If set to true, the model response data will be streamed to the client as it is + * generated using + * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + * See the + * [Streaming section below](https://platform.openai.com/docs/api-reference/chat/streaming) + * for more information, along with the + * [streaming responses](https://platform.openai.com/docs/guides/streaming-responses) + * guide for more information on how to handle the streaming events. + */ + stream: true; +} + +export interface ChatCompletionUpdateParams { + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata: Shared.Metadata | null; +} + +export interface ChatCompletionListParams extends CursorPageParams { + /** + * A list of metadata keys to filter the Chat Completions by. Example: + * + * `metadata[key1]=value1&metadata[key2]=value2` + */ + metadata?: Shared.Metadata | null; + + /** + * The model used to generate the Chat Completions. + */ + model?: string; + + /** + * Sort order for Chat Completions by timestamp. Use `asc` for ascending order or + * `desc` for descending order. Defaults to `asc`. + */ + order?: 'asc' | 'desc'; +} + +Completions.Messages = Messages; + +export declare namespace Completions { + export { + type ChatCompletion as ChatCompletion, + type ChatCompletionAllowedToolChoice as ChatCompletionAllowedToolChoice, + type ChatCompletionAssistantMessageParam as ChatCompletionAssistantMessageParam, + type ChatCompletionAudio as ChatCompletionAudio, + type ChatCompletionAudioParam as ChatCompletionAudioParam, + type ChatCompletionChunk as ChatCompletionChunk, + type ChatCompletionContentPart as ChatCompletionContentPart, + type ChatCompletionContentPartImage as ChatCompletionContentPartImage, + type ChatCompletionContentPartInputAudio as ChatCompletionContentPartInputAudio, + type ChatCompletionContentPartRefusal as ChatCompletionContentPartRefusal, + type ChatCompletionContentPartText as ChatCompletionContentPartText, + type ChatCompletionCustomTool as ChatCompletionCustomTool, + type ChatCompletionDeleted as ChatCompletionDeleted, + type ChatCompletionDeveloperMessageParam as ChatCompletionDeveloperMessageParam, + type ChatCompletionFunctionCallOption as ChatCompletionFunctionCallOption, + type ChatCompletionFunctionMessageParam as ChatCompletionFunctionMessageParam, + type ChatCompletionFunctionTool as ChatCompletionFunctionTool, + type ChatCompletionMessage as ChatCompletionMessage, + type ChatCompletionMessageCustomToolCall as ChatCompletionMessageCustomToolCall, + type ChatCompletionMessageFunctionToolCall as ChatCompletionMessageFunctionToolCall, + type ChatCompletionMessageParam as ChatCompletionMessageParam, + type ChatCompletionMessageToolCall as ChatCompletionMessageToolCall, + type ChatCompletionModality as ChatCompletionModality, + type ChatCompletionNamedToolChoice as ChatCompletionNamedToolChoice, + type ChatCompletionNamedToolChoiceCustom as ChatCompletionNamedToolChoiceCustom, + type ChatCompletionPredictionContent as ChatCompletionPredictionContent, + type ChatCompletionRole as ChatCompletionRole, + type ChatCompletionStoreMessage as ChatCompletionStoreMessage, + type ChatCompletionStreamOptions as ChatCompletionStreamOptions, + type ChatCompletionSystemMessageParam as ChatCompletionSystemMessageParam, + type ChatCompletionTokenLogprob as ChatCompletionTokenLogprob, + type ChatCompletionTool as ChatCompletionTool, + type ChatCompletionToolChoiceOption as ChatCompletionToolChoiceOption, + type ChatCompletionToolMessageParam as ChatCompletionToolMessageParam, + type ChatCompletionUserMessageParam as ChatCompletionUserMessageParam, + type ChatCompletionAllowedTools as ChatCompletionAllowedTools, + type ChatCompletionReasoningEffort as ChatCompletionReasoningEffort, + type ChatCompletionsPage as ChatCompletionsPage, + type ChatCompletionCreateParams as ChatCompletionCreateParams, + type ChatCompletionCreateParamsNonStreaming as ChatCompletionCreateParamsNonStreaming, + type ChatCompletionCreateParamsStreaming as ChatCompletionCreateParamsStreaming, + type ChatCompletionUpdateParams as ChatCompletionUpdateParams, + type ChatCompletionListParams as ChatCompletionListParams, + }; + + export { Messages as Messages, type MessageListParams as MessageListParams }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/chat/completions/index.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/chat/completions/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..6a379c1d63d6df494ab9f022e4aeed4f3316ae9a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/chat/completions/index.ts @@ -0,0 +1,50 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export { + Completions, + type ChatCompletion, + type ChatCompletionAllowedToolChoice, + type ChatCompletionAssistantMessageParam, + type ChatCompletionAudio, + type ChatCompletionAudioParam, + type ChatCompletionChunk, + type ChatCompletionContentPart, + type ChatCompletionContentPartImage, + type ChatCompletionContentPartInputAudio, + type ChatCompletionContentPartRefusal, + type ChatCompletionContentPartText, + type ChatCompletionCustomTool, + type ChatCompletionDeleted, + type ChatCompletionDeveloperMessageParam, + type ChatCompletionFunctionCallOption, + type ChatCompletionFunctionMessageParam, + type ChatCompletionFunctionTool, + type ChatCompletionMessage, + type ChatCompletionMessageCustomToolCall, + type ChatCompletionMessageFunctionToolCall, + type ChatCompletionMessageParam, + type ChatCompletionMessageToolCall, + type ChatCompletionModality, + type ChatCompletionNamedToolChoice, + type ChatCompletionNamedToolChoiceCustom, + type ChatCompletionPredictionContent, + type ChatCompletionRole, + type ChatCompletionStoreMessage, + type ChatCompletionStreamOptions, + type ChatCompletionSystemMessageParam, + type ChatCompletionTokenLogprob, + type ChatCompletionTool, + type ChatCompletionToolChoiceOption, + type ChatCompletionToolMessageParam, + type ChatCompletionUserMessageParam, + type ChatCompletionAllowedTools, + type ChatCompletionCreateParams, + type ChatCompletionCreateParamsNonStreaming, + type ChatCompletionCreateParamsStreaming, + type ChatCompletionUpdateParams, + type ChatCompletionListParams, + type ChatCompletionStoreMessagesPage, + type ChatCompletionsPage, +} from './completions'; +export * from './completions'; +export { Messages, type MessageListParams } from './messages'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/chat/completions/messages.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/chat/completions/messages.ts new file mode 100644 index 0000000000000000000000000000000000000000..ee16e3269ebb03dabe8b63a2c7038f9cb453f8aa --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/chat/completions/messages.ts @@ -0,0 +1,50 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../../core/resource'; +import * as CompletionsAPI from './completions'; +import { ChatCompletionStoreMessagesPage } from './completions'; +import { CursorPage, type CursorPageParams, PagePromise } from '../../../core/pagination'; +import { RequestOptions } from '../../../internal/request-options'; +import { path } from '../../../internal/utils/path'; + +export class Messages extends APIResource { + /** + * Get the messages in a stored chat completion. Only Chat Completions that have + * been created with the `store` parameter set to `true` will be returned. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const chatCompletionStoreMessage of client.chat.completions.messages.list( + * 'completion_id', + * )) { + * // ... + * } + * ``` + */ + list( + completionID: string, + query: MessageListParams | null | undefined = {}, + options?: RequestOptions, + ): PagePromise { + return this._client.getAPIList( + path`/chat/completions/${completionID}/messages`, + CursorPage, + { query, ...options }, + ); + } +} + +export interface MessageListParams extends CursorPageParams { + /** + * Sort order for messages by timestamp. Use `asc` for ascending order or `desc` + * for descending order. Defaults to `asc`. + */ + order?: 'asc' | 'desc'; +} + +export declare namespace Messages { + export { type MessageListParams as MessageListParams }; +} + +export { type ChatCompletionStoreMessagesPage }; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/chat/index.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/chat/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..3004ebb08d434c12d6180bd10b4ff73095287945 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/chat/index.ts @@ -0,0 +1,49 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export { Chat } from './chat'; +export { + Completions, + type ChatCompletion, + type ChatCompletionAllowedToolChoice, + type ChatCompletionAssistantMessageParam, + type ChatCompletionAudio, + type ChatCompletionAudioParam, + type ChatCompletionChunk, + type ChatCompletionContentPart, + type ChatCompletionContentPartImage, + type ChatCompletionContentPartInputAudio, + type ChatCompletionContentPartRefusal, + type ChatCompletionContentPartText, + type ChatCompletionCustomTool, + type ChatCompletionDeleted, + type ChatCompletionDeveloperMessageParam, + type ChatCompletionFunctionCallOption, + type ChatCompletionFunctionMessageParam, + type ChatCompletionFunctionTool, + type ChatCompletionMessage, + type ChatCompletionMessageCustomToolCall, + type ChatCompletionMessageFunctionToolCall, + type ChatCompletionMessageParam, + type ChatCompletionMessageToolCall, + type ChatCompletionModality, + type ChatCompletionNamedToolChoice, + type ChatCompletionNamedToolChoiceCustom, + type ChatCompletionPredictionContent, + type ChatCompletionRole, + type ChatCompletionStoreMessage, + type ChatCompletionStreamOptions, + type ChatCompletionSystemMessageParam, + type ChatCompletionTokenLogprob, + type ChatCompletionTool, + type ChatCompletionToolChoiceOption, + type ChatCompletionToolMessageParam, + type ChatCompletionUserMessageParam, + type ChatCompletionAllowedTools, + type ChatCompletionCreateParams, + type ChatCompletionCreateParamsNonStreaming, + type ChatCompletionCreateParamsStreaming, + type ChatCompletionUpdateParams, + type ChatCompletionListParams, + type ChatCompletionStoreMessagesPage, + type ChatCompletionsPage, +} from './completions/index'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/completions.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/completions.ts new file mode 100644 index 0000000000000000000000000000000000000000..b15c3b5ad94e1e601a8a9c1a75084da91c742caa --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/completions.ts @@ -0,0 +1,394 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../core/resource'; +import * as CompletionsAPI from './completions'; +import * as CompletionsCompletionsAPI from './chat/completions/completions'; +import { APIPromise } from '../core/api-promise'; +import { Stream } from '../core/streaming'; +import { RequestOptions } from '../internal/request-options'; + +export class Completions extends APIResource { + /** + * Creates a completion for the provided prompt and parameters. + * + * @example + * ```ts + * const completion = await client.completions.create({ + * model: 'string', + * prompt: 'This is a test.', + * }); + * ``` + */ + create(body: CompletionCreateParamsNonStreaming, options?: RequestOptions): APIPromise; + create(body: CompletionCreateParamsStreaming, options?: RequestOptions): APIPromise>; + create( + body: CompletionCreateParamsBase, + options?: RequestOptions, + ): APIPromise | Completion>; + create( + body: CompletionCreateParams, + options?: RequestOptions, + ): APIPromise | APIPromise> { + return this._client.post('/completions', { body, ...options, stream: body.stream ?? false }) as + | APIPromise + | APIPromise>; + } +} + +/** + * Represents a completion response from the API. Note: both the streamed and + * non-streamed response objects share the same shape (unlike the chat endpoint). + */ +export interface Completion { + /** + * A unique identifier for the completion. + */ + id: string; + + /** + * The list of completion choices the model generated for the input prompt. + */ + choices: Array; + + /** + * The Unix timestamp (in seconds) of when the completion was created. + */ + created: number; + + /** + * The model used for completion. + */ + model: string; + + /** + * The object type, which is always "text_completion" + */ + object: 'text_completion'; + + /** + * This fingerprint represents the backend configuration that the model runs with. + * + * Can be used in conjunction with the `seed` request parameter to understand when + * backend changes have been made that might impact determinism. + */ + system_fingerprint?: string; + + /** + * Usage statistics for the completion request. + */ + usage?: CompletionUsage; +} + +export interface CompletionChoice { + /** + * The reason the model stopped generating tokens. This will be `stop` if the model + * hit a natural stop point or a provided stop sequence, `length` if the maximum + * number of tokens specified in the request was reached, or `content_filter` if + * content was omitted due to a flag from our content filters. + */ + finish_reason: 'stop' | 'length' | 'content_filter'; + + index: number; + + logprobs: CompletionChoice.Logprobs | null; + + text: string; +} + +export namespace CompletionChoice { + export interface Logprobs { + text_offset?: Array; + + token_logprobs?: Array; + + tokens?: Array; + + top_logprobs?: Array<{ [key: string]: number }>; + } +} + +/** + * Usage statistics for the completion request. + */ +export interface CompletionUsage { + /** + * Number of tokens in the generated completion. + */ + completion_tokens: number; + + /** + * Number of tokens in the prompt. + */ + prompt_tokens: number; + + /** + * Total number of tokens used in the request (prompt + completion). + */ + total_tokens: number; + + /** + * Breakdown of tokens used in a completion. + */ + completion_tokens_details?: CompletionUsage.CompletionTokensDetails; + + /** + * Breakdown of tokens used in the prompt. + */ + prompt_tokens_details?: CompletionUsage.PromptTokensDetails; +} + +export namespace CompletionUsage { + /** + * Breakdown of tokens used in a completion. + */ + export interface CompletionTokensDetails { + /** + * When using Predicted Outputs, the number of tokens in the prediction that + * appeared in the completion. + */ + accepted_prediction_tokens?: number; + + /** + * Audio input tokens generated by the model. + */ + audio_tokens?: number; + + /** + * Tokens generated by the model for reasoning. + */ + reasoning_tokens?: number; + + /** + * When using Predicted Outputs, the number of tokens in the prediction that did + * not appear in the completion. However, like reasoning tokens, these tokens are + * still counted in the total completion tokens for purposes of billing, output, + * and context window limits. + */ + rejected_prediction_tokens?: number; + } + + /** + * Breakdown of tokens used in the prompt. + */ + export interface PromptTokensDetails { + /** + * Audio input tokens present in the prompt. + */ + audio_tokens?: number; + + /** + * Cached tokens present in the prompt. + */ + cached_tokens?: number; + } +} + +export type CompletionCreateParams = CompletionCreateParamsNonStreaming | CompletionCreateParamsStreaming; + +export interface CompletionCreateParamsBase { + /** + * ID of the model to use. You can use the + * [List models](https://platform.openai.com/docs/api-reference/models/list) API to + * see all of your available models, or see our + * [Model overview](https://platform.openai.com/docs/models) for descriptions of + * them. + */ + model: (string & {}) | 'gpt-3.5-turbo-instruct' | 'davinci-002' | 'babbage-002'; + + /** + * The prompt(s) to generate completions for, encoded as a string, array of + * strings, array of tokens, or array of token arrays. + * + * Note that <|endoftext|> is the document separator that the model sees during + * training, so if a prompt is not specified the model will generate as if from the + * beginning of a new document. + */ + prompt: string | Array | Array | Array> | null; + + /** + * Generates `best_of` completions server-side and returns the "best" (the one with + * the highest log probability per token). Results cannot be streamed. + * + * When used with `n`, `best_of` controls the number of candidate completions and + * `n` specifies how many to return – `best_of` must be greater than `n`. + * + * **Note:** Because this parameter generates many completions, it can quickly + * consume your token quota. Use carefully and ensure that you have reasonable + * settings for `max_tokens` and `stop`. + */ + best_of?: number | null; + + /** + * Echo back the prompt in addition to the completion + */ + echo?: boolean | null; + + /** + * Number between -2.0 and 2.0. Positive values penalize new tokens based on their + * existing frequency in the text so far, decreasing the model's likelihood to + * repeat the same line verbatim. + * + * [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) + */ + frequency_penalty?: number | null; + + /** + * Modify the likelihood of specified tokens appearing in the completion. + * + * Accepts a JSON object that maps tokens (specified by their token ID in the GPT + * tokenizer) to an associated bias value from -100 to 100. You can use this + * [tokenizer tool](/tokenizer?view=bpe) to convert text to token IDs. + * Mathematically, the bias is added to the logits generated by the model prior to + * sampling. The exact effect will vary per model, but values between -1 and 1 + * should decrease or increase likelihood of selection; values like -100 or 100 + * should result in a ban or exclusive selection of the relevant token. + * + * As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token + * from being generated. + */ + logit_bias?: { [key: string]: number } | null; + + /** + * Include the log probabilities on the `logprobs` most likely output tokens, as + * well the chosen tokens. For example, if `logprobs` is 5, the API will return a + * list of the 5 most likely tokens. The API will always return the `logprob` of + * the sampled token, so there may be up to `logprobs+1` elements in the response. + * + * The maximum value for `logprobs` is 5. + */ + logprobs?: number | null; + + /** + * The maximum number of [tokens](/tokenizer) that can be generated in the + * completion. + * + * The token count of your prompt plus `max_tokens` cannot exceed the model's + * context length. + * [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) + * for counting tokens. + */ + max_tokens?: number | null; + + /** + * How many completions to generate for each prompt. + * + * **Note:** Because this parameter generates many completions, it can quickly + * consume your token quota. Use carefully and ensure that you have reasonable + * settings for `max_tokens` and `stop`. + */ + n?: number | null; + + /** + * Number between -2.0 and 2.0. Positive values penalize new tokens based on + * whether they appear in the text so far, increasing the model's likelihood to + * talk about new topics. + * + * [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) + */ + presence_penalty?: number | null; + + /** + * If specified, our system will make a best effort to sample deterministically, + * such that repeated requests with the same `seed` and parameters should return + * the same result. + * + * Determinism is not guaranteed, and you should refer to the `system_fingerprint` + * response parameter to monitor changes in the backend. + */ + seed?: number | null; + + /** + * Not supported with latest reasoning models `o3` and `o4-mini`. + * + * Up to 4 sequences where the API will stop generating further tokens. The + * returned text will not contain the stop sequence. + */ + stop?: string | null | Array; + + /** + * Whether to stream back partial progress. If set, tokens will be sent as + * data-only + * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + * as they become available, with the stream terminated by a `data: [DONE]` + * message. + * [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + */ + stream?: boolean | null; + + /** + * Options for streaming response. Only set this when you set `stream: true`. + */ + stream_options?: CompletionsCompletionsAPI.ChatCompletionStreamOptions | null; + + /** + * The suffix that comes after a completion of inserted text. + * + * This parameter is only supported for `gpt-3.5-turbo-instruct`. + */ + suffix?: string | null; + + /** + * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + * make the output more random, while lower values like 0.2 will make it more + * focused and deterministic. + * + * We generally recommend altering this or `top_p` but not both. + */ + temperature?: number | null; + + /** + * An alternative to sampling with temperature, called nucleus sampling, where the + * model considers the results of the tokens with top_p probability mass. So 0.1 + * means only the tokens comprising the top 10% probability mass are considered. + * + * We generally recommend altering this or `temperature` but not both. + */ + top_p?: number | null; + + /** + * A unique identifier representing your end-user, which can help OpenAI to monitor + * and detect abuse. + * [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). + */ + user?: string; +} + +export namespace CompletionCreateParams { + export type CompletionCreateParamsNonStreaming = CompletionsAPI.CompletionCreateParamsNonStreaming; + export type CompletionCreateParamsStreaming = CompletionsAPI.CompletionCreateParamsStreaming; +} + +export interface CompletionCreateParamsNonStreaming extends CompletionCreateParamsBase { + /** + * Whether to stream back partial progress. If set, tokens will be sent as + * data-only + * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + * as they become available, with the stream terminated by a `data: [DONE]` + * message. + * [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + */ + stream?: false | null; +} + +export interface CompletionCreateParamsStreaming extends CompletionCreateParamsBase { + /** + * Whether to stream back partial progress. If set, tokens will be sent as + * data-only + * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + * as they become available, with the stream terminated by a `data: [DONE]` + * message. + * [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + */ + stream: true; +} + +export declare namespace Completions { + export { + type Completion as Completion, + type CompletionChoice as CompletionChoice, + type CompletionUsage as CompletionUsage, + type CompletionCreateParams as CompletionCreateParams, + type CompletionCreateParamsNonStreaming as CompletionCreateParamsNonStreaming, + type CompletionCreateParamsStreaming as CompletionCreateParamsStreaming, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/containers.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/containers.ts new file mode 100644 index 0000000000000000000000000000000000000000..c8f3a6456e3eadb2cb37d87f2d168b5dee390d48 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/containers.ts @@ -0,0 +1,3 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export * from './containers/index'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/containers/containers.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/containers/containers.ts new file mode 100644 index 0000000000000000000000000000000000000000..7fd73ebc0b82b5e27f18611a2c0ee8219d33604f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/containers/containers.ts @@ -0,0 +1,284 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../core/resource'; +import * as FilesAPI from './files/files'; +import { + FileCreateParams, + FileCreateResponse, + FileDeleteParams, + FileListParams, + FileListResponse, + FileListResponsesPage, + FileRetrieveParams, + FileRetrieveResponse, + Files, +} from './files/files'; +import { APIPromise } from '../../core/api-promise'; +import { CursorPage, type CursorPageParams, PagePromise } from '../../core/pagination'; +import { buildHeaders } from '../../internal/headers'; +import { RequestOptions } from '../../internal/request-options'; +import { path } from '../../internal/utils/path'; + +export class Containers extends APIResource { + files: FilesAPI.Files = new FilesAPI.Files(this._client); + + /** + * Create Container + */ + create(body: ContainerCreateParams, options?: RequestOptions): APIPromise { + return this._client.post('/containers', { body, ...options }); + } + + /** + * Retrieve Container + */ + retrieve(containerID: string, options?: RequestOptions): APIPromise { + return this._client.get(path`/containers/${containerID}`, options); + } + + /** + * List Containers + */ + list( + query: ContainerListParams | null | undefined = {}, + options?: RequestOptions, + ): PagePromise { + return this._client.getAPIList('/containers', CursorPage, { query, ...options }); + } + + /** + * Delete Container + */ + delete(containerID: string, options?: RequestOptions): APIPromise { + return this._client.delete(path`/containers/${containerID}`, { + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); + } +} + +export type ContainerListResponsesPage = CursorPage; + +export interface ContainerCreateResponse { + /** + * Unique identifier for the container. + */ + id: string; + + /** + * Unix timestamp (in seconds) when the container was created. + */ + created_at: number; + + /** + * Name of the container. + */ + name: string; + + /** + * The type of this object. + */ + object: string; + + /** + * Status of the container (e.g., active, deleted). + */ + status: string; + + /** + * The container will expire after this time period. The anchor is the reference + * point for the expiration. The minutes is the number of minutes after the anchor + * before the container expires. + */ + expires_after?: ContainerCreateResponse.ExpiresAfter; +} + +export namespace ContainerCreateResponse { + /** + * The container will expire after this time period. The anchor is the reference + * point for the expiration. The minutes is the number of minutes after the anchor + * before the container expires. + */ + export interface ExpiresAfter { + /** + * The reference point for the expiration. + */ + anchor?: 'last_active_at'; + + /** + * The number of minutes after the anchor before the container expires. + */ + minutes?: number; + } +} + +export interface ContainerRetrieveResponse { + /** + * Unique identifier for the container. + */ + id: string; + + /** + * Unix timestamp (in seconds) when the container was created. + */ + created_at: number; + + /** + * Name of the container. + */ + name: string; + + /** + * The type of this object. + */ + object: string; + + /** + * Status of the container (e.g., active, deleted). + */ + status: string; + + /** + * The container will expire after this time period. The anchor is the reference + * point for the expiration. The minutes is the number of minutes after the anchor + * before the container expires. + */ + expires_after?: ContainerRetrieveResponse.ExpiresAfter; +} + +export namespace ContainerRetrieveResponse { + /** + * The container will expire after this time period. The anchor is the reference + * point for the expiration. The minutes is the number of minutes after the anchor + * before the container expires. + */ + export interface ExpiresAfter { + /** + * The reference point for the expiration. + */ + anchor?: 'last_active_at'; + + /** + * The number of minutes after the anchor before the container expires. + */ + minutes?: number; + } +} + +export interface ContainerListResponse { + /** + * Unique identifier for the container. + */ + id: string; + + /** + * Unix timestamp (in seconds) when the container was created. + */ + created_at: number; + + /** + * Name of the container. + */ + name: string; + + /** + * The type of this object. + */ + object: string; + + /** + * Status of the container (e.g., active, deleted). + */ + status: string; + + /** + * The container will expire after this time period. The anchor is the reference + * point for the expiration. The minutes is the number of minutes after the anchor + * before the container expires. + */ + expires_after?: ContainerListResponse.ExpiresAfter; +} + +export namespace ContainerListResponse { + /** + * The container will expire after this time period. The anchor is the reference + * point for the expiration. The minutes is the number of minutes after the anchor + * before the container expires. + */ + export interface ExpiresAfter { + /** + * The reference point for the expiration. + */ + anchor?: 'last_active_at'; + + /** + * The number of minutes after the anchor before the container expires. + */ + minutes?: number; + } +} + +export interface ContainerCreateParams { + /** + * Name of the container to create. + */ + name: string; + + /** + * Container expiration time in seconds relative to the 'anchor' time. + */ + expires_after?: ContainerCreateParams.ExpiresAfter; + + /** + * IDs of files to copy to the container. + */ + file_ids?: Array; +} + +export namespace ContainerCreateParams { + /** + * Container expiration time in seconds relative to the 'anchor' time. + */ + export interface ExpiresAfter { + /** + * Time anchor for the expiration time. Currently only 'last_active_at' is + * supported. + */ + anchor: 'last_active_at'; + + minutes: number; + } +} + +export interface ContainerListParams extends CursorPageParams { + /** + * Sort order by the `created_at` timestamp of the objects. `asc` for ascending + * order and `desc` for descending order. + */ + order?: 'asc' | 'desc'; +} + +Containers.Files = Files; + +export declare namespace Containers { + export { + type ContainerCreateResponse as ContainerCreateResponse, + type ContainerRetrieveResponse as ContainerRetrieveResponse, + type ContainerListResponse as ContainerListResponse, + type ContainerListResponsesPage as ContainerListResponsesPage, + type ContainerCreateParams as ContainerCreateParams, + type ContainerListParams as ContainerListParams, + }; + + export { + Files as Files, + type FileCreateResponse as FileCreateResponse, + type FileRetrieveResponse as FileRetrieveResponse, + type FileListResponse as FileListResponse, + type FileListResponsesPage as FileListResponsesPage, + type FileCreateParams as FileCreateParams, + type FileRetrieveParams as FileRetrieveParams, + type FileListParams as FileListParams, + type FileDeleteParams as FileDeleteParams, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/containers/files.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/containers/files.ts new file mode 100644 index 0000000000000000000000000000000000000000..46a5299c1730b2451e8ca9014a6b8dab93871725 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/containers/files.ts @@ -0,0 +1,3 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export * from './files/index'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/containers/files/content.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/containers/files/content.ts new file mode 100644 index 0000000000000000000000000000000000000000..76ceb170363952c228a6265c77327faecb283e70 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/containers/files/content.ts @@ -0,0 +1,29 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../../core/resource'; +import { APIPromise } from '../../../core/api-promise'; +import { buildHeaders } from '../../../internal/headers'; +import { RequestOptions } from '../../../internal/request-options'; +import { path } from '../../../internal/utils/path'; + +export class Content extends APIResource { + /** + * Retrieve Container File Content + */ + retrieve(fileID: string, params: ContentRetrieveParams, options?: RequestOptions): APIPromise { + const { container_id } = params; + return this._client.get(path`/containers/${container_id}/files/${fileID}/content`, { + ...options, + headers: buildHeaders([{ Accept: 'application/binary' }, options?.headers]), + __binaryResponse: true, + }); + } +} + +export interface ContentRetrieveParams { + container_id: string; +} + +export declare namespace Content { + export { type ContentRetrieveParams as ContentRetrieveParams }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/containers/files/files.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/containers/files/files.ts new file mode 100644 index 0000000000000000000000000000000000000000..cc98d7bf9b3bc6559a9fef2765df412c7b885e29 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/containers/files/files.ts @@ -0,0 +1,228 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../../core/resource'; +import * as ContentAPI from './content'; +import { Content, ContentRetrieveParams } from './content'; +import { APIPromise } from '../../../core/api-promise'; +import { CursorPage, type CursorPageParams, PagePromise } from '../../../core/pagination'; +import { type Uploadable } from '../../../core/uploads'; +import { buildHeaders } from '../../../internal/headers'; +import { RequestOptions } from '../../../internal/request-options'; +import { multipartFormRequestOptions } from '../../../internal/uploads'; +import { path } from '../../../internal/utils/path'; + +export class Files extends APIResource { + content: ContentAPI.Content = new ContentAPI.Content(this._client); + + /** + * Create a Container File + * + * You can send either a multipart/form-data request with the raw file content, or + * a JSON request with a file ID. + */ + create( + containerID: string, + body: FileCreateParams, + options?: RequestOptions, + ): APIPromise { + return this._client.post( + path`/containers/${containerID}/files`, + multipartFormRequestOptions({ body, ...options }, this._client), + ); + } + + /** + * Retrieve Container File + */ + retrieve( + fileID: string, + params: FileRetrieveParams, + options?: RequestOptions, + ): APIPromise { + const { container_id } = params; + return this._client.get(path`/containers/${container_id}/files/${fileID}`, options); + } + + /** + * List Container files + */ + list( + containerID: string, + query: FileListParams | null | undefined = {}, + options?: RequestOptions, + ): PagePromise { + return this._client.getAPIList(path`/containers/${containerID}/files`, CursorPage, { + query, + ...options, + }); + } + + /** + * Delete Container File + */ + delete(fileID: string, params: FileDeleteParams, options?: RequestOptions): APIPromise { + const { container_id } = params; + return this._client.delete(path`/containers/${container_id}/files/${fileID}`, { + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); + } +} + +export type FileListResponsesPage = CursorPage; + +export interface FileCreateResponse { + /** + * Unique identifier for the file. + */ + id: string; + + /** + * Size of the file in bytes. + */ + bytes: number; + + /** + * The container this file belongs to. + */ + container_id: string; + + /** + * Unix timestamp (in seconds) when the file was created. + */ + created_at: number; + + /** + * The type of this object (`container.file`). + */ + object: 'container.file'; + + /** + * Path of the file in the container. + */ + path: string; + + /** + * Source of the file (e.g., `user`, `assistant`). + */ + source: string; +} + +export interface FileRetrieveResponse { + /** + * Unique identifier for the file. + */ + id: string; + + /** + * Size of the file in bytes. + */ + bytes: number; + + /** + * The container this file belongs to. + */ + container_id: string; + + /** + * Unix timestamp (in seconds) when the file was created. + */ + created_at: number; + + /** + * The type of this object (`container.file`). + */ + object: 'container.file'; + + /** + * Path of the file in the container. + */ + path: string; + + /** + * Source of the file (e.g., `user`, `assistant`). + */ + source: string; +} + +export interface FileListResponse { + /** + * Unique identifier for the file. + */ + id: string; + + /** + * Size of the file in bytes. + */ + bytes: number; + + /** + * The container this file belongs to. + */ + container_id: string; + + /** + * Unix timestamp (in seconds) when the file was created. + */ + created_at: number; + + /** + * The type of this object (`container.file`). + */ + object: 'container.file'; + + /** + * Path of the file in the container. + */ + path: string; + + /** + * Source of the file (e.g., `user`, `assistant`). + */ + source: string; +} + +export interface FileCreateParams { + /** + * The File object (not file name) to be uploaded. + */ + file?: Uploadable; + + /** + * Name of the file to create. + */ + file_id?: string; +} + +export interface FileRetrieveParams { + container_id: string; +} + +export interface FileListParams extends CursorPageParams { + /** + * Sort order by the `created_at` timestamp of the objects. `asc` for ascending + * order and `desc` for descending order. + */ + order?: 'asc' | 'desc'; +} + +export interface FileDeleteParams { + container_id: string; +} + +Files.Content = Content; + +export declare namespace Files { + export { + type FileCreateResponse as FileCreateResponse, + type FileRetrieveResponse as FileRetrieveResponse, + type FileListResponse as FileListResponse, + type FileListResponsesPage as FileListResponsesPage, + type FileCreateParams as FileCreateParams, + type FileRetrieveParams as FileRetrieveParams, + type FileListParams as FileListParams, + type FileDeleteParams as FileDeleteParams, + }; + + export { Content as Content, type ContentRetrieveParams as ContentRetrieveParams }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/containers/files/index.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/containers/files/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..863f438c42f476d0b2a3378e3795745a5f4d9f9a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/containers/files/index.ts @@ -0,0 +1,14 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export { Content, type ContentRetrieveParams } from './content'; +export { + Files, + type FileCreateResponse, + type FileRetrieveResponse, + type FileListResponse, + type FileCreateParams, + type FileRetrieveParams, + type FileListParams, + type FileDeleteParams, + type FileListResponsesPage, +} from './files'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/containers/index.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/containers/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..265451481e8304d62bf75fb51cba79148191391a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/containers/index.ts @@ -0,0 +1,22 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export { + Containers, + type ContainerCreateResponse, + type ContainerRetrieveResponse, + type ContainerListResponse, + type ContainerCreateParams, + type ContainerListParams, + type ContainerListResponsesPage, +} from './containers'; +export { + Files, + type FileCreateResponse, + type FileRetrieveResponse, + type FileListResponse, + type FileCreateParams, + type FileRetrieveParams, + type FileListParams, + type FileDeleteParams, + type FileListResponsesPage, +} from './files/index'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/conversations.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/conversations.ts new file mode 100644 index 0000000000000000000000000000000000000000..6b5095057f7ca7fc00aab9f09735788c51a6e947 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/conversations.ts @@ -0,0 +1,3 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export * from './conversations/index'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/conversations/conversations.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/conversations/conversations.ts new file mode 100644 index 0000000000000000000000000000000000000000..4854d8234d1f19059658c48efd4575305027808c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/conversations/conversations.ts @@ -0,0 +1,416 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../core/resource'; +import * as Shared from '../shared'; +import * as ItemsAPI from './items'; +import { + ConversationItem, + ConversationItemList, + ConversationItemsPage, + ItemCreateParams, + ItemDeleteParams, + ItemListParams, + ItemRetrieveParams, + Items, +} from './items'; +import * as ResponsesAPI from '../responses/responses'; +import { APIPromise } from '../../core/api-promise'; +import { RequestOptions } from '../../internal/request-options'; +import { path } from '../../internal/utils/path'; + +export class Conversations extends APIResource { + items: ItemsAPI.Items = new ItemsAPI.Items(this._client); + + /** + * Create a conversation. + */ + create(body: ConversationCreateParams, options?: RequestOptions): APIPromise { + return this._client.post('/conversations', { body, ...options }); + } + + /** + * Get a conversation with the given ID. + */ + retrieve(conversationID: string, options?: RequestOptions): APIPromise { + return this._client.get(path`/conversations/${conversationID}`, options); + } + + /** + * Update a conversation's metadata with the given ID. + */ + update( + conversationID: string, + body: ConversationUpdateParams, + options?: RequestOptions, + ): APIPromise { + return this._client.post(path`/conversations/${conversationID}`, { body, ...options }); + } + + /** + * Delete a conversation with the given ID. + */ + delete(conversationID: string, options?: RequestOptions): APIPromise { + return this._client.delete(path`/conversations/${conversationID}`, options); + } +} + +export interface ComputerScreenshotContent { + /** + * The identifier of an uploaded file that contains the screenshot. + */ + file_id: string | null; + + /** + * The URL of the screenshot image. + */ + image_url: string | null; + + /** + * Specifies the event type. For a computer screenshot, this property is always set + * to `computer_screenshot`. + */ + type: 'computer_screenshot'; +} + +export interface ContainerFileCitationBody { + /** + * The ID of the container file. + */ + container_id: string; + + /** + * The index of the last character of the container file citation in the message. + */ + end_index: number; + + /** + * The ID of the file. + */ + file_id: string; + + /** + * The filename of the container file cited. + */ + filename: string; + + /** + * The index of the first character of the container file citation in the message. + */ + start_index: number; + + /** + * The type of the container file citation. Always `container_file_citation`. + */ + type: 'container_file_citation'; +} + +export interface Conversation { + /** + * The unique ID of the conversation. + */ + id: string; + + /** + * The time at which the conversation was created, measured in seconds since the + * Unix epoch. + */ + created_at: number; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. Keys are strings with a maximum + * length of 64 characters. Values are strings with a maximum length of 512 + * characters. + */ + metadata: unknown; + + /** + * The object type, which is always `conversation`. + */ + object: 'conversation'; +} + +export interface ConversationDeleted { + id: string; + + deleted: boolean; + + object: 'conversation.deleted'; +} + +export interface ConversationDeletedResource { + id: string; + + deleted: boolean; + + object: 'conversation.deleted'; +} + +export interface FileCitationBody { + /** + * The ID of the file. + */ + file_id: string; + + /** + * The filename of the file cited. + */ + filename: string; + + /** + * The index of the file in the list of files. + */ + index: number; + + /** + * The type of the file citation. Always `file_citation`. + */ + type: 'file_citation'; +} + +export interface InputFileContent { + /** + * The ID of the file to be sent to the model. + */ + file_id: string | null; + + /** + * The type of the input item. Always `input_file`. + */ + type: 'input_file'; + + /** + * The URL of the file to be sent to the model. + */ + file_url?: string; + + /** + * The name of the file to be sent to the model. + */ + filename?: string; +} + +export interface InputImageContent { + /** + * The detail level of the image to be sent to the model. One of `high`, `low`, or + * `auto`. Defaults to `auto`. + */ + detail: 'low' | 'high' | 'auto'; + + /** + * The ID of the file to be sent to the model. + */ + file_id: string | null; + + /** + * The URL of the image to be sent to the model. A fully qualified URL or base64 + * encoded image in a data URL. + */ + image_url: string | null; + + /** + * The type of the input item. Always `input_image`. + */ + type: 'input_image'; +} + +export interface InputTextContent { + /** + * The text input to the model. + */ + text: string; + + /** + * The type of the input item. Always `input_text`. + */ + type: 'input_text'; +} + +export interface LobProb { + token: string; + + bytes: Array; + + logprob: number; + + top_logprobs: Array; +} + +export interface Message { + /** + * The unique ID of the message. + */ + id: string; + + /** + * The content of the message + */ + content: Array< + | InputTextContent + | OutputTextContent + | TextContent + | SummaryTextContent + | RefusalContent + | InputImageContent + | ComputerScreenshotContent + | InputFileContent + >; + + /** + * The role of the message. One of `unknown`, `user`, `assistant`, `system`, + * `critic`, `discriminator`, `developer`, or `tool`. + */ + role: 'unknown' | 'user' | 'assistant' | 'system' | 'critic' | 'discriminator' | 'developer' | 'tool'; + + /** + * The status of item. One of `in_progress`, `completed`, or `incomplete`. + * Populated when items are returned via API. + */ + status: 'in_progress' | 'completed' | 'incomplete'; + + /** + * The type of the message. Always set to `message`. + */ + type: 'message'; +} + +export interface OutputTextContent { + /** + * The annotations of the text output. + */ + annotations: Array; + + /** + * The text output from the model. + */ + text: string; + + /** + * The type of the output text. Always `output_text`. + */ + type: 'output_text'; + + logprobs?: Array; +} + +export interface RefusalContent { + /** + * The refusal explanation from the model. + */ + refusal: string; + + /** + * The type of the refusal. Always `refusal`. + */ + type: 'refusal'; +} + +export interface SummaryTextContent { + text: string; + + type: 'summary_text'; +} + +export interface TextContent { + text: string; + + type: 'text'; +} + +export interface TopLogProb { + token: string; + + bytes: Array; + + logprob: number; +} + +export interface URLCitationBody { + /** + * The index of the last character of the URL citation in the message. + */ + end_index: number; + + /** + * The index of the first character of the URL citation in the message. + */ + start_index: number; + + /** + * The title of the web resource. + */ + title: string; + + /** + * The type of the URL citation. Always `url_citation`. + */ + type: 'url_citation'; + + /** + * The URL of the web resource. + */ + url: string; +} + +export interface ConversationCreateParams { + /** + * Initial items to include in the conversation context. You may add up to 20 items + * at a time. + */ + items?: Array | null; + + /** + * Set of 16 key-value pairs that can be attached to an object. Useful for storing + * additional information about the object in a structured format. + */ + metadata?: Shared.Metadata | null; +} + +export interface ConversationUpdateParams { + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. Keys are strings with a maximum + * length of 64 characters. Values are strings with a maximum length of 512 + * characters. + */ + metadata: { [key: string]: string }; +} + +Conversations.Items = Items; + +export declare namespace Conversations { + export { + type ComputerScreenshotContent as ComputerScreenshotContent, + type ContainerFileCitationBody as ContainerFileCitationBody, + type Conversation as Conversation, + type ConversationDeleted as ConversationDeleted, + type ConversationDeletedResource as ConversationDeletedResource, + type FileCitationBody as FileCitationBody, + type InputFileContent as InputFileContent, + type InputImageContent as InputImageContent, + type InputTextContent as InputTextContent, + type LobProb as LobProb, + type Message as Message, + type OutputTextContent as OutputTextContent, + type RefusalContent as RefusalContent, + type SummaryTextContent as SummaryTextContent, + type TextContent as TextContent, + type TopLogProb as TopLogProb, + type URLCitationBody as URLCitationBody, + type ConversationCreateParams as ConversationCreateParams, + type ConversationUpdateParams as ConversationUpdateParams, + }; + + export { + Items as Items, + type ConversationItem as ConversationItem, + type ConversationItemList as ConversationItemList, + type ConversationItemsPage as ConversationItemsPage, + type ItemCreateParams as ItemCreateParams, + type ItemRetrieveParams as ItemRetrieveParams, + type ItemListParams as ItemListParams, + type ItemDeleteParams as ItemDeleteParams, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/conversations/index.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/conversations/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..a1dea13b915e3f4ee1995d0dd3d7e8524190b568 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/conversations/index.ts @@ -0,0 +1,13 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export { Conversations } from './conversations'; +export { + Items, + type ConversationItem, + type ConversationItemList, + type ItemCreateParams, + type ItemRetrieveParams, + type ItemListParams, + type ItemDeleteParams, + type ConversationItemsPage, +} from './items'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/conversations/items.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/conversations/items.ts new file mode 100644 index 0000000000000000000000000000000000000000..d47e0109ef46b18c55499b623ebe544094540058 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/conversations/items.ts @@ -0,0 +1,485 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../core/resource'; +import * as ConversationsAPI from './conversations'; +import * as ResponsesAPI from '../responses/responses'; +import { APIPromise } from '../../core/api-promise'; +import { + ConversationCursorPage, + type ConversationCursorPageParams, + PagePromise, +} from '../../core/pagination'; +import { RequestOptions } from '../../internal/request-options'; +import { path } from '../../internal/utils/path'; + +export class Items extends APIResource { + /** + * Create items in a conversation with the given ID. + */ + create( + conversationID: string, + params: ItemCreateParams, + options?: RequestOptions, + ): APIPromise { + const { include, ...body } = params; + return this._client.post(path`/conversations/${conversationID}/items`, { + query: { include }, + body, + ...options, + }); + } + + /** + * Get a single item from a conversation with the given IDs. + */ + retrieve( + itemID: string, + params: ItemRetrieveParams, + options?: RequestOptions, + ): APIPromise { + const { conversation_id, ...query } = params; + return this._client.get(path`/conversations/${conversation_id}/items/${itemID}`, { query, ...options }); + } + + /** + * List all items for a conversation with the given ID. + */ + list( + conversationID: string, + query: ItemListParams | null | undefined = {}, + options?: RequestOptions, + ): PagePromise { + return this._client.getAPIList( + path`/conversations/${conversationID}/items`, + ConversationCursorPage, + { query, ...options }, + ); + } + + /** + * Delete an item from a conversation with the given IDs. + */ + delete( + itemID: string, + params: ItemDeleteParams, + options?: RequestOptions, + ): APIPromise { + const { conversation_id } = params; + return this._client.delete(path`/conversations/${conversation_id}/items/${itemID}`, options); + } +} + +export type ConversationItemsPage = ConversationCursorPage; + +/** + * A single item within a conversation. The set of possible types are the same as + * the `output` type of a + * [Response object](https://platform.openai.com/docs/api-reference/responses/object#responses/object-output). + */ +export type ConversationItem = + | ConversationsAPI.Message + | ResponsesAPI.ResponseFunctionToolCallItem + | ResponsesAPI.ResponseFunctionToolCallOutputItem + | ResponsesAPI.ResponseFileSearchToolCall + | ResponsesAPI.ResponseFunctionWebSearch + | ConversationItem.ImageGenerationCall + | ResponsesAPI.ResponseComputerToolCall + | ResponsesAPI.ResponseComputerToolCallOutputItem + | ResponsesAPI.ResponseReasoningItem + | ResponsesAPI.ResponseCodeInterpreterToolCall + | ConversationItem.LocalShellCall + | ConversationItem.LocalShellCallOutput + | ConversationItem.McpListTools + | ConversationItem.McpApprovalRequest + | ConversationItem.McpApprovalResponse + | ConversationItem.McpCall + | ResponsesAPI.ResponseCustomToolCall + | ResponsesAPI.ResponseCustomToolCallOutput; + +export namespace ConversationItem { + /** + * An image generation request made by the model. + */ + export interface ImageGenerationCall { + /** + * The unique ID of the image generation call. + */ + id: string; + + /** + * The generated image encoded in base64. + */ + result: string | null; + + /** + * The status of the image generation call. + */ + status: 'in_progress' | 'completed' | 'generating' | 'failed'; + + /** + * The type of the image generation call. Always `image_generation_call`. + */ + type: 'image_generation_call'; + } + + /** + * A tool call to run a command on the local shell. + */ + export interface LocalShellCall { + /** + * The unique ID of the local shell call. + */ + id: string; + + /** + * Execute a shell command on the server. + */ + action: LocalShellCall.Action; + + /** + * The unique ID of the local shell tool call generated by the model. + */ + call_id: string; + + /** + * The status of the local shell call. + */ + status: 'in_progress' | 'completed' | 'incomplete'; + + /** + * The type of the local shell call. Always `local_shell_call`. + */ + type: 'local_shell_call'; + } + + export namespace LocalShellCall { + /** + * Execute a shell command on the server. + */ + export interface Action { + /** + * The command to run. + */ + command: Array; + + /** + * Environment variables to set for the command. + */ + env: { [key: string]: string }; + + /** + * The type of the local shell action. Always `exec`. + */ + type: 'exec'; + + /** + * Optional timeout in milliseconds for the command. + */ + timeout_ms?: number | null; + + /** + * Optional user to run the command as. + */ + user?: string | null; + + /** + * Optional working directory to run the command in. + */ + working_directory?: string | null; + } + } + + /** + * The output of a local shell tool call. + */ + export interface LocalShellCallOutput { + /** + * The unique ID of the local shell tool call generated by the model. + */ + id: string; + + /** + * A JSON string of the output of the local shell tool call. + */ + output: string; + + /** + * The type of the local shell tool call output. Always `local_shell_call_output`. + */ + type: 'local_shell_call_output'; + + /** + * The status of the item. One of `in_progress`, `completed`, or `incomplete`. + */ + status?: 'in_progress' | 'completed' | 'incomplete' | null; + } + + /** + * A list of tools available on an MCP server. + */ + export interface McpListTools { + /** + * The unique ID of the list. + */ + id: string; + + /** + * The label of the MCP server. + */ + server_label: string; + + /** + * The tools available on the server. + */ + tools: Array; + + /** + * The type of the item. Always `mcp_list_tools`. + */ + type: 'mcp_list_tools'; + + /** + * Error message if the server could not list tools. + */ + error?: string | null; + } + + export namespace McpListTools { + /** + * A tool available on an MCP server. + */ + export interface Tool { + /** + * The JSON schema describing the tool's input. + */ + input_schema: unknown; + + /** + * The name of the tool. + */ + name: string; + + /** + * Additional annotations about the tool. + */ + annotations?: unknown | null; + + /** + * The description of the tool. + */ + description?: string | null; + } + } + + /** + * A request for human approval of a tool invocation. + */ + export interface McpApprovalRequest { + /** + * The unique ID of the approval request. + */ + id: string; + + /** + * A JSON string of arguments for the tool. + */ + arguments: string; + + /** + * The name of the tool to run. + */ + name: string; + + /** + * The label of the MCP server making the request. + */ + server_label: string; + + /** + * The type of the item. Always `mcp_approval_request`. + */ + type: 'mcp_approval_request'; + } + + /** + * A response to an MCP approval request. + */ + export interface McpApprovalResponse { + /** + * The unique ID of the approval response + */ + id: string; + + /** + * The ID of the approval request being answered. + */ + approval_request_id: string; + + /** + * Whether the request was approved. + */ + approve: boolean; + + /** + * The type of the item. Always `mcp_approval_response`. + */ + type: 'mcp_approval_response'; + + /** + * Optional reason for the decision. + */ + reason?: string | null; + } + + /** + * An invocation of a tool on an MCP server. + */ + export interface McpCall { + /** + * The unique ID of the tool call. + */ + id: string; + + /** + * A JSON string of the arguments passed to the tool. + */ + arguments: string; + + /** + * The name of the tool that was run. + */ + name: string; + + /** + * The label of the MCP server running the tool. + */ + server_label: string; + + /** + * The type of the item. Always `mcp_call`. + */ + type: 'mcp_call'; + + /** + * The error from the tool call, if any. + */ + error?: string | null; + + /** + * The output from the tool call. + */ + output?: string | null; + } +} + +/** + * A list of Conversation items. + */ +export interface ConversationItemList { + /** + * A list of conversation items. + */ + data: Array; + + /** + * The ID of the first item in the list. + */ + first_id: string; + + /** + * Whether there are more items available. + */ + has_more: boolean; + + /** + * The ID of the last item in the list. + */ + last_id: string; + + /** + * The type of object returned, must be `list`. + */ + object: 'list'; +} + +export interface ItemCreateParams { + /** + * Body param: The items to add to the conversation. You may add up to 20 items at + * a time. + */ + items: Array; + + /** + * Query param: Additional fields to include in the response. See the `include` + * parameter for + * [listing Conversation items above](https://platform.openai.com/docs/api-reference/conversations/list-items#conversations_list_items-include) + * for more information. + */ + include?: Array; +} + +export interface ItemRetrieveParams { + /** + * Path param: The ID of the conversation that contains the item. + */ + conversation_id: string; + + /** + * Query param: Additional fields to include in the response. See the `include` + * parameter for + * [listing Conversation items above](https://platform.openai.com/docs/api-reference/conversations/list-items#conversations_list_items-include) + * for more information. + */ + include?: Array; +} + +export interface ItemListParams extends ConversationCursorPageParams { + /** + * Specify additional output data to include in the model response. Currently + * supported values are: + * + * - `web_search_call.action.sources`: Include the sources of the web search tool + * call. + * - `code_interpreter_call.outputs`: Includes the outputs of python code execution + * in code interpreter tool call items. + * - `computer_call_output.output.image_url`: Include image urls from the computer + * call output. + * - `file_search_call.results`: Include the search results of the file search tool + * call. + * - `message.input_image.image_url`: Include image urls from the input message. + * - `message.output_text.logprobs`: Include logprobs with assistant messages. + * - `reasoning.encrypted_content`: Includes an encrypted version of reasoning + * tokens in reasoning item outputs. This enables reasoning items to be used in + * multi-turn conversations when using the Responses API statelessly (like when + * the `store` parameter is set to `false`, or when an organization is enrolled + * in the zero data retention program). + */ + include?: Array; + + /** + * The order to return the input items in. Default is `desc`. + * + * - `asc`: Return the input items in ascending order. + * - `desc`: Return the input items in descending order. + */ + order?: 'asc' | 'desc'; +} + +export interface ItemDeleteParams { + /** + * The ID of the conversation that contains the item. + */ + conversation_id: string; +} + +export declare namespace Items { + export { + type ConversationItem as ConversationItem, + type ConversationItemList as ConversationItemList, + type ConversationItemsPage as ConversationItemsPage, + type ItemCreateParams as ItemCreateParams, + type ItemRetrieveParams as ItemRetrieveParams, + type ItemListParams as ItemListParams, + type ItemDeleteParams as ItemDeleteParams, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/embeddings.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/embeddings.ts new file mode 100644 index 0000000000000000000000000000000000000000..7a66904f74eebe29881320b5918ac3660b93203f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/embeddings.ts @@ -0,0 +1,177 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../core/resource'; +import { APIPromise } from '../core/api-promise'; +import { RequestOptions } from '../internal/request-options'; +import { loggerFor, toFloat32Array } from '../internal/utils'; + +export class Embeddings extends APIResource { + /** + * Creates an embedding vector representing the input text. + * + * @example + * ```ts + * const createEmbeddingResponse = + * await client.embeddings.create({ + * input: 'The quick brown fox jumped over the lazy dog', + * model: 'text-embedding-3-small', + * }); + * ``` + */ + create(body: EmbeddingCreateParams, options?: RequestOptions): APIPromise { + const hasUserProvidedEncodingFormat = !!body.encoding_format; + // No encoding_format specified, defaulting to base64 for performance reasons + // See https://github.com/openai/openai-node/pull/1312 + let encoding_format: EmbeddingCreateParams['encoding_format'] = + hasUserProvidedEncodingFormat ? body.encoding_format : 'base64'; + + if (hasUserProvidedEncodingFormat) { + loggerFor(this._client).debug('embeddings/user defined encoding_format:', body.encoding_format); + } + + const response: APIPromise = this._client.post('/embeddings', { + body: { + ...body, + encoding_format: encoding_format as EmbeddingCreateParams['encoding_format'], + }, + ...options, + }); + + // if the user specified an encoding_format, return the response as-is + if (hasUserProvidedEncodingFormat) { + return response; + } + + // in this stage, we are sure the user did not specify an encoding_format + // and we defaulted to base64 for performance reasons + // we are sure then that the response is base64 encoded, let's decode it + // the returned result will be a float32 array since this is OpenAI API's default encoding + loggerFor(this._client).debug('embeddings/decoding base64 embeddings from base64'); + + return (response as APIPromise)._thenUnwrap((response) => { + if (response && response.data) { + response.data.forEach((embeddingBase64Obj) => { + const embeddingBase64Str = embeddingBase64Obj.embedding as unknown as string; + embeddingBase64Obj.embedding = toFloat32Array(embeddingBase64Str); + }); + } + + return response; + }); + } +} + +export interface CreateEmbeddingResponse { + /** + * The list of embeddings generated by the model. + */ + data: Array; + + /** + * The name of the model used to generate the embedding. + */ + model: string; + + /** + * The object type, which is always "list". + */ + object: 'list'; + + /** + * The usage information for the request. + */ + usage: CreateEmbeddingResponse.Usage; +} + +export namespace CreateEmbeddingResponse { + /** + * The usage information for the request. + */ + export interface Usage { + /** + * The number of tokens used by the prompt. + */ + prompt_tokens: number; + + /** + * The total number of tokens used by the request. + */ + total_tokens: number; + } +} + +/** + * Represents an embedding vector returned by embedding endpoint. + */ +export interface Embedding { + /** + * The embedding vector, which is a list of floats. The length of vector depends on + * the model as listed in the + * [embedding guide](https://platform.openai.com/docs/guides/embeddings). + */ + embedding: Array; + + /** + * The index of the embedding in the list of embeddings. + */ + index: number; + + /** + * The object type, which is always "embedding". + */ + object: 'embedding'; +} + +export type EmbeddingModel = 'text-embedding-ada-002' | 'text-embedding-3-small' | 'text-embedding-3-large'; + +export interface EmbeddingCreateParams { + /** + * Input text to embed, encoded as a string or array of tokens. To embed multiple + * inputs in a single request, pass an array of strings or array of token arrays. + * The input must not exceed the max input tokens for the model (8192 tokens for + * all embedding models), cannot be an empty string, and any array must be 2048 + * dimensions or less. + * [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) + * for counting tokens. In addition to the per-input token limit, all embedding + * models enforce a maximum of 300,000 tokens summed across all inputs in a single + * request. + */ + input: string | Array | Array | Array>; + + /** + * ID of the model to use. You can use the + * [List models](https://platform.openai.com/docs/api-reference/models/list) API to + * see all of your available models, or see our + * [Model overview](https://platform.openai.com/docs/models) for descriptions of + * them. + */ + model: (string & {}) | EmbeddingModel; + + /** + * The number of dimensions the resulting output embeddings should have. Only + * supported in `text-embedding-3` and later models. + */ + dimensions?: number; + + /** + * The format to return the embeddings in. Can be either `float` or + * [`base64`](https://pypi.org/project/pybase64/). + */ + encoding_format?: 'float' | 'base64'; + + /** + * A unique identifier representing your end-user, which can help OpenAI to monitor + * and detect abuse. + * [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). + */ + user?: string; +} + +export declare namespace Embeddings { + export { + type CreateEmbeddingResponse as CreateEmbeddingResponse, + type Embedding as Embedding, + type EmbeddingModel as EmbeddingModel, + type EmbeddingCreateParams as EmbeddingCreateParams, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/evals.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/evals.ts new file mode 100644 index 0000000000000000000000000000000000000000..b611710e16c69582e2f5532068a0ad775279497e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/evals.ts @@ -0,0 +1,3 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export * from './evals/index'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/evals/evals.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/evals/evals.ts new file mode 100644 index 0000000000000000000000000000000000000000..56109fa11e986a0bb3e9448bc2ea314607adaba9 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/evals/evals.ts @@ -0,0 +1,928 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../core/resource'; +import * as Shared from '../shared'; +import * as GraderModelsAPI from '../graders/grader-models'; +import * as ResponsesAPI from '../responses/responses'; +import * as RunsAPI from './runs/runs'; +import { + CreateEvalCompletionsRunDataSource, + CreateEvalJSONLRunDataSource, + EvalAPIError, + RunCancelParams, + RunCancelResponse, + RunCreateParams, + RunCreateResponse, + RunDeleteParams, + RunDeleteResponse, + RunListParams, + RunListResponse, + RunListResponsesPage, + RunRetrieveParams, + RunRetrieveResponse, + Runs, +} from './runs/runs'; +import { APIPromise } from '../../core/api-promise'; +import { CursorPage, type CursorPageParams, PagePromise } from '../../core/pagination'; +import { RequestOptions } from '../../internal/request-options'; +import { path } from '../../internal/utils/path'; + +export class Evals extends APIResource { + runs: RunsAPI.Runs = new RunsAPI.Runs(this._client); + + /** + * Create the structure of an evaluation that can be used to test a model's + * performance. An evaluation is a set of testing criteria and the config for a + * data source, which dictates the schema of the data used in the evaluation. After + * creating an evaluation, you can run it on different models and model parameters. + * We support several types of graders and datasources. For more information, see + * the [Evals guide](https://platform.openai.com/docs/guides/evals). + */ + create(body: EvalCreateParams, options?: RequestOptions): APIPromise { + return this._client.post('/evals', { body, ...options }); + } + + /** + * Get an evaluation by ID. + */ + retrieve(evalID: string, options?: RequestOptions): APIPromise { + return this._client.get(path`/evals/${evalID}`, options); + } + + /** + * Update certain properties of an evaluation. + */ + update(evalID: string, body: EvalUpdateParams, options?: RequestOptions): APIPromise { + return this._client.post(path`/evals/${evalID}`, { body, ...options }); + } + + /** + * List evaluations for a project. + */ + list( + query: EvalListParams | null | undefined = {}, + options?: RequestOptions, + ): PagePromise { + return this._client.getAPIList('/evals', CursorPage, { query, ...options }); + } + + /** + * Delete an evaluation. + */ + delete(evalID: string, options?: RequestOptions): APIPromise { + return this._client.delete(path`/evals/${evalID}`, options); + } +} + +export type EvalListResponsesPage = CursorPage; + +/** + * A CustomDataSourceConfig which specifies the schema of your `item` and + * optionally `sample` namespaces. The response schema defines the shape of the + * data that will be: + * + * - Used to define your testing criteria and + * - What data is required when creating a run + */ +export interface EvalCustomDataSourceConfig { + /** + * The json schema for the run data source items. Learn how to build JSON schemas + * [here](https://json-schema.org/). + */ + schema: { [key: string]: unknown }; + + /** + * The type of data source. Always `custom`. + */ + type: 'custom'; +} + +/** + * @deprecated Deprecated in favor of LogsDataSourceConfig. + */ +export interface EvalStoredCompletionsDataSourceConfig { + /** + * The json schema for the run data source items. Learn how to build JSON schemas + * [here](https://json-schema.org/). + */ + schema: { [key: string]: unknown }; + + /** + * The type of data source. Always `stored_completions`. + */ + type: 'stored_completions'; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; +} + +/** + * An Eval object with a data source config and testing criteria. An Eval + * represents a task to be done for your LLM integration. Like: + * + * - Improve the quality of my chatbot + * - See how well my chatbot handles customer support + * - Check if o4-mini is better at my usecase than gpt-4o + */ +export interface EvalCreateResponse { + /** + * Unique identifier for the evaluation. + */ + id: string; + + /** + * The Unix timestamp (in seconds) for when the eval was created. + */ + created_at: number; + + /** + * Configuration of data sources used in runs of the evaluation. + */ + data_source_config: + | EvalCustomDataSourceConfig + | EvalCreateResponse.Logs + | EvalStoredCompletionsDataSourceConfig; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata: Shared.Metadata | null; + + /** + * The name of the evaluation. + */ + name: string; + + /** + * The object type. + */ + object: 'eval'; + + /** + * A list of testing criteria. + */ + testing_criteria: Array< + | GraderModelsAPI.LabelModelGrader + | GraderModelsAPI.StringCheckGrader + | EvalCreateResponse.EvalGraderTextSimilarity + | EvalCreateResponse.EvalGraderPython + | EvalCreateResponse.EvalGraderScoreModel + >; +} + +export namespace EvalCreateResponse { + /** + * A LogsDataSourceConfig which specifies the metadata property of your logs query. + * This is usually metadata like `usecase=chatbot` or `prompt-version=v2`, etc. The + * schema returned by this data source config is used to defined what variables are + * available in your evals. `item` and `sample` are both defined when using this + * data source config. + */ + export interface Logs { + /** + * The json schema for the run data source items. Learn how to build JSON schemas + * [here](https://json-schema.org/). + */ + schema: { [key: string]: unknown }; + + /** + * The type of data source. Always `logs`. + */ + type: 'logs'; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; + } + + /** + * A TextSimilarityGrader object which grades text based on similarity metrics. + */ + export interface EvalGraderTextSimilarity extends GraderModelsAPI.TextSimilarityGrader { + /** + * The threshold for the score. + */ + pass_threshold: number; + } + + /** + * A PythonGrader object that runs a python script on the input. + */ + export interface EvalGraderPython extends GraderModelsAPI.PythonGrader { + /** + * The threshold for the score. + */ + pass_threshold?: number; + } + + /** + * A ScoreModelGrader object that uses a model to assign a score to the input. + */ + export interface EvalGraderScoreModel extends GraderModelsAPI.ScoreModelGrader { + /** + * The threshold for the score. + */ + pass_threshold?: number; + } +} + +/** + * An Eval object with a data source config and testing criteria. An Eval + * represents a task to be done for your LLM integration. Like: + * + * - Improve the quality of my chatbot + * - See how well my chatbot handles customer support + * - Check if o4-mini is better at my usecase than gpt-4o + */ +export interface EvalRetrieveResponse { + /** + * Unique identifier for the evaluation. + */ + id: string; + + /** + * The Unix timestamp (in seconds) for when the eval was created. + */ + created_at: number; + + /** + * Configuration of data sources used in runs of the evaluation. + */ + data_source_config: + | EvalCustomDataSourceConfig + | EvalRetrieveResponse.Logs + | EvalStoredCompletionsDataSourceConfig; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata: Shared.Metadata | null; + + /** + * The name of the evaluation. + */ + name: string; + + /** + * The object type. + */ + object: 'eval'; + + /** + * A list of testing criteria. + */ + testing_criteria: Array< + | GraderModelsAPI.LabelModelGrader + | GraderModelsAPI.StringCheckGrader + | EvalRetrieveResponse.EvalGraderTextSimilarity + | EvalRetrieveResponse.EvalGraderPython + | EvalRetrieveResponse.EvalGraderScoreModel + >; +} + +export namespace EvalRetrieveResponse { + /** + * A LogsDataSourceConfig which specifies the metadata property of your logs query. + * This is usually metadata like `usecase=chatbot` or `prompt-version=v2`, etc. The + * schema returned by this data source config is used to defined what variables are + * available in your evals. `item` and `sample` are both defined when using this + * data source config. + */ + export interface Logs { + /** + * The json schema for the run data source items. Learn how to build JSON schemas + * [here](https://json-schema.org/). + */ + schema: { [key: string]: unknown }; + + /** + * The type of data source. Always `logs`. + */ + type: 'logs'; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; + } + + /** + * A TextSimilarityGrader object which grades text based on similarity metrics. + */ + export interface EvalGraderTextSimilarity extends GraderModelsAPI.TextSimilarityGrader { + /** + * The threshold for the score. + */ + pass_threshold: number; + } + + /** + * A PythonGrader object that runs a python script on the input. + */ + export interface EvalGraderPython extends GraderModelsAPI.PythonGrader { + /** + * The threshold for the score. + */ + pass_threshold?: number; + } + + /** + * A ScoreModelGrader object that uses a model to assign a score to the input. + */ + export interface EvalGraderScoreModel extends GraderModelsAPI.ScoreModelGrader { + /** + * The threshold for the score. + */ + pass_threshold?: number; + } +} + +/** + * An Eval object with a data source config and testing criteria. An Eval + * represents a task to be done for your LLM integration. Like: + * + * - Improve the quality of my chatbot + * - See how well my chatbot handles customer support + * - Check if o4-mini is better at my usecase than gpt-4o + */ +export interface EvalUpdateResponse { + /** + * Unique identifier for the evaluation. + */ + id: string; + + /** + * The Unix timestamp (in seconds) for when the eval was created. + */ + created_at: number; + + /** + * Configuration of data sources used in runs of the evaluation. + */ + data_source_config: + | EvalCustomDataSourceConfig + | EvalUpdateResponse.Logs + | EvalStoredCompletionsDataSourceConfig; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata: Shared.Metadata | null; + + /** + * The name of the evaluation. + */ + name: string; + + /** + * The object type. + */ + object: 'eval'; + + /** + * A list of testing criteria. + */ + testing_criteria: Array< + | GraderModelsAPI.LabelModelGrader + | GraderModelsAPI.StringCheckGrader + | EvalUpdateResponse.EvalGraderTextSimilarity + | EvalUpdateResponse.EvalGraderPython + | EvalUpdateResponse.EvalGraderScoreModel + >; +} + +export namespace EvalUpdateResponse { + /** + * A LogsDataSourceConfig which specifies the metadata property of your logs query. + * This is usually metadata like `usecase=chatbot` or `prompt-version=v2`, etc. The + * schema returned by this data source config is used to defined what variables are + * available in your evals. `item` and `sample` are both defined when using this + * data source config. + */ + export interface Logs { + /** + * The json schema for the run data source items. Learn how to build JSON schemas + * [here](https://json-schema.org/). + */ + schema: { [key: string]: unknown }; + + /** + * The type of data source. Always `logs`. + */ + type: 'logs'; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; + } + + /** + * A TextSimilarityGrader object which grades text based on similarity metrics. + */ + export interface EvalGraderTextSimilarity extends GraderModelsAPI.TextSimilarityGrader { + /** + * The threshold for the score. + */ + pass_threshold: number; + } + + /** + * A PythonGrader object that runs a python script on the input. + */ + export interface EvalGraderPython extends GraderModelsAPI.PythonGrader { + /** + * The threshold for the score. + */ + pass_threshold?: number; + } + + /** + * A ScoreModelGrader object that uses a model to assign a score to the input. + */ + export interface EvalGraderScoreModel extends GraderModelsAPI.ScoreModelGrader { + /** + * The threshold for the score. + */ + pass_threshold?: number; + } +} + +/** + * An Eval object with a data source config and testing criteria. An Eval + * represents a task to be done for your LLM integration. Like: + * + * - Improve the quality of my chatbot + * - See how well my chatbot handles customer support + * - Check if o4-mini is better at my usecase than gpt-4o + */ +export interface EvalListResponse { + /** + * Unique identifier for the evaluation. + */ + id: string; + + /** + * The Unix timestamp (in seconds) for when the eval was created. + */ + created_at: number; + + /** + * Configuration of data sources used in runs of the evaluation. + */ + data_source_config: + | EvalCustomDataSourceConfig + | EvalListResponse.Logs + | EvalStoredCompletionsDataSourceConfig; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata: Shared.Metadata | null; + + /** + * The name of the evaluation. + */ + name: string; + + /** + * The object type. + */ + object: 'eval'; + + /** + * A list of testing criteria. + */ + testing_criteria: Array< + | GraderModelsAPI.LabelModelGrader + | GraderModelsAPI.StringCheckGrader + | EvalListResponse.EvalGraderTextSimilarity + | EvalListResponse.EvalGraderPython + | EvalListResponse.EvalGraderScoreModel + >; +} + +export namespace EvalListResponse { + /** + * A LogsDataSourceConfig which specifies the metadata property of your logs query. + * This is usually metadata like `usecase=chatbot` or `prompt-version=v2`, etc. The + * schema returned by this data source config is used to defined what variables are + * available in your evals. `item` and `sample` are both defined when using this + * data source config. + */ + export interface Logs { + /** + * The json schema for the run data source items. Learn how to build JSON schemas + * [here](https://json-schema.org/). + */ + schema: { [key: string]: unknown }; + + /** + * The type of data source. Always `logs`. + */ + type: 'logs'; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; + } + + /** + * A TextSimilarityGrader object which grades text based on similarity metrics. + */ + export interface EvalGraderTextSimilarity extends GraderModelsAPI.TextSimilarityGrader { + /** + * The threshold for the score. + */ + pass_threshold: number; + } + + /** + * A PythonGrader object that runs a python script on the input. + */ + export interface EvalGraderPython extends GraderModelsAPI.PythonGrader { + /** + * The threshold for the score. + */ + pass_threshold?: number; + } + + /** + * A ScoreModelGrader object that uses a model to assign a score to the input. + */ + export interface EvalGraderScoreModel extends GraderModelsAPI.ScoreModelGrader { + /** + * The threshold for the score. + */ + pass_threshold?: number; + } +} + +export interface EvalDeleteResponse { + deleted: boolean; + + eval_id: string; + + object: string; +} + +export interface EvalCreateParams { + /** + * The configuration for the data source used for the evaluation runs. Dictates the + * schema of the data used in the evaluation. + */ + data_source_config: EvalCreateParams.Custom | EvalCreateParams.Logs | EvalCreateParams.StoredCompletions; + + /** + * A list of graders for all eval runs in this group. Graders can reference + * variables in the data source using double curly braces notation, like + * `{{item.variable_name}}`. To reference the model's output, use the `sample` + * namespace (ie, `{{sample.output_text}}`). + */ + testing_criteria: Array< + | EvalCreateParams.LabelModel + | GraderModelsAPI.StringCheckGrader + | EvalCreateParams.TextSimilarity + | EvalCreateParams.Python + | EvalCreateParams.ScoreModel + >; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; + + /** + * The name of the evaluation. + */ + name?: string; +} + +export namespace EvalCreateParams { + /** + * A CustomDataSourceConfig object that defines the schema for the data source used + * for the evaluation runs. This schema is used to define the shape of the data + * that will be: + * + * - Used to define your testing criteria and + * - What data is required when creating a run + */ + export interface Custom { + /** + * The json schema for each row in the data source. + */ + item_schema: { [key: string]: unknown }; + + /** + * The type of data source. Always `custom`. + */ + type: 'custom'; + + /** + * Whether the eval should expect you to populate the sample namespace (ie, by + * generating responses off of your data source) + */ + include_sample_schema?: boolean; + } + + /** + * A data source config which specifies the metadata property of your logs query. + * This is usually metadata like `usecase=chatbot` or `prompt-version=v2`, etc. + */ + export interface Logs { + /** + * The type of data source. Always `logs`. + */ + type: 'logs'; + + /** + * Metadata filters for the logs data source. + */ + metadata?: { [key: string]: unknown }; + } + + /** + * @deprecated Deprecated in favor of LogsDataSourceConfig. + */ + export interface StoredCompletions { + /** + * The type of data source. Always `stored_completions`. + */ + type: 'stored_completions'; + + /** + * Metadata filters for the stored completions data source. + */ + metadata?: { [key: string]: unknown }; + } + + /** + * A LabelModelGrader object which uses a model to assign labels to each item in + * the evaluation. + */ + export interface LabelModel { + /** + * A list of chat messages forming the prompt or context. May include variable + * references to the `item` namespace, ie {{item.name}}. + */ + input: Array; + + /** + * The labels to classify to each item in the evaluation. + */ + labels: Array; + + /** + * The model to use for the evaluation. Must support structured outputs. + */ + model: string; + + /** + * The name of the grader. + */ + name: string; + + /** + * The labels that indicate a passing result. Must be a subset of labels. + */ + passing_labels: Array; + + /** + * The object type, which is always `label_model`. + */ + type: 'label_model'; + } + + export namespace LabelModel { + export interface SimpleInputMessage { + /** + * The content of the message. + */ + content: string; + + /** + * The role of the message (e.g. "system", "assistant", "user"). + */ + role: string; + } + + /** + * A message input to the model with a role indicating instruction following + * hierarchy. Instructions given with the `developer` or `system` role take + * precedence over instructions given with the `user` role. Messages with the + * `assistant` role are presumed to have been generated by the model in previous + * interactions. + */ + export interface EvalItem { + /** + * Inputs to the model - can contain template strings. + */ + content: + | string + | ResponsesAPI.ResponseInputText + | EvalItem.OutputText + | EvalItem.InputImage + | Array; + + /** + * The role of the message input. One of `user`, `assistant`, `system`, or + * `developer`. + */ + role: 'user' | 'assistant' | 'system' | 'developer'; + + /** + * The type of the message input. Always `message`. + */ + type?: 'message'; + } + + export namespace EvalItem { + /** + * A text output from the model. + */ + export interface OutputText { + /** + * The text output from the model. + */ + text: string; + + /** + * The type of the output text. Always `output_text`. + */ + type: 'output_text'; + } + + /** + * An image input to the model. + */ + export interface InputImage { + /** + * The URL of the image input. + */ + image_url: string; + + /** + * The type of the image input. Always `input_image`. + */ + type: 'input_image'; + + /** + * The detail level of the image to be sent to the model. One of `high`, `low`, or + * `auto`. Defaults to `auto`. + */ + detail?: string; + } + } + } + + /** + * A TextSimilarityGrader object which grades text based on similarity metrics. + */ + export interface TextSimilarity extends GraderModelsAPI.TextSimilarityGrader { + /** + * The threshold for the score. + */ + pass_threshold: number; + } + + /** + * A PythonGrader object that runs a python script on the input. + */ + export interface Python extends GraderModelsAPI.PythonGrader { + /** + * The threshold for the score. + */ + pass_threshold?: number; + } + + /** + * A ScoreModelGrader object that uses a model to assign a score to the input. + */ + export interface ScoreModel extends GraderModelsAPI.ScoreModelGrader { + /** + * The threshold for the score. + */ + pass_threshold?: number; + } +} + +export interface EvalUpdateParams { + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; + + /** + * Rename the evaluation. + */ + name?: string; +} + +export interface EvalListParams extends CursorPageParams { + /** + * Sort order for evals by timestamp. Use `asc` for ascending order or `desc` for + * descending order. + */ + order?: 'asc' | 'desc'; + + /** + * Evals can be ordered by creation time or last updated time. Use `created_at` for + * creation time or `updated_at` for last updated time. + */ + order_by?: 'created_at' | 'updated_at'; +} + +Evals.Runs = Runs; + +export declare namespace Evals { + export { + type EvalCustomDataSourceConfig as EvalCustomDataSourceConfig, + type EvalStoredCompletionsDataSourceConfig as EvalStoredCompletionsDataSourceConfig, + type EvalCreateResponse as EvalCreateResponse, + type EvalRetrieveResponse as EvalRetrieveResponse, + type EvalUpdateResponse as EvalUpdateResponse, + type EvalListResponse as EvalListResponse, + type EvalDeleteResponse as EvalDeleteResponse, + type EvalListResponsesPage as EvalListResponsesPage, + type EvalCreateParams as EvalCreateParams, + type EvalUpdateParams as EvalUpdateParams, + type EvalListParams as EvalListParams, + }; + + export { + Runs as Runs, + type CreateEvalCompletionsRunDataSource as CreateEvalCompletionsRunDataSource, + type CreateEvalJSONLRunDataSource as CreateEvalJSONLRunDataSource, + type EvalAPIError as EvalAPIError, + type RunCreateResponse as RunCreateResponse, + type RunRetrieveResponse as RunRetrieveResponse, + type RunListResponse as RunListResponse, + type RunDeleteResponse as RunDeleteResponse, + type RunCancelResponse as RunCancelResponse, + type RunListResponsesPage as RunListResponsesPage, + type RunCreateParams as RunCreateParams, + type RunRetrieveParams as RunRetrieveParams, + type RunListParams as RunListParams, + type RunDeleteParams as RunDeleteParams, + type RunCancelParams as RunCancelParams, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/evals/index.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/evals/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..cd74e0edc92108355ee049044d45a5a1cb7b55d3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/evals/index.ts @@ -0,0 +1,33 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export { + Evals, + type EvalCustomDataSourceConfig, + type EvalStoredCompletionsDataSourceConfig, + type EvalCreateResponse, + type EvalRetrieveResponse, + type EvalUpdateResponse, + type EvalListResponse, + type EvalDeleteResponse, + type EvalCreateParams, + type EvalUpdateParams, + type EvalListParams, + type EvalListResponsesPage, +} from './evals'; +export { + Runs, + type CreateEvalCompletionsRunDataSource, + type CreateEvalJSONLRunDataSource, + type EvalAPIError, + type RunCreateResponse, + type RunRetrieveResponse, + type RunListResponse, + type RunDeleteResponse, + type RunCancelResponse, + type RunCreateParams, + type RunRetrieveParams, + type RunListParams, + type RunDeleteParams, + type RunCancelParams, + type RunListResponsesPage, +} from './runs/index'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/evals/runs.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/evals/runs.ts new file mode 100644 index 0000000000000000000000000000000000000000..a3cc2bc7f368c9e74629deeeca3dadf838472172 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/evals/runs.ts @@ -0,0 +1,3 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export * from './runs/index'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/evals/runs/index.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/evals/runs/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..e51e04c11e40f95aa2d9a890452df20f3df1faec --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/evals/runs/index.ts @@ -0,0 +1,27 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export { + OutputItems, + type OutputItemRetrieveResponse, + type OutputItemListResponse, + type OutputItemRetrieveParams, + type OutputItemListParams, + type OutputItemListResponsesPage, +} from './output-items'; +export { + Runs, + type CreateEvalCompletionsRunDataSource, + type CreateEvalJSONLRunDataSource, + type EvalAPIError, + type RunCreateResponse, + type RunRetrieveResponse, + type RunListResponse, + type RunDeleteResponse, + type RunCancelResponse, + type RunCreateParams, + type RunRetrieveParams, + type RunListParams, + type RunDeleteParams, + type RunCancelParams, + type RunListResponsesPage, +} from './runs'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/evals/runs/output-items.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/evals/runs/output-items.ts new file mode 100644 index 0000000000000000000000000000000000000000..1aded2f91ff526a06bbdd317c9ce18bdefeb32d7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/evals/runs/output-items.ts @@ -0,0 +1,413 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../../core/resource'; +import * as RunsAPI from './runs'; +import { APIPromise } from '../../../core/api-promise'; +import { CursorPage, type CursorPageParams, PagePromise } from '../../../core/pagination'; +import { RequestOptions } from '../../../internal/request-options'; +import { path } from '../../../internal/utils/path'; + +export class OutputItems extends APIResource { + /** + * Get an evaluation run output item by ID. + */ + retrieve( + outputItemID: string, + params: OutputItemRetrieveParams, + options?: RequestOptions, + ): APIPromise { + const { eval_id, run_id } = params; + return this._client.get(path`/evals/${eval_id}/runs/${run_id}/output_items/${outputItemID}`, options); + } + + /** + * Get a list of output items for an evaluation run. + */ + list( + runID: string, + params: OutputItemListParams, + options?: RequestOptions, + ): PagePromise { + const { eval_id, ...query } = params; + return this._client.getAPIList( + path`/evals/${eval_id}/runs/${runID}/output_items`, + CursorPage, + { query, ...options }, + ); + } +} + +export type OutputItemListResponsesPage = CursorPage; + +/** + * A schema representing an evaluation run output item. + */ +export interface OutputItemRetrieveResponse { + /** + * Unique identifier for the evaluation run output item. + */ + id: string; + + /** + * Unix timestamp (in seconds) when the evaluation run was created. + */ + created_at: number; + + /** + * Details of the input data source item. + */ + datasource_item: { [key: string]: unknown }; + + /** + * The identifier for the data source item. + */ + datasource_item_id: number; + + /** + * The identifier of the evaluation group. + */ + eval_id: string; + + /** + * The type of the object. Always "eval.run.output_item". + */ + object: 'eval.run.output_item'; + + /** + * A list of results from the evaluation run. + */ + results: Array<{ [key: string]: unknown }>; + + /** + * The identifier of the evaluation run associated with this output item. + */ + run_id: string; + + /** + * A sample containing the input and output of the evaluation run. + */ + sample: OutputItemRetrieveResponse.Sample; + + /** + * The status of the evaluation run. + */ + status: string; +} + +export namespace OutputItemRetrieveResponse { + /** + * A sample containing the input and output of the evaluation run. + */ + export interface Sample { + /** + * An object representing an error response from the Eval API. + */ + error: RunsAPI.EvalAPIError; + + /** + * The reason why the sample generation was finished. + */ + finish_reason: string; + + /** + * An array of input messages. + */ + input: Array; + + /** + * The maximum number of tokens allowed for completion. + */ + max_completion_tokens: number; + + /** + * The model used for generating the sample. + */ + model: string; + + /** + * An array of output messages. + */ + output: Array; + + /** + * The seed used for generating the sample. + */ + seed: number; + + /** + * The sampling temperature used. + */ + temperature: number; + + /** + * The top_p value used for sampling. + */ + top_p: number; + + /** + * Token usage details for the sample. + */ + usage: Sample.Usage; + } + + export namespace Sample { + /** + * An input message. + */ + export interface Input { + /** + * The content of the message. + */ + content: string; + + /** + * The role of the message sender (e.g., system, user, developer). + */ + role: string; + } + + export interface Output { + /** + * The content of the message. + */ + content?: string; + + /** + * The role of the message (e.g. "system", "assistant", "user"). + */ + role?: string; + } + + /** + * Token usage details for the sample. + */ + export interface Usage { + /** + * The number of tokens retrieved from cache. + */ + cached_tokens: number; + + /** + * The number of completion tokens generated. + */ + completion_tokens: number; + + /** + * The number of prompt tokens used. + */ + prompt_tokens: number; + + /** + * The total number of tokens used. + */ + total_tokens: number; + } + } +} + +/** + * A schema representing an evaluation run output item. + */ +export interface OutputItemListResponse { + /** + * Unique identifier for the evaluation run output item. + */ + id: string; + + /** + * Unix timestamp (in seconds) when the evaluation run was created. + */ + created_at: number; + + /** + * Details of the input data source item. + */ + datasource_item: { [key: string]: unknown }; + + /** + * The identifier for the data source item. + */ + datasource_item_id: number; + + /** + * The identifier of the evaluation group. + */ + eval_id: string; + + /** + * The type of the object. Always "eval.run.output_item". + */ + object: 'eval.run.output_item'; + + /** + * A list of results from the evaluation run. + */ + results: Array<{ [key: string]: unknown }>; + + /** + * The identifier of the evaluation run associated with this output item. + */ + run_id: string; + + /** + * A sample containing the input and output of the evaluation run. + */ + sample: OutputItemListResponse.Sample; + + /** + * The status of the evaluation run. + */ + status: string; +} + +export namespace OutputItemListResponse { + /** + * A sample containing the input and output of the evaluation run. + */ + export interface Sample { + /** + * An object representing an error response from the Eval API. + */ + error: RunsAPI.EvalAPIError; + + /** + * The reason why the sample generation was finished. + */ + finish_reason: string; + + /** + * An array of input messages. + */ + input: Array; + + /** + * The maximum number of tokens allowed for completion. + */ + max_completion_tokens: number; + + /** + * The model used for generating the sample. + */ + model: string; + + /** + * An array of output messages. + */ + output: Array; + + /** + * The seed used for generating the sample. + */ + seed: number; + + /** + * The sampling temperature used. + */ + temperature: number; + + /** + * The top_p value used for sampling. + */ + top_p: number; + + /** + * Token usage details for the sample. + */ + usage: Sample.Usage; + } + + export namespace Sample { + /** + * An input message. + */ + export interface Input { + /** + * The content of the message. + */ + content: string; + + /** + * The role of the message sender (e.g., system, user, developer). + */ + role: string; + } + + export interface Output { + /** + * The content of the message. + */ + content?: string; + + /** + * The role of the message (e.g. "system", "assistant", "user"). + */ + role?: string; + } + + /** + * Token usage details for the sample. + */ + export interface Usage { + /** + * The number of tokens retrieved from cache. + */ + cached_tokens: number; + + /** + * The number of completion tokens generated. + */ + completion_tokens: number; + + /** + * The number of prompt tokens used. + */ + prompt_tokens: number; + + /** + * The total number of tokens used. + */ + total_tokens: number; + } + } +} + +export interface OutputItemRetrieveParams { + /** + * The ID of the evaluation to retrieve runs for. + */ + eval_id: string; + + /** + * The ID of the run to retrieve. + */ + run_id: string; +} + +export interface OutputItemListParams extends CursorPageParams { + /** + * Path param: The ID of the evaluation to retrieve runs for. + */ + eval_id: string; + + /** + * Query param: Sort order for output items by timestamp. Use `asc` for ascending + * order or `desc` for descending order. Defaults to `asc`. + */ + order?: 'asc' | 'desc'; + + /** + * Query param: Filter output items by status. Use `failed` to filter by failed + * output items or `pass` to filter by passed output items. + */ + status?: 'fail' | 'pass'; +} + +export declare namespace OutputItems { + export { + type OutputItemRetrieveResponse as OutputItemRetrieveResponse, + type OutputItemListResponse as OutputItemListResponse, + type OutputItemListResponsesPage as OutputItemListResponsesPage, + type OutputItemRetrieveParams as OutputItemRetrieveParams, + type OutputItemListParams as OutputItemListParams, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/evals/runs/runs.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/evals/runs/runs.ts new file mode 100644 index 0000000000000000000000000000000000000000..d1716d9041ebb87f06416de76d670a87cca9183c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/evals/runs/runs.ts @@ -0,0 +1,2699 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../../core/resource'; +import * as Shared from '../../shared'; +import * as ResponsesAPI from '../../responses/responses'; +import * as CompletionsAPI from '../../chat/completions/completions'; +import * as OutputItemsAPI from './output-items'; +import { + OutputItemListParams, + OutputItemListResponse, + OutputItemListResponsesPage, + OutputItemRetrieveParams, + OutputItemRetrieveResponse, + OutputItems, +} from './output-items'; +import { APIPromise } from '../../../core/api-promise'; +import { CursorPage, type CursorPageParams, PagePromise } from '../../../core/pagination'; +import { RequestOptions } from '../../../internal/request-options'; +import { path } from '../../../internal/utils/path'; + +export class Runs extends APIResource { + outputItems: OutputItemsAPI.OutputItems = new OutputItemsAPI.OutputItems(this._client); + + /** + * Kicks off a new run for a given evaluation, specifying the data source, and what + * model configuration to use to test. The datasource will be validated against the + * schema specified in the config of the evaluation. + */ + create(evalID: string, body: RunCreateParams, options?: RequestOptions): APIPromise { + return this._client.post(path`/evals/${evalID}/runs`, { body, ...options }); + } + + /** + * Get an evaluation run by ID. + */ + retrieve( + runID: string, + params: RunRetrieveParams, + options?: RequestOptions, + ): APIPromise { + const { eval_id } = params; + return this._client.get(path`/evals/${eval_id}/runs/${runID}`, options); + } + + /** + * Get a list of runs for an evaluation. + */ + list( + evalID: string, + query: RunListParams | null | undefined = {}, + options?: RequestOptions, + ): PagePromise { + return this._client.getAPIList(path`/evals/${evalID}/runs`, CursorPage, { + query, + ...options, + }); + } + + /** + * Delete an eval run. + */ + delete(runID: string, params: RunDeleteParams, options?: RequestOptions): APIPromise { + const { eval_id } = params; + return this._client.delete(path`/evals/${eval_id}/runs/${runID}`, options); + } + + /** + * Cancel an ongoing evaluation run. + */ + cancel(runID: string, params: RunCancelParams, options?: RequestOptions): APIPromise { + const { eval_id } = params; + return this._client.post(path`/evals/${eval_id}/runs/${runID}`, options); + } +} + +export type RunListResponsesPage = CursorPage; + +/** + * A CompletionsRunDataSource object describing a model sampling configuration. + */ +export interface CreateEvalCompletionsRunDataSource { + /** + * Determines what populates the `item` namespace in this run's data source. + */ + source: + | CreateEvalCompletionsRunDataSource.FileContent + | CreateEvalCompletionsRunDataSource.FileID + | CreateEvalCompletionsRunDataSource.StoredCompletions; + + /** + * The type of run data source. Always `completions`. + */ + type: 'completions'; + + /** + * Used when sampling from a model. Dictates the structure of the messages passed + * into the model. Can either be a reference to a prebuilt trajectory (ie, + * `item.input_trajectory`), or a template with variable references to the `item` + * namespace. + */ + input_messages?: + | CreateEvalCompletionsRunDataSource.Template + | CreateEvalCompletionsRunDataSource.ItemReference; + + /** + * The name of the model to use for generating completions (e.g. "o3-mini"). + */ + model?: string; + + sampling_params?: CreateEvalCompletionsRunDataSource.SamplingParams; +} + +export namespace CreateEvalCompletionsRunDataSource { + export interface FileContent { + /** + * The content of the jsonl file. + */ + content: Array; + + /** + * The type of jsonl source. Always `file_content`. + */ + type: 'file_content'; + } + + export namespace FileContent { + export interface Content { + item: { [key: string]: unknown }; + + sample?: { [key: string]: unknown }; + } + } + + export interface FileID { + /** + * The identifier of the file. + */ + id: string; + + /** + * The type of jsonl source. Always `file_id`. + */ + type: 'file_id'; + } + + /** + * A StoredCompletionsRunDataSource configuration describing a set of filters + */ + export interface StoredCompletions { + /** + * The type of source. Always `stored_completions`. + */ + type: 'stored_completions'; + + /** + * An optional Unix timestamp to filter items created after this time. + */ + created_after?: number | null; + + /** + * An optional Unix timestamp to filter items created before this time. + */ + created_before?: number | null; + + /** + * An optional maximum number of items to return. + */ + limit?: number | null; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; + + /** + * An optional model to filter by (e.g., 'gpt-4o'). + */ + model?: string | null; + } + + export interface Template { + /** + * A list of chat messages forming the prompt or context. May include variable + * references to the `item` namespace, ie {{item.name}}. + */ + template: Array; + + /** + * The type of input messages. Always `template`. + */ + type: 'template'; + } + + export namespace Template { + /** + * A message input to the model with a role indicating instruction following + * hierarchy. Instructions given with the `developer` or `system` role take + * precedence over instructions given with the `user` role. Messages with the + * `assistant` role are presumed to have been generated by the model in previous + * interactions. + */ + export interface EvalItem { + /** + * Inputs to the model - can contain template strings. + */ + content: + | string + | ResponsesAPI.ResponseInputText + | EvalItem.OutputText + | EvalItem.InputImage + | Array; + + /** + * The role of the message input. One of `user`, `assistant`, `system`, or + * `developer`. + */ + role: 'user' | 'assistant' | 'system' | 'developer'; + + /** + * The type of the message input. Always `message`. + */ + type?: 'message'; + } + + export namespace EvalItem { + /** + * A text output from the model. + */ + export interface OutputText { + /** + * The text output from the model. + */ + text: string; + + /** + * The type of the output text. Always `output_text`. + */ + type: 'output_text'; + } + + /** + * An image input to the model. + */ + export interface InputImage { + /** + * The URL of the image input. + */ + image_url: string; + + /** + * The type of the image input. Always `input_image`. + */ + type: 'input_image'; + + /** + * The detail level of the image to be sent to the model. One of `high`, `low`, or + * `auto`. Defaults to `auto`. + */ + detail?: string; + } + } + } + + export interface ItemReference { + /** + * A reference to a variable in the `item` namespace. Ie, "item.input_trajectory" + */ + item_reference: string; + + /** + * The type of input messages. Always `item_reference`. + */ + type: 'item_reference'; + } + + export interface SamplingParams { + /** + * The maximum number of tokens in the generated output. + */ + max_completion_tokens?: number; + + /** + * An object specifying the format that the model must output. + * + * Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + * Outputs which ensures the model will match your supplied JSON schema. Learn more + * in the + * [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + * + * Setting to `{ "type": "json_object" }` enables the older JSON mode, which + * ensures the message the model generates is valid JSON. Using `json_schema` is + * preferred for models that support it. + */ + response_format?: + | Shared.ResponseFormatText + | Shared.ResponseFormatJSONSchema + | Shared.ResponseFormatJSONObject; + + /** + * A seed value to initialize the randomness, during sampling. + */ + seed?: number; + + /** + * A higher temperature increases randomness in the outputs. + */ + temperature?: number; + + /** + * A list of tools the model may call. Currently, only functions are supported as a + * tool. Use this to provide a list of functions the model may generate JSON inputs + * for. A max of 128 functions are supported. + */ + tools?: Array; + + /** + * An alternative to temperature for nucleus sampling; 1.0 includes all tokens. + */ + top_p?: number; + } +} + +/** + * A JsonlRunDataSource object with that specifies a JSONL file that matches the + * eval + */ +export interface CreateEvalJSONLRunDataSource { + /** + * Determines what populates the `item` namespace in the data source. + */ + source: CreateEvalJSONLRunDataSource.FileContent | CreateEvalJSONLRunDataSource.FileID; + + /** + * The type of data source. Always `jsonl`. + */ + type: 'jsonl'; +} + +export namespace CreateEvalJSONLRunDataSource { + export interface FileContent { + /** + * The content of the jsonl file. + */ + content: Array; + + /** + * The type of jsonl source. Always `file_content`. + */ + type: 'file_content'; + } + + export namespace FileContent { + export interface Content { + item: { [key: string]: unknown }; + + sample?: { [key: string]: unknown }; + } + } + + export interface FileID { + /** + * The identifier of the file. + */ + id: string; + + /** + * The type of jsonl source. Always `file_id`. + */ + type: 'file_id'; + } +} + +/** + * An object representing an error response from the Eval API. + */ +export interface EvalAPIError { + /** + * The error code. + */ + code: string; + + /** + * The error message. + */ + message: string; +} + +/** + * A schema representing an evaluation run. + */ +export interface RunCreateResponse { + /** + * Unique identifier for the evaluation run. + */ + id: string; + + /** + * Unix timestamp (in seconds) when the evaluation run was created. + */ + created_at: number; + + /** + * Information about the run's data source. + */ + data_source: + | CreateEvalJSONLRunDataSource + | CreateEvalCompletionsRunDataSource + | RunCreateResponse.Responses; + + /** + * An object representing an error response from the Eval API. + */ + error: EvalAPIError; + + /** + * The identifier of the associated evaluation. + */ + eval_id: string; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata: Shared.Metadata | null; + + /** + * The model that is evaluated, if applicable. + */ + model: string; + + /** + * The name of the evaluation run. + */ + name: string; + + /** + * The type of the object. Always "eval.run". + */ + object: 'eval.run'; + + /** + * Usage statistics for each model during the evaluation run. + */ + per_model_usage: Array; + + /** + * Results per testing criteria applied during the evaluation run. + */ + per_testing_criteria_results: Array; + + /** + * The URL to the rendered evaluation run report on the UI dashboard. + */ + report_url: string; + + /** + * Counters summarizing the outcomes of the evaluation run. + */ + result_counts: RunCreateResponse.ResultCounts; + + /** + * The status of the evaluation run. + */ + status: string; +} + +export namespace RunCreateResponse { + /** + * A ResponsesRunDataSource object describing a model sampling configuration. + */ + export interface Responses { + /** + * Determines what populates the `item` namespace in this run's data source. + */ + source: Responses.FileContent | Responses.FileID | Responses.Responses; + + /** + * The type of run data source. Always `responses`. + */ + type: 'responses'; + + /** + * Used when sampling from a model. Dictates the structure of the messages passed + * into the model. Can either be a reference to a prebuilt trajectory (ie, + * `item.input_trajectory`), or a template with variable references to the `item` + * namespace. + */ + input_messages?: Responses.Template | Responses.ItemReference; + + /** + * The name of the model to use for generating completions (e.g. "o3-mini"). + */ + model?: string; + + sampling_params?: Responses.SamplingParams; + } + + export namespace Responses { + export interface FileContent { + /** + * The content of the jsonl file. + */ + content: Array; + + /** + * The type of jsonl source. Always `file_content`. + */ + type: 'file_content'; + } + + export namespace FileContent { + export interface Content { + item: { [key: string]: unknown }; + + sample?: { [key: string]: unknown }; + } + } + + export interface FileID { + /** + * The identifier of the file. + */ + id: string; + + /** + * The type of jsonl source. Always `file_id`. + */ + type: 'file_id'; + } + + /** + * A EvalResponsesSource object describing a run data source configuration. + */ + export interface Responses { + /** + * The type of run data source. Always `responses`. + */ + type: 'responses'; + + /** + * Only include items created after this timestamp (inclusive). This is a query + * parameter used to select responses. + */ + created_after?: number | null; + + /** + * Only include items created before this timestamp (inclusive). This is a query + * parameter used to select responses. + */ + created_before?: number | null; + + /** + * Optional string to search the 'instructions' field. This is a query parameter + * used to select responses. + */ + instructions_search?: string | null; + + /** + * Metadata filter for the responses. This is a query parameter used to select + * responses. + */ + metadata?: unknown | null; + + /** + * The name of the model to find responses for. This is a query parameter used to + * select responses. + */ + model?: string | null; + + /** + * Optional reasoning effort parameter. This is a query parameter used to select + * responses. + */ + reasoning_effort?: Shared.ReasoningEffort | null; + + /** + * Sampling temperature. This is a query parameter used to select responses. + */ + temperature?: number | null; + + /** + * List of tool names. This is a query parameter used to select responses. + */ + tools?: Array | null; + + /** + * Nucleus sampling parameter. This is a query parameter used to select responses. + */ + top_p?: number | null; + + /** + * List of user identifiers. This is a query parameter used to select responses. + */ + users?: Array | null; + } + + export interface Template { + /** + * A list of chat messages forming the prompt or context. May include variable + * references to the `item` namespace, ie {{item.name}}. + */ + template: Array; + + /** + * The type of input messages. Always `template`. + */ + type: 'template'; + } + + export namespace Template { + export interface ChatMessage { + /** + * The content of the message. + */ + content: string; + + /** + * The role of the message (e.g. "system", "assistant", "user"). + */ + role: string; + } + + /** + * A message input to the model with a role indicating instruction following + * hierarchy. Instructions given with the `developer` or `system` role take + * precedence over instructions given with the `user` role. Messages with the + * `assistant` role are presumed to have been generated by the model in previous + * interactions. + */ + export interface EvalItem { + /** + * Inputs to the model - can contain template strings. + */ + content: + | string + | ResponsesAPI.ResponseInputText + | EvalItem.OutputText + | EvalItem.InputImage + | Array; + + /** + * The role of the message input. One of `user`, `assistant`, `system`, or + * `developer`. + */ + role: 'user' | 'assistant' | 'system' | 'developer'; + + /** + * The type of the message input. Always `message`. + */ + type?: 'message'; + } + + export namespace EvalItem { + /** + * A text output from the model. + */ + export interface OutputText { + /** + * The text output from the model. + */ + text: string; + + /** + * The type of the output text. Always `output_text`. + */ + type: 'output_text'; + } + + /** + * An image input to the model. + */ + export interface InputImage { + /** + * The URL of the image input. + */ + image_url: string; + + /** + * The type of the image input. Always `input_image`. + */ + type: 'input_image'; + + /** + * The detail level of the image to be sent to the model. One of `high`, `low`, or + * `auto`. Defaults to `auto`. + */ + detail?: string; + } + } + } + + export interface ItemReference { + /** + * A reference to a variable in the `item` namespace. Ie, "item.name" + */ + item_reference: string; + + /** + * The type of input messages. Always `item_reference`. + */ + type: 'item_reference'; + } + + export interface SamplingParams { + /** + * The maximum number of tokens in the generated output. + */ + max_completion_tokens?: number; + + /** + * A seed value to initialize the randomness, during sampling. + */ + seed?: number; + + /** + * A higher temperature increases randomness in the outputs. + */ + temperature?: number; + + /** + * Configuration options for a text response from the model. Can be plain text or + * structured JSON data. Learn more: + * + * - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + * - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) + */ + text?: SamplingParams.Text; + + /** + * An array of tools the model may call while generating a response. You can + * specify which tool to use by setting the `tool_choice` parameter. + * + * The two categories of tools you can provide the model are: + * + * - **Built-in tools**: Tools that are provided by OpenAI that extend the model's + * capabilities, like + * [web search](https://platform.openai.com/docs/guides/tools-web-search) or + * [file search](https://platform.openai.com/docs/guides/tools-file-search). + * Learn more about + * [built-in tools](https://platform.openai.com/docs/guides/tools). + * - **Function calls (custom tools)**: Functions that are defined by you, enabling + * the model to call your own code. Learn more about + * [function calling](https://platform.openai.com/docs/guides/function-calling). + */ + tools?: Array; + + /** + * An alternative to temperature for nucleus sampling; 1.0 includes all tokens. + */ + top_p?: number; + } + + export namespace SamplingParams { + /** + * Configuration options for a text response from the model. Can be plain text or + * structured JSON data. Learn more: + * + * - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + * - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) + */ + export interface Text { + /** + * An object specifying the format that the model must output. + * + * Configuring `{ "type": "json_schema" }` enables Structured Outputs, which + * ensures the model will match your supplied JSON schema. Learn more in the + * [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + * + * The default format is `{ "type": "text" }` with no additional options. + * + * **Not recommended for gpt-4o and newer models:** + * + * Setting to `{ "type": "json_object" }` enables the older JSON mode, which + * ensures the message the model generates is valid JSON. Using `json_schema` is + * preferred for models that support it. + */ + format?: ResponsesAPI.ResponseFormatTextConfig; + } + } + } + + export interface PerModelUsage { + /** + * The number of tokens retrieved from cache. + */ + cached_tokens: number; + + /** + * The number of completion tokens generated. + */ + completion_tokens: number; + + /** + * The number of invocations. + */ + invocation_count: number; + + /** + * The name of the model. + */ + model_name: string; + + /** + * The number of prompt tokens used. + */ + prompt_tokens: number; + + /** + * The total number of tokens used. + */ + total_tokens: number; + } + + export interface PerTestingCriteriaResult { + /** + * Number of tests failed for this criteria. + */ + failed: number; + + /** + * Number of tests passed for this criteria. + */ + passed: number; + + /** + * A description of the testing criteria. + */ + testing_criteria: string; + } + + /** + * Counters summarizing the outcomes of the evaluation run. + */ + export interface ResultCounts { + /** + * Number of output items that resulted in an error. + */ + errored: number; + + /** + * Number of output items that failed to pass the evaluation. + */ + failed: number; + + /** + * Number of output items that passed the evaluation. + */ + passed: number; + + /** + * Total number of executed output items. + */ + total: number; + } +} + +/** + * A schema representing an evaluation run. + */ +export interface RunRetrieveResponse { + /** + * Unique identifier for the evaluation run. + */ + id: string; + + /** + * Unix timestamp (in seconds) when the evaluation run was created. + */ + created_at: number; + + /** + * Information about the run's data source. + */ + data_source: + | CreateEvalJSONLRunDataSource + | CreateEvalCompletionsRunDataSource + | RunRetrieveResponse.Responses; + + /** + * An object representing an error response from the Eval API. + */ + error: EvalAPIError; + + /** + * The identifier of the associated evaluation. + */ + eval_id: string; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata: Shared.Metadata | null; + + /** + * The model that is evaluated, if applicable. + */ + model: string; + + /** + * The name of the evaluation run. + */ + name: string; + + /** + * The type of the object. Always "eval.run". + */ + object: 'eval.run'; + + /** + * Usage statistics for each model during the evaluation run. + */ + per_model_usage: Array; + + /** + * Results per testing criteria applied during the evaluation run. + */ + per_testing_criteria_results: Array; + + /** + * The URL to the rendered evaluation run report on the UI dashboard. + */ + report_url: string; + + /** + * Counters summarizing the outcomes of the evaluation run. + */ + result_counts: RunRetrieveResponse.ResultCounts; + + /** + * The status of the evaluation run. + */ + status: string; +} + +export namespace RunRetrieveResponse { + /** + * A ResponsesRunDataSource object describing a model sampling configuration. + */ + export interface Responses { + /** + * Determines what populates the `item` namespace in this run's data source. + */ + source: Responses.FileContent | Responses.FileID | Responses.Responses; + + /** + * The type of run data source. Always `responses`. + */ + type: 'responses'; + + /** + * Used when sampling from a model. Dictates the structure of the messages passed + * into the model. Can either be a reference to a prebuilt trajectory (ie, + * `item.input_trajectory`), or a template with variable references to the `item` + * namespace. + */ + input_messages?: Responses.Template | Responses.ItemReference; + + /** + * The name of the model to use for generating completions (e.g. "o3-mini"). + */ + model?: string; + + sampling_params?: Responses.SamplingParams; + } + + export namespace Responses { + export interface FileContent { + /** + * The content of the jsonl file. + */ + content: Array; + + /** + * The type of jsonl source. Always `file_content`. + */ + type: 'file_content'; + } + + export namespace FileContent { + export interface Content { + item: { [key: string]: unknown }; + + sample?: { [key: string]: unknown }; + } + } + + export interface FileID { + /** + * The identifier of the file. + */ + id: string; + + /** + * The type of jsonl source. Always `file_id`. + */ + type: 'file_id'; + } + + /** + * A EvalResponsesSource object describing a run data source configuration. + */ + export interface Responses { + /** + * The type of run data source. Always `responses`. + */ + type: 'responses'; + + /** + * Only include items created after this timestamp (inclusive). This is a query + * parameter used to select responses. + */ + created_after?: number | null; + + /** + * Only include items created before this timestamp (inclusive). This is a query + * parameter used to select responses. + */ + created_before?: number | null; + + /** + * Optional string to search the 'instructions' field. This is a query parameter + * used to select responses. + */ + instructions_search?: string | null; + + /** + * Metadata filter for the responses. This is a query parameter used to select + * responses. + */ + metadata?: unknown | null; + + /** + * The name of the model to find responses for. This is a query parameter used to + * select responses. + */ + model?: string | null; + + /** + * Optional reasoning effort parameter. This is a query parameter used to select + * responses. + */ + reasoning_effort?: Shared.ReasoningEffort | null; + + /** + * Sampling temperature. This is a query parameter used to select responses. + */ + temperature?: number | null; + + /** + * List of tool names. This is a query parameter used to select responses. + */ + tools?: Array | null; + + /** + * Nucleus sampling parameter. This is a query parameter used to select responses. + */ + top_p?: number | null; + + /** + * List of user identifiers. This is a query parameter used to select responses. + */ + users?: Array | null; + } + + export interface Template { + /** + * A list of chat messages forming the prompt or context. May include variable + * references to the `item` namespace, ie {{item.name}}. + */ + template: Array; + + /** + * The type of input messages. Always `template`. + */ + type: 'template'; + } + + export namespace Template { + export interface ChatMessage { + /** + * The content of the message. + */ + content: string; + + /** + * The role of the message (e.g. "system", "assistant", "user"). + */ + role: string; + } + + /** + * A message input to the model with a role indicating instruction following + * hierarchy. Instructions given with the `developer` or `system` role take + * precedence over instructions given with the `user` role. Messages with the + * `assistant` role are presumed to have been generated by the model in previous + * interactions. + */ + export interface EvalItem { + /** + * Inputs to the model - can contain template strings. + */ + content: + | string + | ResponsesAPI.ResponseInputText + | EvalItem.OutputText + | EvalItem.InputImage + | Array; + + /** + * The role of the message input. One of `user`, `assistant`, `system`, or + * `developer`. + */ + role: 'user' | 'assistant' | 'system' | 'developer'; + + /** + * The type of the message input. Always `message`. + */ + type?: 'message'; + } + + export namespace EvalItem { + /** + * A text output from the model. + */ + export interface OutputText { + /** + * The text output from the model. + */ + text: string; + + /** + * The type of the output text. Always `output_text`. + */ + type: 'output_text'; + } + + /** + * An image input to the model. + */ + export interface InputImage { + /** + * The URL of the image input. + */ + image_url: string; + + /** + * The type of the image input. Always `input_image`. + */ + type: 'input_image'; + + /** + * The detail level of the image to be sent to the model. One of `high`, `low`, or + * `auto`. Defaults to `auto`. + */ + detail?: string; + } + } + } + + export interface ItemReference { + /** + * A reference to a variable in the `item` namespace. Ie, "item.name" + */ + item_reference: string; + + /** + * The type of input messages. Always `item_reference`. + */ + type: 'item_reference'; + } + + export interface SamplingParams { + /** + * The maximum number of tokens in the generated output. + */ + max_completion_tokens?: number; + + /** + * A seed value to initialize the randomness, during sampling. + */ + seed?: number; + + /** + * A higher temperature increases randomness in the outputs. + */ + temperature?: number; + + /** + * Configuration options for a text response from the model. Can be plain text or + * structured JSON data. Learn more: + * + * - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + * - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) + */ + text?: SamplingParams.Text; + + /** + * An array of tools the model may call while generating a response. You can + * specify which tool to use by setting the `tool_choice` parameter. + * + * The two categories of tools you can provide the model are: + * + * - **Built-in tools**: Tools that are provided by OpenAI that extend the model's + * capabilities, like + * [web search](https://platform.openai.com/docs/guides/tools-web-search) or + * [file search](https://platform.openai.com/docs/guides/tools-file-search). + * Learn more about + * [built-in tools](https://platform.openai.com/docs/guides/tools). + * - **Function calls (custom tools)**: Functions that are defined by you, enabling + * the model to call your own code. Learn more about + * [function calling](https://platform.openai.com/docs/guides/function-calling). + */ + tools?: Array; + + /** + * An alternative to temperature for nucleus sampling; 1.0 includes all tokens. + */ + top_p?: number; + } + + export namespace SamplingParams { + /** + * Configuration options for a text response from the model. Can be plain text or + * structured JSON data. Learn more: + * + * - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + * - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) + */ + export interface Text { + /** + * An object specifying the format that the model must output. + * + * Configuring `{ "type": "json_schema" }` enables Structured Outputs, which + * ensures the model will match your supplied JSON schema. Learn more in the + * [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + * + * The default format is `{ "type": "text" }` with no additional options. + * + * **Not recommended for gpt-4o and newer models:** + * + * Setting to `{ "type": "json_object" }` enables the older JSON mode, which + * ensures the message the model generates is valid JSON. Using `json_schema` is + * preferred for models that support it. + */ + format?: ResponsesAPI.ResponseFormatTextConfig; + } + } + } + + export interface PerModelUsage { + /** + * The number of tokens retrieved from cache. + */ + cached_tokens: number; + + /** + * The number of completion tokens generated. + */ + completion_tokens: number; + + /** + * The number of invocations. + */ + invocation_count: number; + + /** + * The name of the model. + */ + model_name: string; + + /** + * The number of prompt tokens used. + */ + prompt_tokens: number; + + /** + * The total number of tokens used. + */ + total_tokens: number; + } + + export interface PerTestingCriteriaResult { + /** + * Number of tests failed for this criteria. + */ + failed: number; + + /** + * Number of tests passed for this criteria. + */ + passed: number; + + /** + * A description of the testing criteria. + */ + testing_criteria: string; + } + + /** + * Counters summarizing the outcomes of the evaluation run. + */ + export interface ResultCounts { + /** + * Number of output items that resulted in an error. + */ + errored: number; + + /** + * Number of output items that failed to pass the evaluation. + */ + failed: number; + + /** + * Number of output items that passed the evaluation. + */ + passed: number; + + /** + * Total number of executed output items. + */ + total: number; + } +} + +/** + * A schema representing an evaluation run. + */ +export interface RunListResponse { + /** + * Unique identifier for the evaluation run. + */ + id: string; + + /** + * Unix timestamp (in seconds) when the evaluation run was created. + */ + created_at: number; + + /** + * Information about the run's data source. + */ + data_source: CreateEvalJSONLRunDataSource | CreateEvalCompletionsRunDataSource | RunListResponse.Responses; + + /** + * An object representing an error response from the Eval API. + */ + error: EvalAPIError; + + /** + * The identifier of the associated evaluation. + */ + eval_id: string; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata: Shared.Metadata | null; + + /** + * The model that is evaluated, if applicable. + */ + model: string; + + /** + * The name of the evaluation run. + */ + name: string; + + /** + * The type of the object. Always "eval.run". + */ + object: 'eval.run'; + + /** + * Usage statistics for each model during the evaluation run. + */ + per_model_usage: Array; + + /** + * Results per testing criteria applied during the evaluation run. + */ + per_testing_criteria_results: Array; + + /** + * The URL to the rendered evaluation run report on the UI dashboard. + */ + report_url: string; + + /** + * Counters summarizing the outcomes of the evaluation run. + */ + result_counts: RunListResponse.ResultCounts; + + /** + * The status of the evaluation run. + */ + status: string; +} + +export namespace RunListResponse { + /** + * A ResponsesRunDataSource object describing a model sampling configuration. + */ + export interface Responses { + /** + * Determines what populates the `item` namespace in this run's data source. + */ + source: Responses.FileContent | Responses.FileID | Responses.Responses; + + /** + * The type of run data source. Always `responses`. + */ + type: 'responses'; + + /** + * Used when sampling from a model. Dictates the structure of the messages passed + * into the model. Can either be a reference to a prebuilt trajectory (ie, + * `item.input_trajectory`), or a template with variable references to the `item` + * namespace. + */ + input_messages?: Responses.Template | Responses.ItemReference; + + /** + * The name of the model to use for generating completions (e.g. "o3-mini"). + */ + model?: string; + + sampling_params?: Responses.SamplingParams; + } + + export namespace Responses { + export interface FileContent { + /** + * The content of the jsonl file. + */ + content: Array; + + /** + * The type of jsonl source. Always `file_content`. + */ + type: 'file_content'; + } + + export namespace FileContent { + export interface Content { + item: { [key: string]: unknown }; + + sample?: { [key: string]: unknown }; + } + } + + export interface FileID { + /** + * The identifier of the file. + */ + id: string; + + /** + * The type of jsonl source. Always `file_id`. + */ + type: 'file_id'; + } + + /** + * A EvalResponsesSource object describing a run data source configuration. + */ + export interface Responses { + /** + * The type of run data source. Always `responses`. + */ + type: 'responses'; + + /** + * Only include items created after this timestamp (inclusive). This is a query + * parameter used to select responses. + */ + created_after?: number | null; + + /** + * Only include items created before this timestamp (inclusive). This is a query + * parameter used to select responses. + */ + created_before?: number | null; + + /** + * Optional string to search the 'instructions' field. This is a query parameter + * used to select responses. + */ + instructions_search?: string | null; + + /** + * Metadata filter for the responses. This is a query parameter used to select + * responses. + */ + metadata?: unknown | null; + + /** + * The name of the model to find responses for. This is a query parameter used to + * select responses. + */ + model?: string | null; + + /** + * Optional reasoning effort parameter. This is a query parameter used to select + * responses. + */ + reasoning_effort?: Shared.ReasoningEffort | null; + + /** + * Sampling temperature. This is a query parameter used to select responses. + */ + temperature?: number | null; + + /** + * List of tool names. This is a query parameter used to select responses. + */ + tools?: Array | null; + + /** + * Nucleus sampling parameter. This is a query parameter used to select responses. + */ + top_p?: number | null; + + /** + * List of user identifiers. This is a query parameter used to select responses. + */ + users?: Array | null; + } + + export interface Template { + /** + * A list of chat messages forming the prompt or context. May include variable + * references to the `item` namespace, ie {{item.name}}. + */ + template: Array; + + /** + * The type of input messages. Always `template`. + */ + type: 'template'; + } + + export namespace Template { + export interface ChatMessage { + /** + * The content of the message. + */ + content: string; + + /** + * The role of the message (e.g. "system", "assistant", "user"). + */ + role: string; + } + + /** + * A message input to the model with a role indicating instruction following + * hierarchy. Instructions given with the `developer` or `system` role take + * precedence over instructions given with the `user` role. Messages with the + * `assistant` role are presumed to have been generated by the model in previous + * interactions. + */ + export interface EvalItem { + /** + * Inputs to the model - can contain template strings. + */ + content: + | string + | ResponsesAPI.ResponseInputText + | EvalItem.OutputText + | EvalItem.InputImage + | Array; + + /** + * The role of the message input. One of `user`, `assistant`, `system`, or + * `developer`. + */ + role: 'user' | 'assistant' | 'system' | 'developer'; + + /** + * The type of the message input. Always `message`. + */ + type?: 'message'; + } + + export namespace EvalItem { + /** + * A text output from the model. + */ + export interface OutputText { + /** + * The text output from the model. + */ + text: string; + + /** + * The type of the output text. Always `output_text`. + */ + type: 'output_text'; + } + + /** + * An image input to the model. + */ + export interface InputImage { + /** + * The URL of the image input. + */ + image_url: string; + + /** + * The type of the image input. Always `input_image`. + */ + type: 'input_image'; + + /** + * The detail level of the image to be sent to the model. One of `high`, `low`, or + * `auto`. Defaults to `auto`. + */ + detail?: string; + } + } + } + + export interface ItemReference { + /** + * A reference to a variable in the `item` namespace. Ie, "item.name" + */ + item_reference: string; + + /** + * The type of input messages. Always `item_reference`. + */ + type: 'item_reference'; + } + + export interface SamplingParams { + /** + * The maximum number of tokens in the generated output. + */ + max_completion_tokens?: number; + + /** + * A seed value to initialize the randomness, during sampling. + */ + seed?: number; + + /** + * A higher temperature increases randomness in the outputs. + */ + temperature?: number; + + /** + * Configuration options for a text response from the model. Can be plain text or + * structured JSON data. Learn more: + * + * - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + * - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) + */ + text?: SamplingParams.Text; + + /** + * An array of tools the model may call while generating a response. You can + * specify which tool to use by setting the `tool_choice` parameter. + * + * The two categories of tools you can provide the model are: + * + * - **Built-in tools**: Tools that are provided by OpenAI that extend the model's + * capabilities, like + * [web search](https://platform.openai.com/docs/guides/tools-web-search) or + * [file search](https://platform.openai.com/docs/guides/tools-file-search). + * Learn more about + * [built-in tools](https://platform.openai.com/docs/guides/tools). + * - **Function calls (custom tools)**: Functions that are defined by you, enabling + * the model to call your own code. Learn more about + * [function calling](https://platform.openai.com/docs/guides/function-calling). + */ + tools?: Array; + + /** + * An alternative to temperature for nucleus sampling; 1.0 includes all tokens. + */ + top_p?: number; + } + + export namespace SamplingParams { + /** + * Configuration options for a text response from the model. Can be plain text or + * structured JSON data. Learn more: + * + * - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + * - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) + */ + export interface Text { + /** + * An object specifying the format that the model must output. + * + * Configuring `{ "type": "json_schema" }` enables Structured Outputs, which + * ensures the model will match your supplied JSON schema. Learn more in the + * [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + * + * The default format is `{ "type": "text" }` with no additional options. + * + * **Not recommended for gpt-4o and newer models:** + * + * Setting to `{ "type": "json_object" }` enables the older JSON mode, which + * ensures the message the model generates is valid JSON. Using `json_schema` is + * preferred for models that support it. + */ + format?: ResponsesAPI.ResponseFormatTextConfig; + } + } + } + + export interface PerModelUsage { + /** + * The number of tokens retrieved from cache. + */ + cached_tokens: number; + + /** + * The number of completion tokens generated. + */ + completion_tokens: number; + + /** + * The number of invocations. + */ + invocation_count: number; + + /** + * The name of the model. + */ + model_name: string; + + /** + * The number of prompt tokens used. + */ + prompt_tokens: number; + + /** + * The total number of tokens used. + */ + total_tokens: number; + } + + export interface PerTestingCriteriaResult { + /** + * Number of tests failed for this criteria. + */ + failed: number; + + /** + * Number of tests passed for this criteria. + */ + passed: number; + + /** + * A description of the testing criteria. + */ + testing_criteria: string; + } + + /** + * Counters summarizing the outcomes of the evaluation run. + */ + export interface ResultCounts { + /** + * Number of output items that resulted in an error. + */ + errored: number; + + /** + * Number of output items that failed to pass the evaluation. + */ + failed: number; + + /** + * Number of output items that passed the evaluation. + */ + passed: number; + + /** + * Total number of executed output items. + */ + total: number; + } +} + +export interface RunDeleteResponse { + deleted?: boolean; + + object?: string; + + run_id?: string; +} + +/** + * A schema representing an evaluation run. + */ +export interface RunCancelResponse { + /** + * Unique identifier for the evaluation run. + */ + id: string; + + /** + * Unix timestamp (in seconds) when the evaluation run was created. + */ + created_at: number; + + /** + * Information about the run's data source. + */ + data_source: + | CreateEvalJSONLRunDataSource + | CreateEvalCompletionsRunDataSource + | RunCancelResponse.Responses; + + /** + * An object representing an error response from the Eval API. + */ + error: EvalAPIError; + + /** + * The identifier of the associated evaluation. + */ + eval_id: string; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata: Shared.Metadata | null; + + /** + * The model that is evaluated, if applicable. + */ + model: string; + + /** + * The name of the evaluation run. + */ + name: string; + + /** + * The type of the object. Always "eval.run". + */ + object: 'eval.run'; + + /** + * Usage statistics for each model during the evaluation run. + */ + per_model_usage: Array; + + /** + * Results per testing criteria applied during the evaluation run. + */ + per_testing_criteria_results: Array; + + /** + * The URL to the rendered evaluation run report on the UI dashboard. + */ + report_url: string; + + /** + * Counters summarizing the outcomes of the evaluation run. + */ + result_counts: RunCancelResponse.ResultCounts; + + /** + * The status of the evaluation run. + */ + status: string; +} + +export namespace RunCancelResponse { + /** + * A ResponsesRunDataSource object describing a model sampling configuration. + */ + export interface Responses { + /** + * Determines what populates the `item` namespace in this run's data source. + */ + source: Responses.FileContent | Responses.FileID | Responses.Responses; + + /** + * The type of run data source. Always `responses`. + */ + type: 'responses'; + + /** + * Used when sampling from a model. Dictates the structure of the messages passed + * into the model. Can either be a reference to a prebuilt trajectory (ie, + * `item.input_trajectory`), or a template with variable references to the `item` + * namespace. + */ + input_messages?: Responses.Template | Responses.ItemReference; + + /** + * The name of the model to use for generating completions (e.g. "o3-mini"). + */ + model?: string; + + sampling_params?: Responses.SamplingParams; + } + + export namespace Responses { + export interface FileContent { + /** + * The content of the jsonl file. + */ + content: Array; + + /** + * The type of jsonl source. Always `file_content`. + */ + type: 'file_content'; + } + + export namespace FileContent { + export interface Content { + item: { [key: string]: unknown }; + + sample?: { [key: string]: unknown }; + } + } + + export interface FileID { + /** + * The identifier of the file. + */ + id: string; + + /** + * The type of jsonl source. Always `file_id`. + */ + type: 'file_id'; + } + + /** + * A EvalResponsesSource object describing a run data source configuration. + */ + export interface Responses { + /** + * The type of run data source. Always `responses`. + */ + type: 'responses'; + + /** + * Only include items created after this timestamp (inclusive). This is a query + * parameter used to select responses. + */ + created_after?: number | null; + + /** + * Only include items created before this timestamp (inclusive). This is a query + * parameter used to select responses. + */ + created_before?: number | null; + + /** + * Optional string to search the 'instructions' field. This is a query parameter + * used to select responses. + */ + instructions_search?: string | null; + + /** + * Metadata filter for the responses. This is a query parameter used to select + * responses. + */ + metadata?: unknown | null; + + /** + * The name of the model to find responses for. This is a query parameter used to + * select responses. + */ + model?: string | null; + + /** + * Optional reasoning effort parameter. This is a query parameter used to select + * responses. + */ + reasoning_effort?: Shared.ReasoningEffort | null; + + /** + * Sampling temperature. This is a query parameter used to select responses. + */ + temperature?: number | null; + + /** + * List of tool names. This is a query parameter used to select responses. + */ + tools?: Array | null; + + /** + * Nucleus sampling parameter. This is a query parameter used to select responses. + */ + top_p?: number | null; + + /** + * List of user identifiers. This is a query parameter used to select responses. + */ + users?: Array | null; + } + + export interface Template { + /** + * A list of chat messages forming the prompt or context. May include variable + * references to the `item` namespace, ie {{item.name}}. + */ + template: Array; + + /** + * The type of input messages. Always `template`. + */ + type: 'template'; + } + + export namespace Template { + export interface ChatMessage { + /** + * The content of the message. + */ + content: string; + + /** + * The role of the message (e.g. "system", "assistant", "user"). + */ + role: string; + } + + /** + * A message input to the model with a role indicating instruction following + * hierarchy. Instructions given with the `developer` or `system` role take + * precedence over instructions given with the `user` role. Messages with the + * `assistant` role are presumed to have been generated by the model in previous + * interactions. + */ + export interface EvalItem { + /** + * Inputs to the model - can contain template strings. + */ + content: + | string + | ResponsesAPI.ResponseInputText + | EvalItem.OutputText + | EvalItem.InputImage + | Array; + + /** + * The role of the message input. One of `user`, `assistant`, `system`, or + * `developer`. + */ + role: 'user' | 'assistant' | 'system' | 'developer'; + + /** + * The type of the message input. Always `message`. + */ + type?: 'message'; + } + + export namespace EvalItem { + /** + * A text output from the model. + */ + export interface OutputText { + /** + * The text output from the model. + */ + text: string; + + /** + * The type of the output text. Always `output_text`. + */ + type: 'output_text'; + } + + /** + * An image input to the model. + */ + export interface InputImage { + /** + * The URL of the image input. + */ + image_url: string; + + /** + * The type of the image input. Always `input_image`. + */ + type: 'input_image'; + + /** + * The detail level of the image to be sent to the model. One of `high`, `low`, or + * `auto`. Defaults to `auto`. + */ + detail?: string; + } + } + } + + export interface ItemReference { + /** + * A reference to a variable in the `item` namespace. Ie, "item.name" + */ + item_reference: string; + + /** + * The type of input messages. Always `item_reference`. + */ + type: 'item_reference'; + } + + export interface SamplingParams { + /** + * The maximum number of tokens in the generated output. + */ + max_completion_tokens?: number; + + /** + * A seed value to initialize the randomness, during sampling. + */ + seed?: number; + + /** + * A higher temperature increases randomness in the outputs. + */ + temperature?: number; + + /** + * Configuration options for a text response from the model. Can be plain text or + * structured JSON data. Learn more: + * + * - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + * - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) + */ + text?: SamplingParams.Text; + + /** + * An array of tools the model may call while generating a response. You can + * specify which tool to use by setting the `tool_choice` parameter. + * + * The two categories of tools you can provide the model are: + * + * - **Built-in tools**: Tools that are provided by OpenAI that extend the model's + * capabilities, like + * [web search](https://platform.openai.com/docs/guides/tools-web-search) or + * [file search](https://platform.openai.com/docs/guides/tools-file-search). + * Learn more about + * [built-in tools](https://platform.openai.com/docs/guides/tools). + * - **Function calls (custom tools)**: Functions that are defined by you, enabling + * the model to call your own code. Learn more about + * [function calling](https://platform.openai.com/docs/guides/function-calling). + */ + tools?: Array; + + /** + * An alternative to temperature for nucleus sampling; 1.0 includes all tokens. + */ + top_p?: number; + } + + export namespace SamplingParams { + /** + * Configuration options for a text response from the model. Can be plain text or + * structured JSON data. Learn more: + * + * - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + * - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) + */ + export interface Text { + /** + * An object specifying the format that the model must output. + * + * Configuring `{ "type": "json_schema" }` enables Structured Outputs, which + * ensures the model will match your supplied JSON schema. Learn more in the + * [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + * + * The default format is `{ "type": "text" }` with no additional options. + * + * **Not recommended for gpt-4o and newer models:** + * + * Setting to `{ "type": "json_object" }` enables the older JSON mode, which + * ensures the message the model generates is valid JSON. Using `json_schema` is + * preferred for models that support it. + */ + format?: ResponsesAPI.ResponseFormatTextConfig; + } + } + } + + export interface PerModelUsage { + /** + * The number of tokens retrieved from cache. + */ + cached_tokens: number; + + /** + * The number of completion tokens generated. + */ + completion_tokens: number; + + /** + * The number of invocations. + */ + invocation_count: number; + + /** + * The name of the model. + */ + model_name: string; + + /** + * The number of prompt tokens used. + */ + prompt_tokens: number; + + /** + * The total number of tokens used. + */ + total_tokens: number; + } + + export interface PerTestingCriteriaResult { + /** + * Number of tests failed for this criteria. + */ + failed: number; + + /** + * Number of tests passed for this criteria. + */ + passed: number; + + /** + * A description of the testing criteria. + */ + testing_criteria: string; + } + + /** + * Counters summarizing the outcomes of the evaluation run. + */ + export interface ResultCounts { + /** + * Number of output items that resulted in an error. + */ + errored: number; + + /** + * Number of output items that failed to pass the evaluation. + */ + failed: number; + + /** + * Number of output items that passed the evaluation. + */ + passed: number; + + /** + * Total number of executed output items. + */ + total: number; + } +} + +export interface RunCreateParams { + /** + * Details about the run's data source. + */ + data_source: + | CreateEvalJSONLRunDataSource + | CreateEvalCompletionsRunDataSource + | RunCreateParams.CreateEvalResponsesRunDataSource; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; + + /** + * The name of the run. + */ + name?: string; +} + +export namespace RunCreateParams { + /** + * A ResponsesRunDataSource object describing a model sampling configuration. + */ + export interface CreateEvalResponsesRunDataSource { + /** + * Determines what populates the `item` namespace in this run's data source. + */ + source: + | CreateEvalResponsesRunDataSource.FileContent + | CreateEvalResponsesRunDataSource.FileID + | CreateEvalResponsesRunDataSource.Responses; + + /** + * The type of run data source. Always `responses`. + */ + type: 'responses'; + + /** + * Used when sampling from a model. Dictates the structure of the messages passed + * into the model. Can either be a reference to a prebuilt trajectory (ie, + * `item.input_trajectory`), or a template with variable references to the `item` + * namespace. + */ + input_messages?: + | CreateEvalResponsesRunDataSource.Template + | CreateEvalResponsesRunDataSource.ItemReference; + + /** + * The name of the model to use for generating completions (e.g. "o3-mini"). + */ + model?: string; + + sampling_params?: CreateEvalResponsesRunDataSource.SamplingParams; + } + + export namespace CreateEvalResponsesRunDataSource { + export interface FileContent { + /** + * The content of the jsonl file. + */ + content: Array; + + /** + * The type of jsonl source. Always `file_content`. + */ + type: 'file_content'; + } + + export namespace FileContent { + export interface Content { + item: { [key: string]: unknown }; + + sample?: { [key: string]: unknown }; + } + } + + export interface FileID { + /** + * The identifier of the file. + */ + id: string; + + /** + * The type of jsonl source. Always `file_id`. + */ + type: 'file_id'; + } + + /** + * A EvalResponsesSource object describing a run data source configuration. + */ + export interface Responses { + /** + * The type of run data source. Always `responses`. + */ + type: 'responses'; + + /** + * Only include items created after this timestamp (inclusive). This is a query + * parameter used to select responses. + */ + created_after?: number | null; + + /** + * Only include items created before this timestamp (inclusive). This is a query + * parameter used to select responses. + */ + created_before?: number | null; + + /** + * Optional string to search the 'instructions' field. This is a query parameter + * used to select responses. + */ + instructions_search?: string | null; + + /** + * Metadata filter for the responses. This is a query parameter used to select + * responses. + */ + metadata?: unknown | null; + + /** + * The name of the model to find responses for. This is a query parameter used to + * select responses. + */ + model?: string | null; + + /** + * Optional reasoning effort parameter. This is a query parameter used to select + * responses. + */ + reasoning_effort?: Shared.ReasoningEffort | null; + + /** + * Sampling temperature. This is a query parameter used to select responses. + */ + temperature?: number | null; + + /** + * List of tool names. This is a query parameter used to select responses. + */ + tools?: Array | null; + + /** + * Nucleus sampling parameter. This is a query parameter used to select responses. + */ + top_p?: number | null; + + /** + * List of user identifiers. This is a query parameter used to select responses. + */ + users?: Array | null; + } + + export interface Template { + /** + * A list of chat messages forming the prompt or context. May include variable + * references to the `item` namespace, ie {{item.name}}. + */ + template: Array; + + /** + * The type of input messages. Always `template`. + */ + type: 'template'; + } + + export namespace Template { + export interface ChatMessage { + /** + * The content of the message. + */ + content: string; + + /** + * The role of the message (e.g. "system", "assistant", "user"). + */ + role: string; + } + + /** + * A message input to the model with a role indicating instruction following + * hierarchy. Instructions given with the `developer` or `system` role take + * precedence over instructions given with the `user` role. Messages with the + * `assistant` role are presumed to have been generated by the model in previous + * interactions. + */ + export interface EvalItem { + /** + * Inputs to the model - can contain template strings. + */ + content: + | string + | ResponsesAPI.ResponseInputText + | EvalItem.OutputText + | EvalItem.InputImage + | Array; + + /** + * The role of the message input. One of `user`, `assistant`, `system`, or + * `developer`. + */ + role: 'user' | 'assistant' | 'system' | 'developer'; + + /** + * The type of the message input. Always `message`. + */ + type?: 'message'; + } + + export namespace EvalItem { + /** + * A text output from the model. + */ + export interface OutputText { + /** + * The text output from the model. + */ + text: string; + + /** + * The type of the output text. Always `output_text`. + */ + type: 'output_text'; + } + + /** + * An image input to the model. + */ + export interface InputImage { + /** + * The URL of the image input. + */ + image_url: string; + + /** + * The type of the image input. Always `input_image`. + */ + type: 'input_image'; + + /** + * The detail level of the image to be sent to the model. One of `high`, `low`, or + * `auto`. Defaults to `auto`. + */ + detail?: string; + } + } + } + + export interface ItemReference { + /** + * A reference to a variable in the `item` namespace. Ie, "item.name" + */ + item_reference: string; + + /** + * The type of input messages. Always `item_reference`. + */ + type: 'item_reference'; + } + + export interface SamplingParams { + /** + * The maximum number of tokens in the generated output. + */ + max_completion_tokens?: number; + + /** + * A seed value to initialize the randomness, during sampling. + */ + seed?: number; + + /** + * A higher temperature increases randomness in the outputs. + */ + temperature?: number; + + /** + * Configuration options for a text response from the model. Can be plain text or + * structured JSON data. Learn more: + * + * - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + * - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) + */ + text?: SamplingParams.Text; + + /** + * An array of tools the model may call while generating a response. You can + * specify which tool to use by setting the `tool_choice` parameter. + * + * The two categories of tools you can provide the model are: + * + * - **Built-in tools**: Tools that are provided by OpenAI that extend the model's + * capabilities, like + * [web search](https://platform.openai.com/docs/guides/tools-web-search) or + * [file search](https://platform.openai.com/docs/guides/tools-file-search). + * Learn more about + * [built-in tools](https://platform.openai.com/docs/guides/tools). + * - **Function calls (custom tools)**: Functions that are defined by you, enabling + * the model to call your own code. Learn more about + * [function calling](https://platform.openai.com/docs/guides/function-calling). + */ + tools?: Array; + + /** + * An alternative to temperature for nucleus sampling; 1.0 includes all tokens. + */ + top_p?: number; + } + + export namespace SamplingParams { + /** + * Configuration options for a text response from the model. Can be plain text or + * structured JSON data. Learn more: + * + * - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + * - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) + */ + export interface Text { + /** + * An object specifying the format that the model must output. + * + * Configuring `{ "type": "json_schema" }` enables Structured Outputs, which + * ensures the model will match your supplied JSON schema. Learn more in the + * [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + * + * The default format is `{ "type": "text" }` with no additional options. + * + * **Not recommended for gpt-4o and newer models:** + * + * Setting to `{ "type": "json_object" }` enables the older JSON mode, which + * ensures the message the model generates is valid JSON. Using `json_schema` is + * preferred for models that support it. + */ + format?: ResponsesAPI.ResponseFormatTextConfig; + } + } + } +} + +export interface RunRetrieveParams { + /** + * The ID of the evaluation to retrieve runs for. + */ + eval_id: string; +} + +export interface RunListParams extends CursorPageParams { + /** + * Sort order for runs by timestamp. Use `asc` for ascending order or `desc` for + * descending order. Defaults to `asc`. + */ + order?: 'asc' | 'desc'; + + /** + * Filter runs by status. One of `queued` | `in_progress` | `failed` | `completed` + * | `canceled`. + */ + status?: 'queued' | 'in_progress' | 'completed' | 'canceled' | 'failed'; +} + +export interface RunDeleteParams { + /** + * The ID of the evaluation to delete the run from. + */ + eval_id: string; +} + +export interface RunCancelParams { + /** + * The ID of the evaluation whose run you want to cancel. + */ + eval_id: string; +} + +Runs.OutputItems = OutputItems; + +export declare namespace Runs { + export { + type CreateEvalCompletionsRunDataSource as CreateEvalCompletionsRunDataSource, + type CreateEvalJSONLRunDataSource as CreateEvalJSONLRunDataSource, + type EvalAPIError as EvalAPIError, + type RunCreateResponse as RunCreateResponse, + type RunRetrieveResponse as RunRetrieveResponse, + type RunListResponse as RunListResponse, + type RunDeleteResponse as RunDeleteResponse, + type RunCancelResponse as RunCancelResponse, + type RunListResponsesPage as RunListResponsesPage, + type RunCreateParams as RunCreateParams, + type RunRetrieveParams as RunRetrieveParams, + type RunListParams as RunListParams, + type RunDeleteParams as RunDeleteParams, + type RunCancelParams as RunCancelParams, + }; + + export { + OutputItems as OutputItems, + type OutputItemRetrieveResponse as OutputItemRetrieveResponse, + type OutputItemListResponse as OutputItemListResponse, + type OutputItemListResponsesPage as OutputItemListResponsesPage, + type OutputItemRetrieveParams as OutputItemRetrieveParams, + type OutputItemListParams as OutputItemListParams, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/files.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/files.ts new file mode 100644 index 0000000000000000000000000000000000000000..ef68732211e440c88508f28ca2acd0e73db79646 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/files.ts @@ -0,0 +1,250 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../core/resource'; +import { APIPromise } from '../core/api-promise'; +import { CursorPage, type CursorPageParams, PagePromise } from '../core/pagination'; +import { type Uploadable } from '../core/uploads'; +import { buildHeaders } from '../internal/headers'; +import { RequestOptions } from '../internal/request-options'; +import { sleep } from '../internal/utils/sleep'; +import { APIConnectionTimeoutError } from '../error'; +import { multipartFormRequestOptions } from '../internal/uploads'; +import { path } from '../internal/utils/path'; + +export class Files extends APIResource { + /** + * Upload a file that can be used across various endpoints. Individual files can be + * up to 512 MB, and the size of all files uploaded by one organization can be up + * to 1 TB. + * + * The Assistants API supports files up to 2 million tokens and of specific file + * types. See the + * [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) for + * details. + * + * The Fine-tuning API only supports `.jsonl` files. The input also has certain + * required formats for fine-tuning + * [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or + * [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) + * models. + * + * The Batch API only supports `.jsonl` files up to 200 MB in size. The input also + * has a specific required + * [format](https://platform.openai.com/docs/api-reference/batch/request-input). + * + * Please [contact us](https://help.openai.com/) if you need to increase these + * storage limits. + */ + create(body: FileCreateParams, options?: RequestOptions): APIPromise { + return this._client.post('/files', multipartFormRequestOptions({ body, ...options }, this._client)); + } + + /** + * Returns information about a specific file. + */ + retrieve(fileID: string, options?: RequestOptions): APIPromise { + return this._client.get(path`/files/${fileID}`, options); + } + + /** + * Returns a list of files. + */ + list( + query: FileListParams | null | undefined = {}, + options?: RequestOptions, + ): PagePromise { + return this._client.getAPIList('/files', CursorPage, { query, ...options }); + } + + /** + * Delete a file. + */ + delete(fileID: string, options?: RequestOptions): APIPromise { + return this._client.delete(path`/files/${fileID}`, options); + } + + /** + * Returns the contents of the specified file. + */ + content(fileID: string, options?: RequestOptions): APIPromise { + return this._client.get(path`/files/${fileID}/content`, { + ...options, + headers: buildHeaders([{ Accept: 'application/binary' }, options?.headers]), + __binaryResponse: true, + }); + } + + /** + * Waits for the given file to be processed, default timeout is 30 mins. + */ + async waitForProcessing( + id: string, + { pollInterval = 5000, maxWait = 30 * 60 * 1000 }: { pollInterval?: number; maxWait?: number } = {}, + ): Promise { + const TERMINAL_STATES = new Set(['processed', 'error', 'deleted']); + + const start = Date.now(); + let file = await this.retrieve(id); + + while (!file.status || !TERMINAL_STATES.has(file.status)) { + await sleep(pollInterval); + + file = await this.retrieve(id); + if (Date.now() - start > maxWait) { + throw new APIConnectionTimeoutError({ + message: `Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.`, + }); + } + } + + return file; + } +} + +export type FileObjectsPage = CursorPage; + +export type FileContent = string; + +export interface FileDeleted { + id: string; + + deleted: boolean; + + object: 'file'; +} + +/** + * The `File` object represents a document that has been uploaded to OpenAI. + */ +export interface FileObject { + /** + * The file identifier, which can be referenced in the API endpoints. + */ + id: string; + + /** + * The size of the file, in bytes. + */ + bytes: number; + + /** + * The Unix timestamp (in seconds) for when the file was created. + */ + created_at: number; + + /** + * The name of the file. + */ + filename: string; + + /** + * The object type, which is always `file`. + */ + object: 'file'; + + /** + * The intended purpose of the file. Supported values are `assistants`, + * `assistants_output`, `batch`, `batch_output`, `fine-tune`, `fine-tune-results`, + * `vision`, and `user_data`. + */ + purpose: + | 'assistants' + | 'assistants_output' + | 'batch' + | 'batch_output' + | 'fine-tune' + | 'fine-tune-results' + | 'vision' + | 'user_data'; + + /** + * @deprecated Deprecated. The current status of the file, which can be either + * `uploaded`, `processed`, or `error`. + */ + status: 'uploaded' | 'processed' | 'error'; + + /** + * The Unix timestamp (in seconds) for when the file will expire. + */ + expires_at?: number; + + /** + * @deprecated Deprecated. For details on why a fine-tuning training file failed + * validation, see the `error` field on `fine_tuning.job`. + */ + status_details?: string; +} + +/** + * The intended purpose of the uploaded file. One of: - `assistants`: Used in the + * Assistants API - `batch`: Used in the Batch API - `fine-tune`: Used for + * fine-tuning - `vision`: Images used for vision fine-tuning - `user_data`: + * Flexible file type for any purpose - `evals`: Used for eval data sets + */ +export type FilePurpose = 'assistants' | 'batch' | 'fine-tune' | 'vision' | 'user_data' | 'evals'; + +export interface FileCreateParams { + /** + * The File object (not file name) to be uploaded. + */ + file: Uploadable; + + /** + * The intended purpose of the uploaded file. One of: - `assistants`: Used in the + * Assistants API - `batch`: Used in the Batch API - `fine-tune`: Used for + * fine-tuning - `vision`: Images used for vision fine-tuning - `user_data`: + * Flexible file type for any purpose - `evals`: Used for eval data sets + */ + purpose: FilePurpose; + + /** + * The expiration policy for a file. By default, files with `purpose=batch` expire + * after 30 days and all other files are persisted until they are manually deleted. + */ + expires_after?: FileCreateParams.ExpiresAfter; +} + +export namespace FileCreateParams { + /** + * The expiration policy for a file. By default, files with `purpose=batch` expire + * after 30 days and all other files are persisted until they are manually deleted. + */ + export interface ExpiresAfter { + /** + * Anchor timestamp after which the expiration policy applies. Supported anchors: + * `created_at`. + */ + anchor: 'created_at'; + + /** + * The number of seconds after the anchor time that the file will expire. Must be + * between 3600 (1 hour) and 2592000 (30 days). + */ + seconds: number; + } +} + +export interface FileListParams extends CursorPageParams { + /** + * Sort order by the `created_at` timestamp of the objects. `asc` for ascending + * order and `desc` for descending order. + */ + order?: 'asc' | 'desc'; + + /** + * Only return files with the given purpose. + */ + purpose?: string; +} + +export declare namespace Files { + export { + type FileContent as FileContent, + type FileDeleted as FileDeleted, + type FileObject as FileObject, + type FilePurpose as FilePurpose, + type FileObjectsPage as FileObjectsPage, + type FileCreateParams as FileCreateParams, + type FileListParams as FileListParams, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning.ts new file mode 100644 index 0000000000000000000000000000000000000000..01fd61342719f4d3e70bca832250680d1a3be0de --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning.ts @@ -0,0 +1,3 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export * from './fine-tuning/index'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/alpha.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/alpha.ts new file mode 100644 index 0000000000000000000000000000000000000000..446b6431e4dce5a92710c5bf6c14b9ed209b5108 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/alpha.ts @@ -0,0 +1,3 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export * from './alpha/index'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/alpha/alpha.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/alpha/alpha.ts new file mode 100644 index 0000000000000000000000000000000000000000..5a77065e8a99c63be459854d3dba1bbbe4a8b6f3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/alpha/alpha.ts @@ -0,0 +1,27 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../../core/resource'; +import * as GradersAPI from './graders'; +import { + GraderRunParams, + GraderRunResponse, + GraderValidateParams, + GraderValidateResponse, + Graders, +} from './graders'; + +export class Alpha extends APIResource { + graders: GradersAPI.Graders = new GradersAPI.Graders(this._client); +} + +Alpha.Graders = Graders; + +export declare namespace Alpha { + export { + Graders as Graders, + type GraderRunResponse as GraderRunResponse, + type GraderValidateResponse as GraderValidateResponse, + type GraderRunParams as GraderRunParams, + type GraderValidateParams as GraderValidateParams, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/alpha/graders.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/alpha/graders.ts new file mode 100644 index 0000000000000000000000000000000000000000..273c7117e61d43d1d1c1bc74fbfd8aa10a797d52 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/alpha/graders.ts @@ -0,0 +1,171 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../../core/resource'; +import * as GraderModelsAPI from '../../graders/grader-models'; +import { APIPromise } from '../../../core/api-promise'; +import { RequestOptions } from '../../../internal/request-options'; + +export class Graders extends APIResource { + /** + * Run a grader. + * + * @example + * ```ts + * const response = await client.fineTuning.alpha.graders.run({ + * grader: { + * input: 'input', + * name: 'name', + * operation: 'eq', + * reference: 'reference', + * type: 'string_check', + * }, + * model_sample: 'model_sample', + * }); + * ``` + */ + run(body: GraderRunParams, options?: RequestOptions): APIPromise { + return this._client.post('/fine_tuning/alpha/graders/run', { body, ...options }); + } + + /** + * Validate a grader. + * + * @example + * ```ts + * const response = + * await client.fineTuning.alpha.graders.validate({ + * grader: { + * input: 'input', + * name: 'name', + * operation: 'eq', + * reference: 'reference', + * type: 'string_check', + * }, + * }); + * ``` + */ + validate(body: GraderValidateParams, options?: RequestOptions): APIPromise { + return this._client.post('/fine_tuning/alpha/graders/validate', { body, ...options }); + } +} + +export interface GraderRunResponse { + metadata: GraderRunResponse.Metadata; + + model_grader_token_usage_per_model: { [key: string]: unknown }; + + reward: number; + + sub_rewards: { [key: string]: unknown }; +} + +export namespace GraderRunResponse { + export interface Metadata { + errors: Metadata.Errors; + + execution_time: number; + + name: string; + + sampled_model_name: string | null; + + scores: { [key: string]: unknown }; + + token_usage: number | null; + + type: string; + } + + export namespace Metadata { + export interface Errors { + formula_parse_error: boolean; + + invalid_variable_error: boolean; + + model_grader_parse_error: boolean; + + model_grader_refusal_error: boolean; + + model_grader_server_error: boolean; + + model_grader_server_error_details: string | null; + + other_error: boolean; + + python_grader_runtime_error: boolean; + + python_grader_runtime_error_details: string | null; + + python_grader_server_error: boolean; + + python_grader_server_error_type: string | null; + + sample_parse_error: boolean; + + truncated_observation_error: boolean; + + unresponsive_reward_error: boolean; + } + } +} + +export interface GraderValidateResponse { + /** + * The grader used for the fine-tuning job. + */ + grader?: + | GraderModelsAPI.StringCheckGrader + | GraderModelsAPI.TextSimilarityGrader + | GraderModelsAPI.PythonGrader + | GraderModelsAPI.ScoreModelGrader + | GraderModelsAPI.MultiGrader; +} + +export interface GraderRunParams { + /** + * The grader used for the fine-tuning job. + */ + grader: + | GraderModelsAPI.StringCheckGrader + | GraderModelsAPI.TextSimilarityGrader + | GraderModelsAPI.PythonGrader + | GraderModelsAPI.ScoreModelGrader + | GraderModelsAPI.MultiGrader; + + /** + * The model sample to be evaluated. This value will be used to populate the + * `sample` namespace. See + * [the guide](https://platform.openai.com/docs/guides/graders) for more details. + * The `output_json` variable will be populated if the model sample is a valid JSON + * string. + */ + model_sample: string; + + /** + * The dataset item provided to the grader. This will be used to populate the + * `item` namespace. See + * [the guide](https://platform.openai.com/docs/guides/graders) for more details. + */ + item?: unknown; +} + +export interface GraderValidateParams { + /** + * The grader used for the fine-tuning job. + */ + grader: + | GraderModelsAPI.StringCheckGrader + | GraderModelsAPI.TextSimilarityGrader + | GraderModelsAPI.PythonGrader + | GraderModelsAPI.ScoreModelGrader + | GraderModelsAPI.MultiGrader; +} + +export declare namespace Graders { + export { + type GraderRunResponse as GraderRunResponse, + type GraderValidateResponse as GraderValidateResponse, + type GraderRunParams as GraderRunParams, + type GraderValidateParams as GraderValidateParams, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/alpha/index.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/alpha/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..47b229bc33bbab283867c8f66358e674c0995d77 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/alpha/index.ts @@ -0,0 +1,10 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export { Alpha } from './alpha'; +export { + Graders, + type GraderRunResponse, + type GraderValidateResponse, + type GraderRunParams, + type GraderValidateParams, +} from './graders'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/checkpoints.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/checkpoints.ts new file mode 100644 index 0000000000000000000000000000000000000000..eb09063f64a9473b30009f243ad61e62f139ec82 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/checkpoints.ts @@ -0,0 +1,3 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export * from './checkpoints/index'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/checkpoints/checkpoints.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/checkpoints/checkpoints.ts new file mode 100644 index 0000000000000000000000000000000000000000..da055b0e45e0bd4401f8f2995b833013d589a750 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/checkpoints/checkpoints.ts @@ -0,0 +1,33 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../../core/resource'; +import * as PermissionsAPI from './permissions'; +import { + PermissionCreateParams, + PermissionCreateResponse, + PermissionCreateResponsesPage, + PermissionDeleteParams, + PermissionDeleteResponse, + PermissionRetrieveParams, + PermissionRetrieveResponse, + Permissions, +} from './permissions'; + +export class Checkpoints extends APIResource { + permissions: PermissionsAPI.Permissions = new PermissionsAPI.Permissions(this._client); +} + +Checkpoints.Permissions = Permissions; + +export declare namespace Checkpoints { + export { + Permissions as Permissions, + type PermissionCreateResponse as PermissionCreateResponse, + type PermissionRetrieveResponse as PermissionRetrieveResponse, + type PermissionDeleteResponse as PermissionDeleteResponse, + type PermissionCreateResponsesPage as PermissionCreateResponsesPage, + type PermissionCreateParams as PermissionCreateParams, + type PermissionRetrieveParams as PermissionRetrieveParams, + type PermissionDeleteParams as PermissionDeleteParams, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/checkpoints/index.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/checkpoints/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..7e04fc667f42b5153878bc806f888fb336ac0389 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/checkpoints/index.ts @@ -0,0 +1,13 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export { Checkpoints } from './checkpoints'; +export { + Permissions, + type PermissionCreateResponse, + type PermissionRetrieveResponse, + type PermissionDeleteResponse, + type PermissionCreateParams, + type PermissionRetrieveParams, + type PermissionDeleteParams, + type PermissionCreateResponsesPage, +} from './permissions'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/checkpoints/permissions.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/checkpoints/permissions.ts new file mode 100644 index 0000000000000000000000000000000000000000..9217f324cc99c5e75e30b04515c944f2e8bc42fa --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/checkpoints/permissions.ts @@ -0,0 +1,227 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../../core/resource'; +import { APIPromise } from '../../../core/api-promise'; +import { Page, PagePromise } from '../../../core/pagination'; +import { RequestOptions } from '../../../internal/request-options'; +import { path } from '../../../internal/utils/path'; + +export class Permissions extends APIResource { + /** + * **NOTE:** Calling this endpoint requires an [admin API key](../admin-api-keys). + * + * This enables organization owners to share fine-tuned models with other projects + * in their organization. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const permissionCreateResponse of client.fineTuning.checkpoints.permissions.create( + * 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd', + * { project_ids: ['string'] }, + * )) { + * // ... + * } + * ``` + */ + create( + fineTunedModelCheckpoint: string, + body: PermissionCreateParams, + options?: RequestOptions, + ): PagePromise { + return this._client.getAPIList( + path`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, + Page, + { body, method: 'post', ...options }, + ); + } + + /** + * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). + * + * Organization owners can use this endpoint to view all permissions for a + * fine-tuned model checkpoint. + * + * @example + * ```ts + * const permission = + * await client.fineTuning.checkpoints.permissions.retrieve( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + retrieve( + fineTunedModelCheckpoint: string, + query: PermissionRetrieveParams | null | undefined = {}, + options?: RequestOptions, + ): APIPromise { + return this._client.get(path`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, { + query, + ...options, + }); + } + + /** + * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). + * + * Organization owners can use this endpoint to delete a permission for a + * fine-tuned model checkpoint. + * + * @example + * ```ts + * const permission = + * await client.fineTuning.checkpoints.permissions.delete( + * 'cp_zc4Q7MP6XxulcVzj4MZdwsAB', + * { + * fine_tuned_model_checkpoint: + * 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd', + * }, + * ); + * ``` + */ + delete( + permissionID: string, + params: PermissionDeleteParams, + options?: RequestOptions, + ): APIPromise { + const { fine_tuned_model_checkpoint } = params; + return this._client.delete( + path`/fine_tuning/checkpoints/${fine_tuned_model_checkpoint}/permissions/${permissionID}`, + options, + ); + } +} + +// Note: no pagination actually occurs yet, this is for forwards-compatibility. +export type PermissionCreateResponsesPage = Page; + +/** + * The `checkpoint.permission` object represents a permission for a fine-tuned + * model checkpoint. + */ +export interface PermissionCreateResponse { + /** + * The permission identifier, which can be referenced in the API endpoints. + */ + id: string; + + /** + * The Unix timestamp (in seconds) for when the permission was created. + */ + created_at: number; + + /** + * The object type, which is always "checkpoint.permission". + */ + object: 'checkpoint.permission'; + + /** + * The project identifier that the permission is for. + */ + project_id: string; +} + +export interface PermissionRetrieveResponse { + data: Array; + + has_more: boolean; + + object: 'list'; + + first_id?: string | null; + + last_id?: string | null; +} + +export namespace PermissionRetrieveResponse { + /** + * The `checkpoint.permission` object represents a permission for a fine-tuned + * model checkpoint. + */ + export interface Data { + /** + * The permission identifier, which can be referenced in the API endpoints. + */ + id: string; + + /** + * The Unix timestamp (in seconds) for when the permission was created. + */ + created_at: number; + + /** + * The object type, which is always "checkpoint.permission". + */ + object: 'checkpoint.permission'; + + /** + * The project identifier that the permission is for. + */ + project_id: string; + } +} + +export interface PermissionDeleteResponse { + /** + * The ID of the fine-tuned model checkpoint permission that was deleted. + */ + id: string; + + /** + * Whether the fine-tuned model checkpoint permission was successfully deleted. + */ + deleted: boolean; + + /** + * The object type, which is always "checkpoint.permission". + */ + object: 'checkpoint.permission'; +} + +export interface PermissionCreateParams { + /** + * The project identifiers to grant access to. + */ + project_ids: Array; +} + +export interface PermissionRetrieveParams { + /** + * Identifier for the last permission ID from the previous pagination request. + */ + after?: string; + + /** + * Number of permissions to retrieve. + */ + limit?: number; + + /** + * The order in which to retrieve permissions. + */ + order?: 'ascending' | 'descending'; + + /** + * The ID of the project to get permissions for. + */ + project_id?: string; +} + +export interface PermissionDeleteParams { + /** + * The ID of the fine-tuned model checkpoint to delete a permission for. + */ + fine_tuned_model_checkpoint: string; +} + +export declare namespace Permissions { + export { + type PermissionCreateResponse as PermissionCreateResponse, + type PermissionRetrieveResponse as PermissionRetrieveResponse, + type PermissionDeleteResponse as PermissionDeleteResponse, + type PermissionCreateResponsesPage as PermissionCreateResponsesPage, + type PermissionCreateParams as PermissionCreateParams, + type PermissionRetrieveParams as PermissionRetrieveParams, + type PermissionDeleteParams as PermissionDeleteParams, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/fine-tuning.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/fine-tuning.ts new file mode 100644 index 0000000000000000000000000000000000000000..11d441754ea8ce889749acd0c49faf486d781605 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/fine-tuning.ts @@ -0,0 +1,73 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../core/resource'; +import * as MethodsAPI from './methods'; +import { + DpoHyperparameters, + DpoMethod, + Methods, + ReinforcementHyperparameters, + ReinforcementMethod, + SupervisedHyperparameters, + SupervisedMethod, +} from './methods'; +import * as AlphaAPI from './alpha/alpha'; +import { Alpha } from './alpha/alpha'; +import * as CheckpointsAPI from './checkpoints/checkpoints'; +import { Checkpoints } from './checkpoints/checkpoints'; +import * as JobsAPI from './jobs/jobs'; +import { + FineTuningJob, + FineTuningJobEvent, + FineTuningJobEventsPage, + FineTuningJobIntegration, + FineTuningJobWandbIntegration, + FineTuningJobWandbIntegrationObject, + FineTuningJobsPage, + JobCreateParams, + JobListEventsParams, + JobListParams, + Jobs, +} from './jobs/jobs'; + +export class FineTuning extends APIResource { + methods: MethodsAPI.Methods = new MethodsAPI.Methods(this._client); + jobs: JobsAPI.Jobs = new JobsAPI.Jobs(this._client); + checkpoints: CheckpointsAPI.Checkpoints = new CheckpointsAPI.Checkpoints(this._client); + alpha: AlphaAPI.Alpha = new AlphaAPI.Alpha(this._client); +} + +FineTuning.Methods = Methods; +FineTuning.Jobs = Jobs; +FineTuning.Checkpoints = Checkpoints; +FineTuning.Alpha = Alpha; + +export declare namespace FineTuning { + export { + Methods as Methods, + type DpoHyperparameters as DpoHyperparameters, + type DpoMethod as DpoMethod, + type ReinforcementHyperparameters as ReinforcementHyperparameters, + type ReinforcementMethod as ReinforcementMethod, + type SupervisedHyperparameters as SupervisedHyperparameters, + type SupervisedMethod as SupervisedMethod, + }; + + export { + Jobs as Jobs, + type FineTuningJob as FineTuningJob, + type FineTuningJobEvent as FineTuningJobEvent, + type FineTuningJobWandbIntegration as FineTuningJobWandbIntegration, + type FineTuningJobWandbIntegrationObject as FineTuningJobWandbIntegrationObject, + type FineTuningJobIntegration as FineTuningJobIntegration, + type FineTuningJobsPage as FineTuningJobsPage, + type FineTuningJobEventsPage as FineTuningJobEventsPage, + type JobCreateParams as JobCreateParams, + type JobListParams as JobListParams, + type JobListEventsParams as JobListEventsParams, + }; + + export { Checkpoints as Checkpoints }; + + export { Alpha as Alpha }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/index.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..8d4f240f2d6b8e152fbf386b27bc0ef0a8c3ea9d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/index.ts @@ -0,0 +1,27 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export { Alpha } from './alpha/index'; +export { Checkpoints } from './checkpoints/index'; +export { FineTuning } from './fine-tuning'; +export { + Jobs, + type FineTuningJob, + type FineTuningJobEvent, + type FineTuningJobWandbIntegration, + type FineTuningJobWandbIntegrationObject, + type FineTuningJobIntegration, + type JobCreateParams, + type JobListParams, + type JobListEventsParams, + type FineTuningJobsPage, + type FineTuningJobEventsPage, +} from './jobs/index'; +export { + Methods, + type DpoHyperparameters, + type DpoMethod, + type ReinforcementHyperparameters, + type ReinforcementMethod, + type SupervisedHyperparameters, + type SupervisedMethod, +} from './methods'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/jobs.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/jobs.ts new file mode 100644 index 0000000000000000000000000000000000000000..6640de1f209ee5d84b1c6e1f889dc1e7d6793a28 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/jobs.ts @@ -0,0 +1,3 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export * from './jobs/index'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/jobs/checkpoints.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/jobs/checkpoints.ts new file mode 100644 index 0000000000000000000000000000000000000000..868713b6d299c10851ebdb94f51708004215bb94 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/jobs/checkpoints.ts @@ -0,0 +1,107 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../../core/resource'; +import { CursorPage, type CursorPageParams, PagePromise } from '../../../core/pagination'; +import { RequestOptions } from '../../../internal/request-options'; +import { path } from '../../../internal/utils/path'; + +export class Checkpoints extends APIResource { + /** + * List checkpoints for a fine-tuning job. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const fineTuningJobCheckpoint of client.fineTuning.jobs.checkpoints.list( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * )) { + * // ... + * } + * ``` + */ + list( + fineTuningJobID: string, + query: CheckpointListParams | null | undefined = {}, + options?: RequestOptions, + ): PagePromise { + return this._client.getAPIList( + path`/fine_tuning/jobs/${fineTuningJobID}/checkpoints`, + CursorPage, + { query, ...options }, + ); + } +} + +export type FineTuningJobCheckpointsPage = CursorPage; + +/** + * The `fine_tuning.job.checkpoint` object represents a model checkpoint for a + * fine-tuning job that is ready to use. + */ +export interface FineTuningJobCheckpoint { + /** + * The checkpoint identifier, which can be referenced in the API endpoints. + */ + id: string; + + /** + * The Unix timestamp (in seconds) for when the checkpoint was created. + */ + created_at: number; + + /** + * The name of the fine-tuned checkpoint model that is created. + */ + fine_tuned_model_checkpoint: string; + + /** + * The name of the fine-tuning job that this checkpoint was created from. + */ + fine_tuning_job_id: string; + + /** + * Metrics at the step number during the fine-tuning job. + */ + metrics: FineTuningJobCheckpoint.Metrics; + + /** + * The object type, which is always "fine_tuning.job.checkpoint". + */ + object: 'fine_tuning.job.checkpoint'; + + /** + * The step number that the checkpoint was created at. + */ + step_number: number; +} + +export namespace FineTuningJobCheckpoint { + /** + * Metrics at the step number during the fine-tuning job. + */ + export interface Metrics { + full_valid_loss?: number; + + full_valid_mean_token_accuracy?: number; + + step?: number; + + train_loss?: number; + + train_mean_token_accuracy?: number; + + valid_loss?: number; + + valid_mean_token_accuracy?: number; + } +} + +export interface CheckpointListParams extends CursorPageParams {} + +export declare namespace Checkpoints { + export { + type FineTuningJobCheckpoint as FineTuningJobCheckpoint, + type FineTuningJobCheckpointsPage as FineTuningJobCheckpointsPage, + type CheckpointListParams as CheckpointListParams, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/jobs/index.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/jobs/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..18a2b1a93dccd70520a6a9c5dcd834f9e04a50c3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/jobs/index.ts @@ -0,0 +1,21 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export { + Checkpoints, + type FineTuningJobCheckpoint, + type CheckpointListParams, + type FineTuningJobCheckpointsPage, +} from './checkpoints'; +export { + Jobs, + type FineTuningJob, + type FineTuningJobEvent, + type FineTuningJobWandbIntegration, + type FineTuningJobWandbIntegrationObject, + type FineTuningJobIntegration, + type JobCreateParams, + type JobListParams, + type JobListEventsParams, + type FineTuningJobsPage, + type FineTuningJobEventsPage, +} from './jobs'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/jobs/jobs.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/jobs/jobs.ts new file mode 100644 index 0000000000000000000000000000000000000000..91935a49619b4b07a5bdbbd99393f756514bf103 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/jobs/jobs.ts @@ -0,0 +1,654 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../../core/resource'; +import * as Shared from '../../shared'; +import * as MethodsAPI from '../methods'; +import * as CheckpointsAPI from './checkpoints'; +import { + CheckpointListParams, + Checkpoints, + FineTuningJobCheckpoint, + FineTuningJobCheckpointsPage, +} from './checkpoints'; +import { APIPromise } from '../../../core/api-promise'; +import { CursorPage, type CursorPageParams, PagePromise } from '../../../core/pagination'; +import { RequestOptions } from '../../../internal/request-options'; +import { path } from '../../../internal/utils/path'; + +export class Jobs extends APIResource { + checkpoints: CheckpointsAPI.Checkpoints = new CheckpointsAPI.Checkpoints(this._client); + + /** + * Creates a fine-tuning job which begins the process of creating a new model from + * a given dataset. + * + * Response includes details of the enqueued job including job status and the name + * of the fine-tuned models once complete. + * + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization) + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.create({ + * model: 'gpt-4o-mini', + * training_file: 'file-abc123', + * }); + * ``` + */ + create(body: JobCreateParams, options?: RequestOptions): APIPromise { + return this._client.post('/fine_tuning/jobs', { body, ...options }); + } + + /** + * Get info about a fine-tuning job. + * + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization) + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.retrieve( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + retrieve(fineTuningJobID: string, options?: RequestOptions): APIPromise { + return this._client.get(path`/fine_tuning/jobs/${fineTuningJobID}`, options); + } + + /** + * List your organization's fine-tuning jobs + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const fineTuningJob of client.fineTuning.jobs.list()) { + * // ... + * } + * ``` + */ + list( + query: JobListParams | null | undefined = {}, + options?: RequestOptions, + ): PagePromise { + return this._client.getAPIList('/fine_tuning/jobs', CursorPage, { query, ...options }); + } + + /** + * Immediately cancel a fine-tune job. + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.cancel( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + cancel(fineTuningJobID: string, options?: RequestOptions): APIPromise { + return this._client.post(path`/fine_tuning/jobs/${fineTuningJobID}/cancel`, options); + } + + /** + * Get status updates for a fine-tuning job. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const fineTuningJobEvent of client.fineTuning.jobs.listEvents( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * )) { + * // ... + * } + * ``` + */ + listEvents( + fineTuningJobID: string, + query: JobListEventsParams | null | undefined = {}, + options?: RequestOptions, + ): PagePromise { + return this._client.getAPIList( + path`/fine_tuning/jobs/${fineTuningJobID}/events`, + CursorPage, + { query, ...options }, + ); + } + + /** + * Pause a fine-tune job. + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.pause( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + pause(fineTuningJobID: string, options?: RequestOptions): APIPromise { + return this._client.post(path`/fine_tuning/jobs/${fineTuningJobID}/pause`, options); + } + + /** + * Resume a fine-tune job. + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.resume( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + resume(fineTuningJobID: string, options?: RequestOptions): APIPromise { + return this._client.post(path`/fine_tuning/jobs/${fineTuningJobID}/resume`, options); + } +} + +export type FineTuningJobsPage = CursorPage; + +export type FineTuningJobEventsPage = CursorPage; + +/** + * The `fine_tuning.job` object represents a fine-tuning job that has been created + * through the API. + */ +export interface FineTuningJob { + /** + * The object identifier, which can be referenced in the API endpoints. + */ + id: string; + + /** + * The Unix timestamp (in seconds) for when the fine-tuning job was created. + */ + created_at: number; + + /** + * For fine-tuning jobs that have `failed`, this will contain more information on + * the cause of the failure. + */ + error: FineTuningJob.Error | null; + + /** + * The name of the fine-tuned model that is being created. The value will be null + * if the fine-tuning job is still running. + */ + fine_tuned_model: string | null; + + /** + * The Unix timestamp (in seconds) for when the fine-tuning job was finished. The + * value will be null if the fine-tuning job is still running. + */ + finished_at: number | null; + + /** + * The hyperparameters used for the fine-tuning job. This value will only be + * returned when running `supervised` jobs. + */ + hyperparameters: FineTuningJob.Hyperparameters; + + /** + * The base model that is being fine-tuned. + */ + model: string; + + /** + * The object type, which is always "fine_tuning.job". + */ + object: 'fine_tuning.job'; + + /** + * The organization that owns the fine-tuning job. + */ + organization_id: string; + + /** + * The compiled results file ID(s) for the fine-tuning job. You can retrieve the + * results with the + * [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). + */ + result_files: Array; + + /** + * The seed used for the fine-tuning job. + */ + seed: number; + + /** + * The current status of the fine-tuning job, which can be either + * `validating_files`, `queued`, `running`, `succeeded`, `failed`, or `cancelled`. + */ + status: 'validating_files' | 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelled'; + + /** + * The total number of billable tokens processed by this fine-tuning job. The value + * will be null if the fine-tuning job is still running. + */ + trained_tokens: number | null; + + /** + * The file ID used for training. You can retrieve the training data with the + * [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). + */ + training_file: string; + + /** + * The file ID used for validation. You can retrieve the validation results with + * the + * [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). + */ + validation_file: string | null; + + /** + * The Unix timestamp (in seconds) for when the fine-tuning job is estimated to + * finish. The value will be null if the fine-tuning job is not running. + */ + estimated_finish?: number | null; + + /** + * A list of integrations to enable for this fine-tuning job. + */ + integrations?: Array | null; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; + + /** + * The method used for fine-tuning. + */ + method?: FineTuningJob.Method; +} + +export namespace FineTuningJob { + /** + * For fine-tuning jobs that have `failed`, this will contain more information on + * the cause of the failure. + */ + export interface Error { + /** + * A machine-readable error code. + */ + code: string; + + /** + * A human-readable error message. + */ + message: string; + + /** + * The parameter that was invalid, usually `training_file` or `validation_file`. + * This field will be null if the failure was not parameter-specific. + */ + param: string | null; + } + + /** + * The hyperparameters used for the fine-tuning job. This value will only be + * returned when running `supervised` jobs. + */ + export interface Hyperparameters { + /** + * Number of examples in each batch. A larger batch size means that model + * parameters are updated less frequently, but with lower variance. + */ + batch_size?: 'auto' | number | null; + + /** + * Scaling factor for the learning rate. A smaller learning rate may be useful to + * avoid overfitting. + */ + learning_rate_multiplier?: 'auto' | number; + + /** + * The number of epochs to train the model for. An epoch refers to one full cycle + * through the training dataset. + */ + n_epochs?: 'auto' | number; + } + + /** + * The method used for fine-tuning. + */ + export interface Method { + /** + * The type of method. Is either `supervised`, `dpo`, or `reinforcement`. + */ + type: 'supervised' | 'dpo' | 'reinforcement'; + + /** + * Configuration for the DPO fine-tuning method. + */ + dpo?: MethodsAPI.DpoMethod; + + /** + * Configuration for the reinforcement fine-tuning method. + */ + reinforcement?: MethodsAPI.ReinforcementMethod; + + /** + * Configuration for the supervised fine-tuning method. + */ + supervised?: MethodsAPI.SupervisedMethod; + } +} + +/** + * Fine-tuning job event object + */ +export interface FineTuningJobEvent { + /** + * The object identifier. + */ + id: string; + + /** + * The Unix timestamp (in seconds) for when the fine-tuning job was created. + */ + created_at: number; + + /** + * The log level of the event. + */ + level: 'info' | 'warn' | 'error'; + + /** + * The message of the event. + */ + message: string; + + /** + * The object type, which is always "fine_tuning.job.event". + */ + object: 'fine_tuning.job.event'; + + /** + * The data associated with the event. + */ + data?: unknown; + + /** + * The type of event. + */ + type?: 'message' | 'metrics'; +} + +/** + * The settings for your integration with Weights and Biases. This payload + * specifies the project that metrics will be sent to. Optionally, you can set an + * explicit display name for your run, add tags to your run, and set a default + * entity (team, username, etc) to be associated with your run. + */ +export interface FineTuningJobWandbIntegration { + /** + * The name of the project that the new run will be created under. + */ + project: string; + + /** + * The entity to use for the run. This allows you to set the team or username of + * the WandB user that you would like associated with the run. If not set, the + * default entity for the registered WandB API key is used. + */ + entity?: string | null; + + /** + * A display name to set for the run. If not set, we will use the Job ID as the + * name. + */ + name?: string | null; + + /** + * A list of tags to be attached to the newly created run. These tags are passed + * through directly to WandB. Some default tags are generated by OpenAI: + * "openai/finetune", "openai/{base-model}", "openai/{ftjob-abcdef}". + */ + tags?: Array; +} + +export interface FineTuningJobWandbIntegrationObject { + /** + * The type of the integration being enabled for the fine-tuning job + */ + type: 'wandb'; + + /** + * The settings for your integration with Weights and Biases. This payload + * specifies the project that metrics will be sent to. Optionally, you can set an + * explicit display name for your run, add tags to your run, and set a default + * entity (team, username, etc) to be associated with your run. + */ + wandb: FineTuningJobWandbIntegration; +} + +export type FineTuningJobIntegration = FineTuningJobWandbIntegrationObject; + +export interface JobCreateParams { + /** + * The name of the model to fine-tune. You can select one of the + * [supported models](https://platform.openai.com/docs/guides/fine-tuning#which-models-can-be-fine-tuned). + */ + model: (string & {}) | 'babbage-002' | 'davinci-002' | 'gpt-3.5-turbo' | 'gpt-4o-mini'; + + /** + * The ID of an uploaded file that contains training data. + * + * See [upload file](https://platform.openai.com/docs/api-reference/files/create) + * for how to upload a file. + * + * Your dataset must be formatted as a JSONL file. Additionally, you must upload + * your file with the purpose `fine-tune`. + * + * The contents of the file should differ depending on if the model uses the + * [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input), + * [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) + * format, or if the fine-tuning method uses the + * [preference](https://platform.openai.com/docs/api-reference/fine-tuning/preference-input) + * format. + * + * See the + * [fine-tuning guide](https://platform.openai.com/docs/guides/model-optimization) + * for more details. + */ + training_file: string; + + /** + * @deprecated The hyperparameters used for the fine-tuning job. This value is now + * deprecated in favor of `method`, and should be passed in under the `method` + * parameter. + */ + hyperparameters?: JobCreateParams.Hyperparameters; + + /** + * A list of integrations to enable for your fine-tuning job. + */ + integrations?: Array | null; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; + + /** + * The method used for fine-tuning. + */ + method?: JobCreateParams.Method; + + /** + * The seed controls the reproducibility of the job. Passing in the same seed and + * job parameters should produce the same results, but may differ in rare cases. If + * a seed is not specified, one will be generated for you. + */ + seed?: number | null; + + /** + * A string of up to 64 characters that will be added to your fine-tuned model + * name. + * + * For example, a `suffix` of "custom-model-name" would produce a model name like + * `ft:gpt-4o-mini:openai:custom-model-name:7p4lURel`. + */ + suffix?: string | null; + + /** + * The ID of an uploaded file that contains validation data. + * + * If you provide this file, the data is used to generate validation metrics + * periodically during fine-tuning. These metrics can be viewed in the fine-tuning + * results file. The same data should not be present in both train and validation + * files. + * + * Your dataset must be formatted as a JSONL file. You must upload your file with + * the purpose `fine-tune`. + * + * See the + * [fine-tuning guide](https://platform.openai.com/docs/guides/model-optimization) + * for more details. + */ + validation_file?: string | null; +} + +export namespace JobCreateParams { + /** + * @deprecated The hyperparameters used for the fine-tuning job. This value is now + * deprecated in favor of `method`, and should be passed in under the `method` + * parameter. + */ + export interface Hyperparameters { + /** + * Number of examples in each batch. A larger batch size means that model + * parameters are updated less frequently, but with lower variance. + */ + batch_size?: 'auto' | number; + + /** + * Scaling factor for the learning rate. A smaller learning rate may be useful to + * avoid overfitting. + */ + learning_rate_multiplier?: 'auto' | number; + + /** + * The number of epochs to train the model for. An epoch refers to one full cycle + * through the training dataset. + */ + n_epochs?: 'auto' | number; + } + + export interface Integration { + /** + * The type of integration to enable. Currently, only "wandb" (Weights and Biases) + * is supported. + */ + type: 'wandb'; + + /** + * The settings for your integration with Weights and Biases. This payload + * specifies the project that metrics will be sent to. Optionally, you can set an + * explicit display name for your run, add tags to your run, and set a default + * entity (team, username, etc) to be associated with your run. + */ + wandb: Integration.Wandb; + } + + export namespace Integration { + /** + * The settings for your integration with Weights and Biases. This payload + * specifies the project that metrics will be sent to. Optionally, you can set an + * explicit display name for your run, add tags to your run, and set a default + * entity (team, username, etc) to be associated with your run. + */ + export interface Wandb { + /** + * The name of the project that the new run will be created under. + */ + project: string; + + /** + * The entity to use for the run. This allows you to set the team or username of + * the WandB user that you would like associated with the run. If not set, the + * default entity for the registered WandB API key is used. + */ + entity?: string | null; + + /** + * A display name to set for the run. If not set, we will use the Job ID as the + * name. + */ + name?: string | null; + + /** + * A list of tags to be attached to the newly created run. These tags are passed + * through directly to WandB. Some default tags are generated by OpenAI: + * "openai/finetune", "openai/{base-model}", "openai/{ftjob-abcdef}". + */ + tags?: Array; + } + } + + /** + * The method used for fine-tuning. + */ + export interface Method { + /** + * The type of method. Is either `supervised`, `dpo`, or `reinforcement`. + */ + type: 'supervised' | 'dpo' | 'reinforcement'; + + /** + * Configuration for the DPO fine-tuning method. + */ + dpo?: MethodsAPI.DpoMethod; + + /** + * Configuration for the reinforcement fine-tuning method. + */ + reinforcement?: MethodsAPI.ReinforcementMethod; + + /** + * Configuration for the supervised fine-tuning method. + */ + supervised?: MethodsAPI.SupervisedMethod; + } +} + +export interface JobListParams extends CursorPageParams { + /** + * Optional metadata filter. To filter, use the syntax `metadata[k]=v`. + * Alternatively, set `metadata=null` to indicate no metadata. + */ + metadata?: { [key: string]: string } | null; +} + +export interface JobListEventsParams extends CursorPageParams {} + +Jobs.Checkpoints = Checkpoints; + +export declare namespace Jobs { + export { + type FineTuningJob as FineTuningJob, + type FineTuningJobEvent as FineTuningJobEvent, + type FineTuningJobWandbIntegration as FineTuningJobWandbIntegration, + type FineTuningJobWandbIntegrationObject as FineTuningJobWandbIntegrationObject, + type FineTuningJobIntegration as FineTuningJobIntegration, + type FineTuningJobsPage as FineTuningJobsPage, + type FineTuningJobEventsPage as FineTuningJobEventsPage, + type JobCreateParams as JobCreateParams, + type JobListParams as JobListParams, + type JobListEventsParams as JobListEventsParams, + }; + + export { + Checkpoints as Checkpoints, + type FineTuningJobCheckpoint as FineTuningJobCheckpoint, + type FineTuningJobCheckpointsPage as FineTuningJobCheckpointsPage, + type CheckpointListParams as CheckpointListParams, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/methods.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/methods.ts new file mode 100644 index 0000000000000000000000000000000000000000..9c78d584bddddf2a5d5c41477db3f68ef7e80512 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/fine-tuning/methods.ts @@ -0,0 +1,152 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../core/resource'; +import * as GraderModelsAPI from '../graders/grader-models'; + +export class Methods extends APIResource {} + +/** + * The hyperparameters used for the DPO fine-tuning job. + */ +export interface DpoHyperparameters { + /** + * Number of examples in each batch. A larger batch size means that model + * parameters are updated less frequently, but with lower variance. + */ + batch_size?: 'auto' | number; + + /** + * The beta value for the DPO method. A higher beta value will increase the weight + * of the penalty between the policy and reference model. + */ + beta?: 'auto' | number; + + /** + * Scaling factor for the learning rate. A smaller learning rate may be useful to + * avoid overfitting. + */ + learning_rate_multiplier?: 'auto' | number; + + /** + * The number of epochs to train the model for. An epoch refers to one full cycle + * through the training dataset. + */ + n_epochs?: 'auto' | number; +} + +/** + * Configuration for the DPO fine-tuning method. + */ +export interface DpoMethod { + /** + * The hyperparameters used for the DPO fine-tuning job. + */ + hyperparameters?: DpoHyperparameters; +} + +/** + * The hyperparameters used for the reinforcement fine-tuning job. + */ +export interface ReinforcementHyperparameters { + /** + * Number of examples in each batch. A larger batch size means that model + * parameters are updated less frequently, but with lower variance. + */ + batch_size?: 'auto' | number; + + /** + * Multiplier on amount of compute used for exploring search space during training. + */ + compute_multiplier?: 'auto' | number; + + /** + * The number of training steps between evaluation runs. + */ + eval_interval?: 'auto' | number; + + /** + * Number of evaluation samples to generate per training step. + */ + eval_samples?: 'auto' | number; + + /** + * Scaling factor for the learning rate. A smaller learning rate may be useful to + * avoid overfitting. + */ + learning_rate_multiplier?: 'auto' | number; + + /** + * The number of epochs to train the model for. An epoch refers to one full cycle + * through the training dataset. + */ + n_epochs?: 'auto' | number; + + /** + * Level of reasoning effort. + */ + reasoning_effort?: 'default' | 'low' | 'medium' | 'high'; +} + +/** + * Configuration for the reinforcement fine-tuning method. + */ +export interface ReinforcementMethod { + /** + * The grader used for the fine-tuning job. + */ + grader: + | GraderModelsAPI.StringCheckGrader + | GraderModelsAPI.TextSimilarityGrader + | GraderModelsAPI.PythonGrader + | GraderModelsAPI.ScoreModelGrader + | GraderModelsAPI.MultiGrader; + + /** + * The hyperparameters used for the reinforcement fine-tuning job. + */ + hyperparameters?: ReinforcementHyperparameters; +} + +/** + * The hyperparameters used for the fine-tuning job. + */ +export interface SupervisedHyperparameters { + /** + * Number of examples in each batch. A larger batch size means that model + * parameters are updated less frequently, but with lower variance. + */ + batch_size?: 'auto' | number; + + /** + * Scaling factor for the learning rate. A smaller learning rate may be useful to + * avoid overfitting. + */ + learning_rate_multiplier?: 'auto' | number; + + /** + * The number of epochs to train the model for. An epoch refers to one full cycle + * through the training dataset. + */ + n_epochs?: 'auto' | number; +} + +/** + * Configuration for the supervised fine-tuning method. + */ +export interface SupervisedMethod { + /** + * The hyperparameters used for the fine-tuning job. + */ + hyperparameters?: SupervisedHyperparameters; +} + +export declare namespace Methods { + export { + type DpoHyperparameters as DpoHyperparameters, + type DpoMethod as DpoMethod, + type ReinforcementHyperparameters as ReinforcementHyperparameters, + type ReinforcementMethod as ReinforcementMethod, + type SupervisedHyperparameters as SupervisedHyperparameters, + type SupervisedMethod as SupervisedMethod, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/graders.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/graders.ts new file mode 100644 index 0000000000000000000000000000000000000000..2ea9aa959a9b9daaf7e8ff87ef67554ed7eac9b3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/graders.ts @@ -0,0 +1,3 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export * from './graders/index'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/graders/grader-models.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/graders/grader-models.ts new file mode 100644 index 0000000000000000000000000000000000000000..36908007dcb91962a49a3385168e25db80ea60a0 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/graders/grader-models.ts @@ -0,0 +1,340 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../core/resource'; +import * as ResponsesAPI from '../responses/responses'; + +export class GraderModels extends APIResource {} + +/** + * A LabelModelGrader object which uses a model to assign labels to each item in + * the evaluation. + */ +export interface LabelModelGrader { + input: Array; + + /** + * The labels to assign to each item in the evaluation. + */ + labels: Array; + + /** + * The model to use for the evaluation. Must support structured outputs. + */ + model: string; + + /** + * The name of the grader. + */ + name: string; + + /** + * The labels that indicate a passing result. Must be a subset of labels. + */ + passing_labels: Array; + + /** + * The object type, which is always `label_model`. + */ + type: 'label_model'; +} + +export namespace LabelModelGrader { + /** + * A message input to the model with a role indicating instruction following + * hierarchy. Instructions given with the `developer` or `system` role take + * precedence over instructions given with the `user` role. Messages with the + * `assistant` role are presumed to have been generated by the model in previous + * interactions. + */ + export interface Input { + /** + * Inputs to the model - can contain template strings. + */ + content: string | ResponsesAPI.ResponseInputText | Input.OutputText | Input.InputImage | Array; + + /** + * The role of the message input. One of `user`, `assistant`, `system`, or + * `developer`. + */ + role: 'user' | 'assistant' | 'system' | 'developer'; + + /** + * The type of the message input. Always `message`. + */ + type?: 'message'; + } + + export namespace Input { + /** + * A text output from the model. + */ + export interface OutputText { + /** + * The text output from the model. + */ + text: string; + + /** + * The type of the output text. Always `output_text`. + */ + type: 'output_text'; + } + + /** + * An image input to the model. + */ + export interface InputImage { + /** + * The URL of the image input. + */ + image_url: string; + + /** + * The type of the image input. Always `input_image`. + */ + type: 'input_image'; + + /** + * The detail level of the image to be sent to the model. One of `high`, `low`, or + * `auto`. Defaults to `auto`. + */ + detail?: string; + } + } +} + +/** + * A MultiGrader object combines the output of multiple graders to produce a single + * score. + */ +export interface MultiGrader { + /** + * A formula to calculate the output based on grader results. + */ + calculate_output: string; + + /** + * A StringCheckGrader object that performs a string comparison between input and + * reference using a specified operation. + */ + graders: StringCheckGrader | TextSimilarityGrader | PythonGrader | ScoreModelGrader | LabelModelGrader; + + /** + * The name of the grader. + */ + name: string; + + /** + * The object type, which is always `multi`. + */ + type: 'multi'; +} + +/** + * A PythonGrader object that runs a python script on the input. + */ +export interface PythonGrader { + /** + * The name of the grader. + */ + name: string; + + /** + * The source code of the python script. + */ + source: string; + + /** + * The object type, which is always `python`. + */ + type: 'python'; + + /** + * The image tag to use for the python script. + */ + image_tag?: string; +} + +/** + * A ScoreModelGrader object that uses a model to assign a score to the input. + */ +export interface ScoreModelGrader { + /** + * The input text. This may include template strings. + */ + input: Array; + + /** + * The model to use for the evaluation. + */ + model: string; + + /** + * The name of the grader. + */ + name: string; + + /** + * The object type, which is always `score_model`. + */ + type: 'score_model'; + + /** + * The range of the score. Defaults to `[0, 1]`. + */ + range?: Array; + + /** + * The sampling parameters for the model. + */ + sampling_params?: unknown; +} + +export namespace ScoreModelGrader { + /** + * A message input to the model with a role indicating instruction following + * hierarchy. Instructions given with the `developer` or `system` role take + * precedence over instructions given with the `user` role. Messages with the + * `assistant` role are presumed to have been generated by the model in previous + * interactions. + */ + export interface Input { + /** + * Inputs to the model - can contain template strings. + */ + content: string | ResponsesAPI.ResponseInputText | Input.OutputText | Input.InputImage | Array; + + /** + * The role of the message input. One of `user`, `assistant`, `system`, or + * `developer`. + */ + role: 'user' | 'assistant' | 'system' | 'developer'; + + /** + * The type of the message input. Always `message`. + */ + type?: 'message'; + } + + export namespace Input { + /** + * A text output from the model. + */ + export interface OutputText { + /** + * The text output from the model. + */ + text: string; + + /** + * The type of the output text. Always `output_text`. + */ + type: 'output_text'; + } + + /** + * An image input to the model. + */ + export interface InputImage { + /** + * The URL of the image input. + */ + image_url: string; + + /** + * The type of the image input. Always `input_image`. + */ + type: 'input_image'; + + /** + * The detail level of the image to be sent to the model. One of `high`, `low`, or + * `auto`. Defaults to `auto`. + */ + detail?: string; + } + } +} + +/** + * A StringCheckGrader object that performs a string comparison between input and + * reference using a specified operation. + */ +export interface StringCheckGrader { + /** + * The input text. This may include template strings. + */ + input: string; + + /** + * The name of the grader. + */ + name: string; + + /** + * The string check operation to perform. One of `eq`, `ne`, `like`, or `ilike`. + */ + operation: 'eq' | 'ne' | 'like' | 'ilike'; + + /** + * The reference text. This may include template strings. + */ + reference: string; + + /** + * The object type, which is always `string_check`. + */ + type: 'string_check'; +} + +/** + * A TextSimilarityGrader object which grades text based on similarity metrics. + */ +export interface TextSimilarityGrader { + /** + * The evaluation metric to use. One of `cosine`, `fuzzy_match`, `bleu`, `gleu`, + * `meteor`, `rouge_1`, `rouge_2`, `rouge_3`, `rouge_4`, `rouge_5`, or `rouge_l`. + */ + evaluation_metric: + | 'cosine' + | 'fuzzy_match' + | 'bleu' + | 'gleu' + | 'meteor' + | 'rouge_1' + | 'rouge_2' + | 'rouge_3' + | 'rouge_4' + | 'rouge_5' + | 'rouge_l'; + + /** + * The text being graded. + */ + input: string; + + /** + * The name of the grader. + */ + name: string; + + /** + * The text being graded against. + */ + reference: string; + + /** + * The type of grader. + */ + type: 'text_similarity'; +} + +export declare namespace GraderModels { + export { + type LabelModelGrader as LabelModelGrader, + type MultiGrader as MultiGrader, + type PythonGrader as PythonGrader, + type ScoreModelGrader as ScoreModelGrader, + type StringCheckGrader as StringCheckGrader, + type TextSimilarityGrader as TextSimilarityGrader, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/graders/graders.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/graders/graders.ts new file mode 100644 index 0000000000000000000000000000000000000000..d337e02aea4f8a4ef2f87689f11d7f8dd2e801d7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/graders/graders.ts @@ -0,0 +1,31 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../core/resource'; +import * as GraderModelsAPI from './grader-models'; +import { + GraderModels, + LabelModelGrader, + MultiGrader, + PythonGrader, + ScoreModelGrader, + StringCheckGrader, + TextSimilarityGrader, +} from './grader-models'; + +export class Graders extends APIResource { + graderModels: GraderModelsAPI.GraderModels = new GraderModelsAPI.GraderModels(this._client); +} + +Graders.GraderModels = GraderModels; + +export declare namespace Graders { + export { + GraderModels as GraderModels, + type LabelModelGrader as LabelModelGrader, + type MultiGrader as MultiGrader, + type PythonGrader as PythonGrader, + type ScoreModelGrader as ScoreModelGrader, + type StringCheckGrader as StringCheckGrader, + type TextSimilarityGrader as TextSimilarityGrader, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/graders/index.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/graders/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..82d557a6a856054c369f4dd91459c25babca204d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/graders/index.ts @@ -0,0 +1,12 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export { + GraderModels, + type LabelModelGrader, + type MultiGrader, + type PythonGrader, + type ScoreModelGrader, + type StringCheckGrader, + type TextSimilarityGrader, +} from './grader-models'; +export { Graders } from './graders'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/images.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/images.ts new file mode 100644 index 0000000000000000000000000000000000000000..8f1dad624fa12815d1c9dadeb36bdc4c0c8273d7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/images.ts @@ -0,0 +1,822 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../core/resource'; +import * as ImagesAPI from './images'; +import { APIPromise } from '../core/api-promise'; +import { Stream } from '../core/streaming'; +import { type Uploadable } from '../core/uploads'; +import { RequestOptions } from '../internal/request-options'; +import { multipartFormRequestOptions } from '../internal/uploads'; + +export class Images extends APIResource { + /** + * Creates a variation of a given image. This endpoint only supports `dall-e-2`. + * + * @example + * ```ts + * const imagesResponse = await client.images.createVariation({ + * image: fs.createReadStream('otter.png'), + * }); + * ``` + */ + createVariation(body: ImageCreateVariationParams, options?: RequestOptions): APIPromise { + return this._client.post( + '/images/variations', + multipartFormRequestOptions({ body, ...options }, this._client), + ); + } + + /** + * Creates an edited or extended image given one or more source images and a + * prompt. This endpoint only supports `gpt-image-1` and `dall-e-2`. + * + * @example + * ```ts + * const imagesResponse = await client.images.edit({ + * image: fs.createReadStream('path/to/file'), + * prompt: 'A cute baby sea otter wearing a beret', + * }); + * ``` + */ + edit(body: ImageEditParamsNonStreaming, options?: RequestOptions): APIPromise; + edit(body: ImageEditParamsStreaming, options?: RequestOptions): APIPromise>; + edit( + body: ImageEditParamsBase, + options?: RequestOptions, + ): APIPromise | ImagesResponse>; + edit( + body: ImageEditParams, + options?: RequestOptions, + ): APIPromise | APIPromise> { + return this._client.post( + '/images/edits', + multipartFormRequestOptions({ body, ...options, stream: body.stream ?? false }, this._client), + ) as APIPromise | APIPromise>; + } + + /** + * Creates an image given a prompt. + * [Learn more](https://platform.openai.com/docs/guides/images). + * + * @example + * ```ts + * const imagesResponse = await client.images.generate({ + * prompt: 'A cute baby sea otter', + * }); + * ``` + */ + generate(body: ImageGenerateParamsNonStreaming, options?: RequestOptions): APIPromise; + generate( + body: ImageGenerateParamsStreaming, + options?: RequestOptions, + ): APIPromise>; + generate( + body: ImageGenerateParamsBase, + options?: RequestOptions, + ): APIPromise | ImagesResponse>; + generate( + body: ImageGenerateParams, + options?: RequestOptions, + ): APIPromise | APIPromise> { + return this._client.post('/images/generations', { body, ...options, stream: body.stream ?? false }) as + | APIPromise + | APIPromise>; + } +} + +/** + * Represents the content or the URL of an image generated by the OpenAI API. + */ +export interface Image { + /** + * The base64-encoded JSON of the generated image. Default value for `gpt-image-1`, + * and only present if `response_format` is set to `b64_json` for `dall-e-2` and + * `dall-e-3`. + */ + b64_json?: string; + + /** + * For `dall-e-3` only, the revised prompt that was used to generate the image. + */ + revised_prompt?: string; + + /** + * When using `dall-e-2` or `dall-e-3`, the URL of the generated image if + * `response_format` is set to `url` (default value). Unsupported for + * `gpt-image-1`. + */ + url?: string; +} + +/** + * Emitted when image editing has completed and the final image is available. + */ +export interface ImageEditCompletedEvent { + /** + * Base64-encoded final edited image data, suitable for rendering as an image. + */ + b64_json: string; + + /** + * The background setting for the edited image. + */ + background: 'transparent' | 'opaque' | 'auto'; + + /** + * The Unix timestamp when the event was created. + */ + created_at: number; + + /** + * The output format for the edited image. + */ + output_format: 'png' | 'webp' | 'jpeg'; + + /** + * The quality setting for the edited image. + */ + quality: 'low' | 'medium' | 'high' | 'auto'; + + /** + * The size of the edited image. + */ + size: '1024x1024' | '1024x1536' | '1536x1024' | 'auto'; + + /** + * The type of the event. Always `image_edit.completed`. + */ + type: 'image_edit.completed'; + + /** + * For `gpt-image-1` only, the token usage information for the image generation. + */ + usage: ImageEditCompletedEvent.Usage; +} + +export namespace ImageEditCompletedEvent { + /** + * For `gpt-image-1` only, the token usage information for the image generation. + */ + export interface Usage { + /** + * The number of tokens (images and text) in the input prompt. + */ + input_tokens: number; + + /** + * The input tokens detailed information for the image generation. + */ + input_tokens_details: Usage.InputTokensDetails; + + /** + * The number of image tokens in the output image. + */ + output_tokens: number; + + /** + * The total number of tokens (images and text) used for the image generation. + */ + total_tokens: number; + } + + export namespace Usage { + /** + * The input tokens detailed information for the image generation. + */ + export interface InputTokensDetails { + /** + * The number of image tokens in the input prompt. + */ + image_tokens: number; + + /** + * The number of text tokens in the input prompt. + */ + text_tokens: number; + } + } +} + +/** + * Emitted when a partial image is available during image editing streaming. + */ +export interface ImageEditPartialImageEvent { + /** + * Base64-encoded partial image data, suitable for rendering as an image. + */ + b64_json: string; + + /** + * The background setting for the requested edited image. + */ + background: 'transparent' | 'opaque' | 'auto'; + + /** + * The Unix timestamp when the event was created. + */ + created_at: number; + + /** + * The output format for the requested edited image. + */ + output_format: 'png' | 'webp' | 'jpeg'; + + /** + * 0-based index for the partial image (streaming). + */ + partial_image_index: number; + + /** + * The quality setting for the requested edited image. + */ + quality: 'low' | 'medium' | 'high' | 'auto'; + + /** + * The size of the requested edited image. + */ + size: '1024x1024' | '1024x1536' | '1536x1024' | 'auto'; + + /** + * The type of the event. Always `image_edit.partial_image`. + */ + type: 'image_edit.partial_image'; +} + +/** + * Emitted when a partial image is available during image editing streaming. + */ +export type ImageEditStreamEvent = ImageEditPartialImageEvent | ImageEditCompletedEvent; + +/** + * Emitted when image generation has completed and the final image is available. + */ +export interface ImageGenCompletedEvent { + /** + * Base64-encoded image data, suitable for rendering as an image. + */ + b64_json: string; + + /** + * The background setting for the generated image. + */ + background: 'transparent' | 'opaque' | 'auto'; + + /** + * The Unix timestamp when the event was created. + */ + created_at: number; + + /** + * The output format for the generated image. + */ + output_format: 'png' | 'webp' | 'jpeg'; + + /** + * The quality setting for the generated image. + */ + quality: 'low' | 'medium' | 'high' | 'auto'; + + /** + * The size of the generated image. + */ + size: '1024x1024' | '1024x1536' | '1536x1024' | 'auto'; + + /** + * The type of the event. Always `image_generation.completed`. + */ + type: 'image_generation.completed'; + + /** + * For `gpt-image-1` only, the token usage information for the image generation. + */ + usage: ImageGenCompletedEvent.Usage; +} + +export namespace ImageGenCompletedEvent { + /** + * For `gpt-image-1` only, the token usage information for the image generation. + */ + export interface Usage { + /** + * The number of tokens (images and text) in the input prompt. + */ + input_tokens: number; + + /** + * The input tokens detailed information for the image generation. + */ + input_tokens_details: Usage.InputTokensDetails; + + /** + * The number of image tokens in the output image. + */ + output_tokens: number; + + /** + * The total number of tokens (images and text) used for the image generation. + */ + total_tokens: number; + } + + export namespace Usage { + /** + * The input tokens detailed information for the image generation. + */ + export interface InputTokensDetails { + /** + * The number of image tokens in the input prompt. + */ + image_tokens: number; + + /** + * The number of text tokens in the input prompt. + */ + text_tokens: number; + } + } +} + +/** + * Emitted when a partial image is available during image generation streaming. + */ +export interface ImageGenPartialImageEvent { + /** + * Base64-encoded partial image data, suitable for rendering as an image. + */ + b64_json: string; + + /** + * The background setting for the requested image. + */ + background: 'transparent' | 'opaque' | 'auto'; + + /** + * The Unix timestamp when the event was created. + */ + created_at: number; + + /** + * The output format for the requested image. + */ + output_format: 'png' | 'webp' | 'jpeg'; + + /** + * 0-based index for the partial image (streaming). + */ + partial_image_index: number; + + /** + * The quality setting for the requested image. + */ + quality: 'low' | 'medium' | 'high' | 'auto'; + + /** + * The size of the requested image. + */ + size: '1024x1024' | '1024x1536' | '1536x1024' | 'auto'; + + /** + * The type of the event. Always `image_generation.partial_image`. + */ + type: 'image_generation.partial_image'; +} + +/** + * Emitted when a partial image is available during image generation streaming. + */ +export type ImageGenStreamEvent = ImageGenPartialImageEvent | ImageGenCompletedEvent; + +export type ImageModel = 'dall-e-2' | 'dall-e-3' | 'gpt-image-1'; + +/** + * The response from the image generation endpoint. + */ +export interface ImagesResponse { + /** + * The Unix timestamp (in seconds) of when the image was created. + */ + created: number; + + /** + * The background parameter used for the image generation. Either `transparent` or + * `opaque`. + */ + background?: 'transparent' | 'opaque'; + + /** + * The list of generated images. + */ + data?: Array; + + /** + * The output format of the image generation. Either `png`, `webp`, or `jpeg`. + */ + output_format?: 'png' | 'webp' | 'jpeg'; + + /** + * The quality of the image generated. Either `low`, `medium`, or `high`. + */ + quality?: 'low' | 'medium' | 'high'; + + /** + * The size of the image generated. Either `1024x1024`, `1024x1536`, or + * `1536x1024`. + */ + size?: '1024x1024' | '1024x1536' | '1536x1024'; + + /** + * For `gpt-image-1` only, the token usage information for the image generation. + */ + usage?: ImagesResponse.Usage; +} + +export namespace ImagesResponse { + /** + * For `gpt-image-1` only, the token usage information for the image generation. + */ + export interface Usage { + /** + * The number of tokens (images and text) in the input prompt. + */ + input_tokens: number; + + /** + * The input tokens detailed information for the image generation. + */ + input_tokens_details: Usage.InputTokensDetails; + + /** + * The number of output tokens generated by the model. + */ + output_tokens: number; + + /** + * The total number of tokens (images and text) used for the image generation. + */ + total_tokens: number; + } + + export namespace Usage { + /** + * The input tokens detailed information for the image generation. + */ + export interface InputTokensDetails { + /** + * The number of image tokens in the input prompt. + */ + image_tokens: number; + + /** + * The number of text tokens in the input prompt. + */ + text_tokens: number; + } + } +} + +export interface ImageCreateVariationParams { + /** + * The image to use as the basis for the variation(s). Must be a valid PNG file, + * less than 4MB, and square. + */ + image: Uploadable; + + /** + * The model to use for image generation. Only `dall-e-2` is supported at this + * time. + */ + model?: (string & {}) | ImageModel | null; + + /** + * The number of images to generate. Must be between 1 and 10. + */ + n?: number | null; + + /** + * The format in which the generated images are returned. Must be one of `url` or + * `b64_json`. URLs are only valid for 60 minutes after the image has been + * generated. + */ + response_format?: 'url' | 'b64_json' | null; + + /** + * The size of the generated images. Must be one of `256x256`, `512x512`, or + * `1024x1024`. + */ + size?: '256x256' | '512x512' | '1024x1024' | null; + + /** + * A unique identifier representing your end-user, which can help OpenAI to monitor + * and detect abuse. + * [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). + */ + user?: string; +} + +export type ImageEditParams = ImageEditParamsNonStreaming | ImageEditParamsStreaming; + +export interface ImageEditParamsBase { + /** + * The image(s) to edit. Must be a supported image file or an array of images. + * + * For `gpt-image-1`, each image should be a `png`, `webp`, or `jpg` file less than + * 50MB. You can provide up to 16 images. + * + * For `dall-e-2`, you can only provide one image, and it should be a square `png` + * file less than 4MB. + */ + image: Uploadable | Array; + + /** + * A text description of the desired image(s). The maximum length is 1000 + * characters for `dall-e-2`, and 32000 characters for `gpt-image-1`. + */ + prompt: string; + + /** + * Allows to set transparency for the background of the generated image(s). This + * parameter is only supported for `gpt-image-1`. Must be one of `transparent`, + * `opaque` or `auto` (default value). When `auto` is used, the model will + * automatically determine the best background for the image. + * + * If `transparent`, the output format needs to support transparency, so it should + * be set to either `png` (default value) or `webp`. + */ + background?: 'transparent' | 'opaque' | 'auto' | null; + + /** + * Control how much effort the model will exert to match the style and features, + * especially facial features, of input images. This parameter is only supported + * for `gpt-image-1`. Supports `high` and `low`. Defaults to `low`. + */ + input_fidelity?: 'high' | 'low' | null; + + /** + * An additional image whose fully transparent areas (e.g. where alpha is zero) + * indicate where `image` should be edited. If there are multiple images provided, + * the mask will be applied on the first image. Must be a valid PNG file, less than + * 4MB, and have the same dimensions as `image`. + */ + mask?: Uploadable; + + /** + * The model to use for image generation. Only `dall-e-2` and `gpt-image-1` are + * supported. Defaults to `dall-e-2` unless a parameter specific to `gpt-image-1` + * is used. + */ + model?: (string & {}) | ImageModel | null; + + /** + * The number of images to generate. Must be between 1 and 10. + */ + n?: number | null; + + /** + * The compression level (0-100%) for the generated images. This parameter is only + * supported for `gpt-image-1` with the `webp` or `jpeg` output formats, and + * defaults to 100. + */ + output_compression?: number | null; + + /** + * The format in which the generated images are returned. This parameter is only + * supported for `gpt-image-1`. Must be one of `png`, `jpeg`, or `webp`. The + * default value is `png`. + */ + output_format?: 'png' | 'jpeg' | 'webp' | null; + + /** + * The number of partial images to generate. This parameter is used for streaming + * responses that return partial images. Value must be between 0 and 3. When set to + * 0, the response will be a single image sent in one streaming event. + * + * Note that the final image may be sent before the full number of partial images + * are generated if the full image is generated more quickly. + */ + partial_images?: number | null; + + /** + * The quality of the image that will be generated. `high`, `medium` and `low` are + * only supported for `gpt-image-1`. `dall-e-2` only supports `standard` quality. + * Defaults to `auto`. + */ + quality?: 'standard' | 'low' | 'medium' | 'high' | 'auto' | null; + + /** + * The format in which the generated images are returned. Must be one of `url` or + * `b64_json`. URLs are only valid for 60 minutes after the image has been + * generated. This parameter is only supported for `dall-e-2`, as `gpt-image-1` + * will always return base64-encoded images. + */ + response_format?: 'url' | 'b64_json' | null; + + /** + * The size of the generated images. Must be one of `1024x1024`, `1536x1024` + * (landscape), `1024x1536` (portrait), or `auto` (default value) for + * `gpt-image-1`, and one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`. + */ + size?: '256x256' | '512x512' | '1024x1024' | '1536x1024' | '1024x1536' | 'auto' | null; + + /** + * Edit the image in streaming mode. Defaults to `false`. See the + * [Image generation guide](https://platform.openai.com/docs/guides/image-generation) + * for more information. + */ + stream?: boolean | null; + + /** + * A unique identifier representing your end-user, which can help OpenAI to monitor + * and detect abuse. + * [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). + */ + user?: string; +} + +export namespace ImageEditParams { + export type ImageEditParamsNonStreaming = ImagesAPI.ImageEditParamsNonStreaming; + export type ImageEditParamsStreaming = ImagesAPI.ImageEditParamsStreaming; +} + +export interface ImageEditParamsNonStreaming extends ImageEditParamsBase { + /** + * Edit the image in streaming mode. Defaults to `false`. See the + * [Image generation guide](https://platform.openai.com/docs/guides/image-generation) + * for more information. + */ + stream?: false | null; +} + +export interface ImageEditParamsStreaming extends ImageEditParamsBase { + /** + * Edit the image in streaming mode. Defaults to `false`. See the + * [Image generation guide](https://platform.openai.com/docs/guides/image-generation) + * for more information. + */ + stream: true; +} + +export type ImageGenerateParams = ImageGenerateParamsNonStreaming | ImageGenerateParamsStreaming; + +export interface ImageGenerateParamsBase { + /** + * A text description of the desired image(s). The maximum length is 32000 + * characters for `gpt-image-1`, 1000 characters for `dall-e-2` and 4000 characters + * for `dall-e-3`. + */ + prompt: string; + + /** + * Allows to set transparency for the background of the generated image(s). This + * parameter is only supported for `gpt-image-1`. Must be one of `transparent`, + * `opaque` or `auto` (default value). When `auto` is used, the model will + * automatically determine the best background for the image. + * + * If `transparent`, the output format needs to support transparency, so it should + * be set to either `png` (default value) or `webp`. + */ + background?: 'transparent' | 'opaque' | 'auto' | null; + + /** + * The model to use for image generation. One of `dall-e-2`, `dall-e-3`, or + * `gpt-image-1`. Defaults to `dall-e-2` unless a parameter specific to + * `gpt-image-1` is used. + */ + model?: (string & {}) | ImageModel | null; + + /** + * Control the content-moderation level for images generated by `gpt-image-1`. Must + * be either `low` for less restrictive filtering or `auto` (default value). + */ + moderation?: 'low' | 'auto' | null; + + /** + * The number of images to generate. Must be between 1 and 10. For `dall-e-3`, only + * `n=1` is supported. + */ + n?: number | null; + + /** + * The compression level (0-100%) for the generated images. This parameter is only + * supported for `gpt-image-1` with the `webp` or `jpeg` output formats, and + * defaults to 100. + */ + output_compression?: number | null; + + /** + * The format in which the generated images are returned. This parameter is only + * supported for `gpt-image-1`. Must be one of `png`, `jpeg`, or `webp`. + */ + output_format?: 'png' | 'jpeg' | 'webp' | null; + + /** + * The number of partial images to generate. This parameter is used for streaming + * responses that return partial images. Value must be between 0 and 3. When set to + * 0, the response will be a single image sent in one streaming event. + * + * Note that the final image may be sent before the full number of partial images + * are generated if the full image is generated more quickly. + */ + partial_images?: number | null; + + /** + * The quality of the image that will be generated. + * + * - `auto` (default value) will automatically select the best quality for the + * given model. + * - `high`, `medium` and `low` are supported for `gpt-image-1`. + * - `hd` and `standard` are supported for `dall-e-3`. + * - `standard` is the only option for `dall-e-2`. + */ + quality?: 'standard' | 'hd' | 'low' | 'medium' | 'high' | 'auto' | null; + + /** + * The format in which generated images with `dall-e-2` and `dall-e-3` are + * returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes + * after the image has been generated. This parameter isn't supported for + * `gpt-image-1` which will always return base64-encoded images. + */ + response_format?: 'url' | 'b64_json' | null; + + /** + * The size of the generated images. Must be one of `1024x1024`, `1536x1024` + * (landscape), `1024x1536` (portrait), or `auto` (default value) for + * `gpt-image-1`, one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`, and + * one of `1024x1024`, `1792x1024`, or `1024x1792` for `dall-e-3`. + */ + size?: + | 'auto' + | '1024x1024' + | '1536x1024' + | '1024x1536' + | '256x256' + | '512x512' + | '1792x1024' + | '1024x1792' + | null; + + /** + * Generate the image in streaming mode. Defaults to `false`. See the + * [Image generation guide](https://platform.openai.com/docs/guides/image-generation) + * for more information. This parameter is only supported for `gpt-image-1`. + */ + stream?: boolean | null; + + /** + * The style of the generated images. This parameter is only supported for + * `dall-e-3`. Must be one of `vivid` or `natural`. Vivid causes the model to lean + * towards generating hyper-real and dramatic images. Natural causes the model to + * produce more natural, less hyper-real looking images. + */ + style?: 'vivid' | 'natural' | null; + + /** + * A unique identifier representing your end-user, which can help OpenAI to monitor + * and detect abuse. + * [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). + */ + user?: string; +} + +export namespace ImageGenerateParams { + export type ImageGenerateParamsNonStreaming = ImagesAPI.ImageGenerateParamsNonStreaming; + export type ImageGenerateParamsStreaming = ImagesAPI.ImageGenerateParamsStreaming; +} + +export interface ImageGenerateParamsNonStreaming extends ImageGenerateParamsBase { + /** + * Generate the image in streaming mode. Defaults to `false`. See the + * [Image generation guide](https://platform.openai.com/docs/guides/image-generation) + * for more information. This parameter is only supported for `gpt-image-1`. + */ + stream?: false | null; +} + +export interface ImageGenerateParamsStreaming extends ImageGenerateParamsBase { + /** + * Generate the image in streaming mode. Defaults to `false`. See the + * [Image generation guide](https://platform.openai.com/docs/guides/image-generation) + * for more information. This parameter is only supported for `gpt-image-1`. + */ + stream: true; +} + +export declare namespace Images { + export { + type Image as Image, + type ImageEditCompletedEvent as ImageEditCompletedEvent, + type ImageEditPartialImageEvent as ImageEditPartialImageEvent, + type ImageEditStreamEvent as ImageEditStreamEvent, + type ImageGenCompletedEvent as ImageGenCompletedEvent, + type ImageGenPartialImageEvent as ImageGenPartialImageEvent, + type ImageGenStreamEvent as ImageGenStreamEvent, + type ImageModel as ImageModel, + type ImagesResponse as ImagesResponse, + type ImageCreateVariationParams as ImageCreateVariationParams, + type ImageEditParams as ImageEditParams, + type ImageEditParamsNonStreaming as ImageEditParamsNonStreaming, + type ImageEditParamsStreaming as ImageEditParamsStreaming, + type ImageGenerateParams as ImageGenerateParams, + type ImageGenerateParamsNonStreaming as ImageGenerateParamsNonStreaming, + type ImageGenerateParamsStreaming as ImageGenerateParamsStreaming, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/index.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..129b1cbd0b63eefe716adbfc7075e413307c98b5 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/index.ts @@ -0,0 +1,119 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export * from './chat/index'; +export * from './shared'; +export { Audio, type AudioModel, type AudioResponseFormat } from './audio/audio'; +export { + Batches, + type Batch, + type BatchError, + type BatchRequestCounts, + type BatchCreateParams, + type BatchListParams, + type BatchesPage, +} from './batches'; +export { Beta } from './beta/beta'; +export { + Completions, + type Completion, + type CompletionChoice, + type CompletionUsage, + type CompletionCreateParams, + type CompletionCreateParamsNonStreaming, + type CompletionCreateParamsStreaming, +} from './completions'; +export { + Containers, + type ContainerCreateResponse, + type ContainerRetrieveResponse, + type ContainerListResponse, + type ContainerCreateParams, + type ContainerListParams, + type ContainerListResponsesPage, +} from './containers/containers'; +export { Conversations } from './conversations/conversations'; +export { + Embeddings, + type CreateEmbeddingResponse, + type Embedding, + type EmbeddingModel, + type EmbeddingCreateParams, +} from './embeddings'; +export { + Evals, + type EvalCustomDataSourceConfig, + type EvalStoredCompletionsDataSourceConfig, + type EvalCreateResponse, + type EvalRetrieveResponse, + type EvalUpdateResponse, + type EvalListResponse, + type EvalDeleteResponse, + type EvalCreateParams, + type EvalUpdateParams, + type EvalListParams, + type EvalListResponsesPage, +} from './evals/evals'; +export { + Files, + type FileContent, + type FileDeleted, + type FileObject, + type FilePurpose, + type FileCreateParams, + type FileListParams, + type FileObjectsPage, +} from './files'; +export { FineTuning } from './fine-tuning/fine-tuning'; +export { Graders } from './graders/graders'; +export { + Images, + type Image, + type ImageEditCompletedEvent, + type ImageEditPartialImageEvent, + type ImageEditStreamEvent, + type ImageGenCompletedEvent, + type ImageGenPartialImageEvent, + type ImageGenStreamEvent, + type ImageModel, + type ImagesResponse, + type ImageCreateVariationParams, + type ImageEditParams, + type ImageEditParamsNonStreaming, + type ImageEditParamsStreaming, + type ImageGenerateParams, + type ImageGenerateParamsNonStreaming, + type ImageGenerateParamsStreaming, +} from './images'; +export { Models, type Model, type ModelDeleted, type ModelsPage } from './models'; +export { + Moderations, + type Moderation, + type ModerationImageURLInput, + type ModerationModel, + type ModerationMultiModalInput, + type ModerationTextInput, + type ModerationCreateResponse, + type ModerationCreateParams, +} from './moderations'; +export { Responses } from './responses/responses'; +export { Uploads, type Upload, type UploadCreateParams, type UploadCompleteParams } from './uploads/uploads'; +export { + VectorStores, + type AutoFileChunkingStrategyParam, + type FileChunkingStrategy, + type FileChunkingStrategyParam, + type OtherFileChunkingStrategyObject, + type StaticFileChunkingStrategy, + type StaticFileChunkingStrategyObject, + type StaticFileChunkingStrategyObjectParam, + type VectorStore, + type VectorStoreDeleted, + type VectorStoreSearchResponse, + type VectorStoreCreateParams, + type VectorStoreUpdateParams, + type VectorStoreListParams, + type VectorStoreSearchParams, + type VectorStoresPage, + type VectorStoreSearchResponsesPage, +} from './vector-stores/vector-stores'; +export { Webhooks } from './webhooks'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/models.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/models.ts new file mode 100644 index 0000000000000000000000000000000000000000..25a730ebfd66a2361a05dc509120e8ea06ba4091 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/models.ts @@ -0,0 +1,73 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../core/resource'; +import { APIPromise } from '../core/api-promise'; +import { Page, PagePromise } from '../core/pagination'; +import { RequestOptions } from '../internal/request-options'; +import { path } from '../internal/utils/path'; + +export class Models extends APIResource { + /** + * Retrieves a model instance, providing basic information about the model such as + * the owner and permissioning. + */ + retrieve(model: string, options?: RequestOptions): APIPromise { + return this._client.get(path`/models/${model}`, options); + } + + /** + * Lists the currently available models, and provides basic information about each + * one such as the owner and availability. + */ + list(options?: RequestOptions): PagePromise { + return this._client.getAPIList('/models', Page, options); + } + + /** + * Delete a fine-tuned model. You must have the Owner role in your organization to + * delete a model. + */ + delete(model: string, options?: RequestOptions): APIPromise { + return this._client.delete(path`/models/${model}`, options); + } +} + +// Note: no pagination actually occurs yet, this is for forwards-compatibility. +export type ModelsPage = Page; + +/** + * Describes an OpenAI model offering that can be used with the API. + */ +export interface Model { + /** + * The model identifier, which can be referenced in the API endpoints. + */ + id: string; + + /** + * The Unix timestamp (in seconds) when the model was created. + */ + created: number; + + /** + * The object type, which is always "model". + */ + object: 'model'; + + /** + * The organization that owns the model. + */ + owned_by: string; +} + +export interface ModelDeleted { + id: string; + + deleted: boolean; + + object: string; +} + +export declare namespace Models { + export { type Model as Model, type ModelDeleted as ModelDeleted, type ModelsPage as ModelsPage }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/moderations.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/moderations.ts new file mode 100644 index 0000000000000000000000000000000000000000..2792e0f306c3d9bb698102a10bc4fa722f3c77cd --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/moderations.ts @@ -0,0 +1,367 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../core/resource'; +import { APIPromise } from '../core/api-promise'; +import { RequestOptions } from '../internal/request-options'; + +export class Moderations extends APIResource { + /** + * Classifies if text and/or image inputs are potentially harmful. Learn more in + * the [moderation guide](https://platform.openai.com/docs/guides/moderation). + */ + create(body: ModerationCreateParams, options?: RequestOptions): APIPromise { + return this._client.post('/moderations', { body, ...options }); + } +} + +export interface Moderation { + /** + * A list of the categories, and whether they are flagged or not. + */ + categories: Moderation.Categories; + + /** + * A list of the categories along with the input type(s) that the score applies to. + */ + category_applied_input_types: Moderation.CategoryAppliedInputTypes; + + /** + * A list of the categories along with their scores as predicted by model. + */ + category_scores: Moderation.CategoryScores; + + /** + * Whether any of the below categories are flagged. + */ + flagged: boolean; +} + +export namespace Moderation { + /** + * A list of the categories, and whether they are flagged or not. + */ + export interface Categories { + /** + * Content that expresses, incites, or promotes harassing language towards any + * target. + */ + harassment: boolean; + + /** + * Harassment content that also includes violence or serious harm towards any + * target. + */ + 'harassment/threatening': boolean; + + /** + * Content that expresses, incites, or promotes hate based on race, gender, + * ethnicity, religion, nationality, sexual orientation, disability status, or + * caste. Hateful content aimed at non-protected groups (e.g., chess players) is + * harassment. + */ + hate: boolean; + + /** + * Hateful content that also includes violence or serious harm towards the targeted + * group based on race, gender, ethnicity, religion, nationality, sexual + * orientation, disability status, or caste. + */ + 'hate/threatening': boolean; + + /** + * Content that includes instructions or advice that facilitate the planning or + * execution of wrongdoing, or that gives advice or instruction on how to commit + * illicit acts. For example, "how to shoplift" would fit this category. + */ + illicit: boolean | null; + + /** + * Content that includes instructions or advice that facilitate the planning or + * execution of wrongdoing that also includes violence, or that gives advice or + * instruction on the procurement of any weapon. + */ + 'illicit/violent': boolean | null; + + /** + * Content that promotes, encourages, or depicts acts of self-harm, such as + * suicide, cutting, and eating disorders. + */ + 'self-harm': boolean; + + /** + * Content that encourages performing acts of self-harm, such as suicide, cutting, + * and eating disorders, or that gives instructions or advice on how to commit such + * acts. + */ + 'self-harm/instructions': boolean; + + /** + * Content where the speaker expresses that they are engaging or intend to engage + * in acts of self-harm, such as suicide, cutting, and eating disorders. + */ + 'self-harm/intent': boolean; + + /** + * Content meant to arouse sexual excitement, such as the description of sexual + * activity, or that promotes sexual services (excluding sex education and + * wellness). + */ + sexual: boolean; + + /** + * Sexual content that includes an individual who is under 18 years old. + */ + 'sexual/minors': boolean; + + /** + * Content that depicts death, violence, or physical injury. + */ + violence: boolean; + + /** + * Content that depicts death, violence, or physical injury in graphic detail. + */ + 'violence/graphic': boolean; + } + + /** + * A list of the categories along with the input type(s) that the score applies to. + */ + export interface CategoryAppliedInputTypes { + /** + * The applied input type(s) for the category 'harassment'. + */ + harassment: Array<'text'>; + + /** + * The applied input type(s) for the category 'harassment/threatening'. + */ + 'harassment/threatening': Array<'text'>; + + /** + * The applied input type(s) for the category 'hate'. + */ + hate: Array<'text'>; + + /** + * The applied input type(s) for the category 'hate/threatening'. + */ + 'hate/threatening': Array<'text'>; + + /** + * The applied input type(s) for the category 'illicit'. + */ + illicit: Array<'text'>; + + /** + * The applied input type(s) for the category 'illicit/violent'. + */ + 'illicit/violent': Array<'text'>; + + /** + * The applied input type(s) for the category 'self-harm'. + */ + 'self-harm': Array<'text' | 'image'>; + + /** + * The applied input type(s) for the category 'self-harm/instructions'. + */ + 'self-harm/instructions': Array<'text' | 'image'>; + + /** + * The applied input type(s) for the category 'self-harm/intent'. + */ + 'self-harm/intent': Array<'text' | 'image'>; + + /** + * The applied input type(s) for the category 'sexual'. + */ + sexual: Array<'text' | 'image'>; + + /** + * The applied input type(s) for the category 'sexual/minors'. + */ + 'sexual/minors': Array<'text'>; + + /** + * The applied input type(s) for the category 'violence'. + */ + violence: Array<'text' | 'image'>; + + /** + * The applied input type(s) for the category 'violence/graphic'. + */ + 'violence/graphic': Array<'text' | 'image'>; + } + + /** + * A list of the categories along with their scores as predicted by model. + */ + export interface CategoryScores { + /** + * The score for the category 'harassment'. + */ + harassment: number; + + /** + * The score for the category 'harassment/threatening'. + */ + 'harassment/threatening': number; + + /** + * The score for the category 'hate'. + */ + hate: number; + + /** + * The score for the category 'hate/threatening'. + */ + 'hate/threatening': number; + + /** + * The score for the category 'illicit'. + */ + illicit: number; + + /** + * The score for the category 'illicit/violent'. + */ + 'illicit/violent': number; + + /** + * The score for the category 'self-harm'. + */ + 'self-harm': number; + + /** + * The score for the category 'self-harm/instructions'. + */ + 'self-harm/instructions': number; + + /** + * The score for the category 'self-harm/intent'. + */ + 'self-harm/intent': number; + + /** + * The score for the category 'sexual'. + */ + sexual: number; + + /** + * The score for the category 'sexual/minors'. + */ + 'sexual/minors': number; + + /** + * The score for the category 'violence'. + */ + violence: number; + + /** + * The score for the category 'violence/graphic'. + */ + 'violence/graphic': number; + } +} + +/** + * An object describing an image to classify. + */ +export interface ModerationImageURLInput { + /** + * Contains either an image URL or a data URL for a base64 encoded image. + */ + image_url: ModerationImageURLInput.ImageURL; + + /** + * Always `image_url`. + */ + type: 'image_url'; +} + +export namespace ModerationImageURLInput { + /** + * Contains either an image URL or a data URL for a base64 encoded image. + */ + export interface ImageURL { + /** + * Either a URL of the image or the base64 encoded image data. + */ + url: string; + } +} + +export type ModerationModel = + | 'omni-moderation-latest' + | 'omni-moderation-2024-09-26' + | 'text-moderation-latest' + | 'text-moderation-stable'; + +/** + * An object describing an image to classify. + */ +export type ModerationMultiModalInput = ModerationImageURLInput | ModerationTextInput; + +/** + * An object describing text to classify. + */ +export interface ModerationTextInput { + /** + * A string of text to classify. + */ + text: string; + + /** + * Always `text`. + */ + type: 'text'; +} + +/** + * Represents if a given text input is potentially harmful. + */ +export interface ModerationCreateResponse { + /** + * The unique identifier for the moderation request. + */ + id: string; + + /** + * The model used to generate the moderation results. + */ + model: string; + + /** + * A list of moderation objects. + */ + results: Array; +} + +export interface ModerationCreateParams { + /** + * Input (or inputs) to classify. Can be a single string, an array of strings, or + * an array of multi-modal input objects similar to other models. + */ + input: string | Array | Array; + + /** + * The content moderation model you would like to use. Learn more in + * [the moderation guide](https://platform.openai.com/docs/guides/moderation), and + * learn about available models + * [here](https://platform.openai.com/docs/models#moderation). + */ + model?: (string & {}) | ModerationModel; +} + +export declare namespace Moderations { + export { + type Moderation as Moderation, + type ModerationImageURLInput as ModerationImageURLInput, + type ModerationModel as ModerationModel, + type ModerationMultiModalInput as ModerationMultiModalInput, + type ModerationTextInput as ModerationTextInput, + type ModerationCreateResponse as ModerationCreateResponse, + type ModerationCreateParams as ModerationCreateParams, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/responses.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/responses.ts new file mode 100644 index 0000000000000000000000000000000000000000..9d26aac0c6764bb453fb21728ff33547cff1986e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/responses.ts @@ -0,0 +1,3 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export * from './responses/index'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/responses/index.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/responses/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..ad3f9a38606b1bcd89000c67d15d6a58f38d59b9 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/responses/index.ts @@ -0,0 +1,4 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export { InputItems, type ResponseItemList, type InputItemListParams } from './input-items'; +export { Responses } from './responses'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/responses/input-items.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/responses/input-items.ts new file mode 100644 index 0000000000000000000000000000000000000000..4acb6c77be548c30975343ddaaf4dd7f30227e6c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/responses/input-items.ts @@ -0,0 +1,87 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../core/resource'; +import * as ResponsesAPI from './responses'; +import { ResponseItemsPage } from './responses'; +import { CursorPage, type CursorPageParams, PagePromise } from '../../core/pagination'; +import { RequestOptions } from '../../internal/request-options'; +import { path } from '../../internal/utils/path'; + +export class InputItems extends APIResource { + /** + * Returns a list of input items for a given response. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const responseItem of client.responses.inputItems.list( + * 'response_id', + * )) { + * // ... + * } + * ``` + */ + list( + responseID: string, + query: InputItemListParams | null | undefined = {}, + options?: RequestOptions, + ): PagePromise { + return this._client.getAPIList( + path`/responses/${responseID}/input_items`, + CursorPage, + { query, ...options }, + ); + } +} + +/** + * A list of Response items. + */ +export interface ResponseItemList { + /** + * A list of items used to generate this response. + */ + data: Array; + + /** + * The ID of the first item in the list. + */ + first_id: string; + + /** + * Whether there are more items available. + */ + has_more: boolean; + + /** + * The ID of the last item in the list. + */ + last_id: string; + + /** + * The type of object returned, must be `list`. + */ + object: 'list'; +} + +export interface InputItemListParams extends CursorPageParams { + /** + * Additional fields to include in the response. See the `include` parameter for + * Response creation above for more information. + */ + include?: Array; + + /** + * The order to return the input items in. Default is `desc`. + * + * - `asc`: Return the input items in ascending order. + * - `desc`: Return the input items in descending order. + */ + order?: 'asc' | 'desc'; +} + +export declare namespace InputItems { + export { type ResponseItemList as ResponseItemList, type InputItemListParams as InputItemListParams }; +} + +export { type ResponseItemsPage }; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/responses/responses.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/responses/responses.ts new file mode 100644 index 0000000000000000000000000000000000000000..5512b0e1162f373d88f65e36721de95b08c44c0e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/responses/responses.ts @@ -0,0 +1,5690 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { + type ExtractParsedContentFromParams, + parseResponse, + type ResponseCreateParamsWithTools, + addOutputText, +} from '../../lib/ResponsesParser'; +import { ResponseStream, ResponseStreamParams } from '../../lib/responses/ResponseStream'; +import { APIResource } from '../../core/resource'; +import * as ResponsesAPI from './responses'; +import * as Shared from '../shared'; +import * as InputItemsAPI from './input-items'; +import { InputItemListParams, InputItems, ResponseItemList } from './input-items'; +import { APIPromise } from '../../core/api-promise'; +import { CursorPage } from '../../core/pagination'; +import { Stream } from '../../core/streaming'; +import { buildHeaders } from '../../internal/headers'; +import { RequestOptions } from '../../internal/request-options'; +import { path } from '../../internal/utils/path'; + +export interface ParsedResponseOutputText extends ResponseOutputText { + parsed: ParsedT | null; +} + +export type ParsedContent = ParsedResponseOutputText | ResponseOutputRefusal; + +export interface ParsedResponseOutputMessage extends ResponseOutputMessage { + content: ParsedContent[]; +} + +export interface ParsedResponseFunctionToolCall extends ResponseFunctionToolCall { + parsed_arguments: any; +} + +export type ParsedResponseOutputItem = + | ParsedResponseOutputMessage + | ParsedResponseFunctionToolCall + | ResponseFileSearchToolCall + | ResponseFunctionWebSearch + | ResponseComputerToolCall + | ResponseReasoningItem + | ResponseOutputItem.ImageGenerationCall + | ResponseCodeInterpreterToolCall + | ResponseOutputItem.LocalShellCall + | ResponseOutputItem.McpCall + | ResponseOutputItem.McpListTools + | ResponseOutputItem.McpApprovalRequest + | ResponseCustomToolCall; + +export interface ParsedResponse extends Response { + output: Array>; + + output_parsed: ParsedT | null; +} + +export type ResponseParseParams = ResponseCreateParamsNonStreaming; + +export class Responses extends APIResource { + inputItems: InputItemsAPI.InputItems = new InputItemsAPI.InputItems(this._client); + + /** + * Creates a model response. Provide + * [text](https://platform.openai.com/docs/guides/text) or + * [image](https://platform.openai.com/docs/guides/images) inputs to generate + * [text](https://platform.openai.com/docs/guides/text) or + * [JSON](https://platform.openai.com/docs/guides/structured-outputs) outputs. Have + * the model call your own + * [custom code](https://platform.openai.com/docs/guides/function-calling) or use + * built-in [tools](https://platform.openai.com/docs/guides/tools) like + * [web search](https://platform.openai.com/docs/guides/tools-web-search) or + * [file search](https://platform.openai.com/docs/guides/tools-file-search) to use + * your own data as input for the model's response. + * + * @example + * ```ts + * const response = await client.responses.create(); + * ``` + */ + create(body: ResponseCreateParamsNonStreaming, options?: RequestOptions): APIPromise; + create( + body: ResponseCreateParamsStreaming, + options?: RequestOptions, + ): APIPromise>; + create( + body: ResponseCreateParamsBase, + options?: RequestOptions, + ): APIPromise | Response>; + create( + body: ResponseCreateParams, + options?: RequestOptions, + ): APIPromise | APIPromise> { + return ( + this._client.post('/responses', { body, ...options, stream: body.stream ?? false }) as + | APIPromise + | APIPromise> + )._thenUnwrap((rsp) => { + if ('object' in rsp && rsp.object === 'response') { + addOutputText(rsp as Response); + } + + return rsp; + }) as APIPromise | APIPromise>; + } + + /** + * Retrieves a model response with the given ID. + * + * @example + * ```ts + * const response = await client.responses.retrieve( + * 'resp_677efb5139a88190b512bc3fef8e535d', + * ); + * ``` + */ + retrieve( + responseID: string, + query?: ResponseRetrieveParamsNonStreaming, + options?: RequestOptions, + ): APIPromise; + retrieve( + responseID: string, + query: ResponseRetrieveParamsStreaming, + options?: RequestOptions, + ): APIPromise>; + retrieve( + responseID: string, + query?: ResponseRetrieveParamsBase | undefined, + options?: RequestOptions, + ): APIPromise | Response>; + retrieve( + responseID: string, + query: ResponseRetrieveParams | undefined = {}, + options?: RequestOptions, + ): APIPromise | APIPromise> { + return ( + this._client.get(path`/responses/${responseID}`, { + query, + ...options, + stream: query?.stream ?? false, + }) as APIPromise | APIPromise> + )._thenUnwrap((rsp) => { + if ('object' in rsp && rsp.object === 'response') { + addOutputText(rsp as Response); + } + + return rsp; + }) as APIPromise | APIPromise>; + } + + /** + * Deletes a model response with the given ID. + * + * @example + * ```ts + * await client.responses.delete( + * 'resp_677efb5139a88190b512bc3fef8e535d', + * ); + * ``` + */ + delete(responseID: string, options?: RequestOptions): APIPromise { + return this._client.delete(path`/responses/${responseID}`, { + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); + } + + parse>( + body: Params, + options?: RequestOptions, + ): APIPromise> { + return this._client.responses + .create(body, options) + ._thenUnwrap((response) => parseResponse(response as Response, body)); + } + + /** + * Creates a model response stream + */ + stream>( + body: Params, + options?: RequestOptions, + ): ResponseStream { + return ResponseStream.createResponse(this._client, body, options); + } + + /** + * Cancels a model response with the given ID. Only responses created with the + * `background` parameter set to `true` can be cancelled. + * [Learn more](https://platform.openai.com/docs/guides/background). + * + * @example + * ```ts + * const response = await client.responses.cancel( + * 'resp_677efb5139a88190b512bc3fef8e535d', + * ); + * ``` + */ + cancel(responseID: string, options?: RequestOptions): APIPromise { + return this._client.post(path`/responses/${responseID}/cancel`, options); + } +} + +export type ResponseItemsPage = CursorPage; + +/** + * A tool that controls a virtual computer. Learn more about the + * [computer tool](https://platform.openai.com/docs/guides/tools-computer-use). + */ +export interface ComputerTool { + /** + * The height of the computer display. + */ + display_height: number; + + /** + * The width of the computer display. + */ + display_width: number; + + /** + * The type of computer environment to control. + */ + environment: 'windows' | 'mac' | 'linux' | 'ubuntu' | 'browser'; + + /** + * The type of the computer use tool. Always `computer_use_preview`. + */ + type: 'computer_use_preview'; +} + +/** + * A custom tool that processes input using a specified format. Learn more about + * [custom tools](https://platform.openai.com/docs/guides/function-calling#custom-tools). + */ +export interface CustomTool { + /** + * The name of the custom tool, used to identify it in tool calls. + */ + name: string; + + /** + * The type of the custom tool. Always `custom`. + */ + type: 'custom'; + + /** + * Optional description of the custom tool, used to provide more context. + */ + description?: string; + + /** + * The input format for the custom tool. Default is unconstrained text. + */ + format?: Shared.CustomToolInputFormat; +} + +/** + * A message input to the model with a role indicating instruction following + * hierarchy. Instructions given with the `developer` or `system` role take + * precedence over instructions given with the `user` role. Messages with the + * `assistant` role are presumed to have been generated by the model in previous + * interactions. + */ +export interface EasyInputMessage { + /** + * Text, image, or audio input to the model, used to generate a response. Can also + * contain previous assistant responses. + */ + content: string | ResponseInputMessageContentList; + + /** + * The role of the message input. One of `user`, `assistant`, `system`, or + * `developer`. + */ + role: 'user' | 'assistant' | 'system' | 'developer'; + + /** + * The type of the message input. Always `message`. + */ + type?: 'message'; +} + +/** + * A tool that searches for relevant content from uploaded files. Learn more about + * the + * [file search tool](https://platform.openai.com/docs/guides/tools-file-search). + */ +export interface FileSearchTool { + /** + * The type of the file search tool. Always `file_search`. + */ + type: 'file_search'; + + /** + * The IDs of the vector stores to search. + */ + vector_store_ids: Array; + + /** + * A filter to apply. + */ + filters?: Shared.ComparisonFilter | Shared.CompoundFilter | null; + + /** + * The maximum number of results to return. This number should be between 1 and 50 + * inclusive. + */ + max_num_results?: number; + + /** + * Ranking options for search. + */ + ranking_options?: FileSearchTool.RankingOptions; +} + +export namespace FileSearchTool { + /** + * Ranking options for search. + */ + export interface RankingOptions { + /** + * The ranker to use for the file search. + */ + ranker?: 'auto' | 'default-2024-11-15'; + + /** + * The score threshold for the file search, a number between 0 and 1. Numbers + * closer to 1 will attempt to return only the most relevant results, but may + * return fewer results. + */ + score_threshold?: number; + } +} + +/** + * Defines a function in your own code the model can choose to call. Learn more + * about + * [function calling](https://platform.openai.com/docs/guides/function-calling). + */ +export interface FunctionTool { + /** + * The name of the function to call. + */ + name: string; + + /** + * A JSON schema object describing the parameters of the function. + */ + parameters: { [key: string]: unknown } | null; + + /** + * Whether to enforce strict parameter validation. Default `true`. + */ + strict: boolean | null; + + /** + * The type of the function tool. Always `function`. + */ + type: 'function'; + + /** + * A description of the function. Used by the model to determine whether or not to + * call the function. + */ + description?: string | null; +} + +export interface Response { + /** + * Unique identifier for this Response. + */ + id: string; + + /** + * Unix timestamp (in seconds) of when this Response was created. + */ + created_at: number; + + output_text: string; + + /** + * An error object returned when the model fails to generate a Response. + */ + error: ResponseError | null; + + /** + * Details about why the response is incomplete. + */ + incomplete_details: Response.IncompleteDetails | null; + + /** + * A system (or developer) message inserted into the model's context. + * + * When using along with `previous_response_id`, the instructions from a previous + * response will not be carried over to the next response. This makes it simple to + * swap out system (or developer) messages in new responses. + */ + instructions: string | Array | null; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata: Shared.Metadata | null; + + /** + * Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI offers a + * wide range of models with different capabilities, performance characteristics, + * and price points. Refer to the + * [model guide](https://platform.openai.com/docs/models) to browse and compare + * available models. + */ + model: Shared.ResponsesModel; + + /** + * The object type of this resource - always set to `response`. + */ + object: 'response'; + + /** + * An array of content items generated by the model. + * + * - The length and order of items in the `output` array is dependent on the + * model's response. + * - Rather than accessing the first item in the `output` array and assuming it's + * an `assistant` message with the content generated by the model, you might + * consider using the `output_text` property where supported in SDKs. + */ + output: Array; + + /** + * Whether to allow the model to run tool calls in parallel. + */ + parallel_tool_calls: boolean; + + /** + * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + * make the output more random, while lower values like 0.2 will make it more + * focused and deterministic. We generally recommend altering this or `top_p` but + * not both. + */ + temperature: number | null; + + /** + * How the model should select which tool (or tools) to use when generating a + * response. See the `tools` parameter to see how to specify which tools the model + * can call. + */ + tool_choice: + | ToolChoiceOptions + | ToolChoiceAllowed + | ToolChoiceTypes + | ToolChoiceFunction + | ToolChoiceMcp + | ToolChoiceCustom; + + /** + * An array of tools the model may call while generating a response. You can + * specify which tool to use by setting the `tool_choice` parameter. + * + * The two categories of tools you can provide the model are: + * + * - **Built-in tools**: Tools that are provided by OpenAI that extend the model's + * capabilities, like + * [web search](https://platform.openai.com/docs/guides/tools-web-search) or + * [file search](https://platform.openai.com/docs/guides/tools-file-search). + * Learn more about + * [built-in tools](https://platform.openai.com/docs/guides/tools). + * - **Function calls (custom tools)**: Functions that are defined by you, enabling + * the model to call your own code with strongly typed arguments and outputs. + * Learn more about + * [function calling](https://platform.openai.com/docs/guides/function-calling). + * You can also use custom tools to call your own code. + */ + tools: Array; + + /** + * An alternative to sampling with temperature, called nucleus sampling, where the + * model considers the results of the tokens with top_p probability mass. So 0.1 + * means only the tokens comprising the top 10% probability mass are considered. + * + * We generally recommend altering this or `temperature` but not both. + */ + top_p: number | null; + + /** + * Whether to run the model response in the background. + * [Learn more](https://platform.openai.com/docs/guides/background). + */ + background?: boolean | null; + + /** + * The conversation that this response belongs to. Input items and output items + * from this response are automatically added to this conversation. + */ + conversation?: Response.Conversation | null; + + /** + * An upper bound for the number of tokens that can be generated for a response, + * including visible output tokens and + * [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). + */ + max_output_tokens?: number | null; + + /** + * The unique ID of the previous response to the model. Use this to create + * multi-turn conversations. Learn more about + * [conversation state](https://platform.openai.com/docs/guides/conversation-state). + * Cannot be used in conjunction with `conversation`. + */ + previous_response_id?: string | null; + + /** + * Reference to a prompt template and its variables. + * [Learn more](https://platform.openai.com/docs/guides/text?api-mode=responses#reusable-prompts). + */ + prompt?: ResponsePrompt | null; + + /** + * Used by OpenAI to cache responses for similar requests to optimize your cache + * hit rates. Replaces the `user` field. + * [Learn more](https://platform.openai.com/docs/guides/prompt-caching). + */ + prompt_cache_key?: string; + + /** + * **gpt-5 and o-series models only** + * + * Configuration options for + * [reasoning models](https://platform.openai.com/docs/guides/reasoning). + */ + reasoning?: Shared.Reasoning | null; + + /** + * A stable identifier used to help detect users of your application that may be + * violating OpenAI's usage policies. The IDs should be a string that uniquely + * identifies each user. We recommend hashing their username or email address, in + * order to avoid sending us any identifying information. + * [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers). + */ + safety_identifier?: string; + + /** + * Specifies the latency tier to use for processing the request. This parameter is + * relevant for customers subscribed to the scale tier service: + * + * - If set to 'auto', then the request will be processed with the service tier + * configured in the Project settings. Unless otherwise configured, the Project + * will use 'default'. + * - If set to 'default', then the request will be processed with the standard + * pricing and performance for the selected model. + * - If set to '[flex](https://platform.openai.com/docs/guides/flex-processing)' or + * '[priority](https://openai.com/api-priority-processing/)', then the request + * will be processed with the corresponding service tier. + * - When not set, the default behavior is 'auto'. + * + * When this parameter is set, the response body will include the `service_tier` + * utilized. + */ + service_tier?: 'auto' | 'default' | 'flex' | 'scale' | 'priority' | null; + + /** + * The status of the response generation. One of `completed`, `failed`, + * `in_progress`, `cancelled`, `queued`, or `incomplete`. + */ + status?: ResponseStatus; + + /** + * Configuration options for a text response from the model. Can be plain text or + * structured JSON data. Learn more: + * + * - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + * - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) + */ + text?: ResponseTextConfig; + + /** + * The truncation strategy to use for the model response. + * + * - `auto`: If the context of this response and previous ones exceeds the model's + * context window size, the model will truncate the response to fit the context + * window by dropping input items in the middle of the conversation. + * - `disabled` (default): If a model response will exceed the context window size + * for a model, the request will fail with a 400 error. + */ + truncation?: 'auto' | 'disabled' | null; + + /** + * Represents token usage details including input tokens, output tokens, a + * breakdown of output tokens, and the total tokens used. + */ + usage?: ResponseUsage; + + /** + * @deprecated This field is being replaced by `safety_identifier` and + * `prompt_cache_key`. Use `prompt_cache_key` instead to maintain caching + * optimizations. A stable identifier for your end-users. Used to boost cache hit + * rates by better bucketing similar requests and to help OpenAI detect and prevent + * abuse. + * [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers). + */ + user?: string; +} + +export namespace Response { + /** + * Details about why the response is incomplete. + */ + export interface IncompleteDetails { + /** + * The reason why the response is incomplete. + */ + reason?: 'max_output_tokens' | 'content_filter'; + } + + /** + * The conversation that this response belongs to. Input items and output items + * from this response are automatically added to this conversation. + */ + export interface Conversation { + /** + * The unique ID of the conversation. + */ + id: string; + } +} + +/** + * Emitted when there is a partial audio response. + */ +export interface ResponseAudioDeltaEvent { + /** + * A chunk of Base64 encoded response audio bytes. + */ + delta: string; + + /** + * A sequence number for this chunk of the stream response. + */ + sequence_number: number; + + /** + * The type of the event. Always `response.audio.delta`. + */ + type: 'response.audio.delta'; +} + +/** + * Emitted when the audio response is complete. + */ +export interface ResponseAudioDoneEvent { + /** + * The sequence number of the delta. + */ + sequence_number: number; + + /** + * The type of the event. Always `response.audio.done`. + */ + type: 'response.audio.done'; +} + +/** + * Emitted when there is a partial transcript of audio. + */ +export interface ResponseAudioTranscriptDeltaEvent { + /** + * The partial transcript of the audio response. + */ + delta: string; + + /** + * The sequence number of this event. + */ + sequence_number: number; + + /** + * The type of the event. Always `response.audio.transcript.delta`. + */ + type: 'response.audio.transcript.delta'; +} + +/** + * Emitted when the full audio transcript is completed. + */ +export interface ResponseAudioTranscriptDoneEvent { + /** + * The sequence number of this event. + */ + sequence_number: number; + + /** + * The type of the event. Always `response.audio.transcript.done`. + */ + type: 'response.audio.transcript.done'; +} + +/** + * Emitted when a partial code snippet is streamed by the code interpreter. + */ +export interface ResponseCodeInterpreterCallCodeDeltaEvent { + /** + * The partial code snippet being streamed by the code interpreter. + */ + delta: string; + + /** + * The unique identifier of the code interpreter tool call item. + */ + item_id: string; + + /** + * The index of the output item in the response for which the code is being + * streamed. + */ + output_index: number; + + /** + * The sequence number of this event, used to order streaming events. + */ + sequence_number: number; + + /** + * The type of the event. Always `response.code_interpreter_call_code.delta`. + */ + type: 'response.code_interpreter_call_code.delta'; +} + +/** + * Emitted when the code snippet is finalized by the code interpreter. + */ +export interface ResponseCodeInterpreterCallCodeDoneEvent { + /** + * The final code snippet output by the code interpreter. + */ + code: string; + + /** + * The unique identifier of the code interpreter tool call item. + */ + item_id: string; + + /** + * The index of the output item in the response for which the code is finalized. + */ + output_index: number; + + /** + * The sequence number of this event, used to order streaming events. + */ + sequence_number: number; + + /** + * The type of the event. Always `response.code_interpreter_call_code.done`. + */ + type: 'response.code_interpreter_call_code.done'; +} + +/** + * Emitted when the code interpreter call is completed. + */ +export interface ResponseCodeInterpreterCallCompletedEvent { + /** + * The unique identifier of the code interpreter tool call item. + */ + item_id: string; + + /** + * The index of the output item in the response for which the code interpreter call + * is completed. + */ + output_index: number; + + /** + * The sequence number of this event, used to order streaming events. + */ + sequence_number: number; + + /** + * The type of the event. Always `response.code_interpreter_call.completed`. + */ + type: 'response.code_interpreter_call.completed'; +} + +/** + * Emitted when a code interpreter call is in progress. + */ +export interface ResponseCodeInterpreterCallInProgressEvent { + /** + * The unique identifier of the code interpreter tool call item. + */ + item_id: string; + + /** + * The index of the output item in the response for which the code interpreter call + * is in progress. + */ + output_index: number; + + /** + * The sequence number of this event, used to order streaming events. + */ + sequence_number: number; + + /** + * The type of the event. Always `response.code_interpreter_call.in_progress`. + */ + type: 'response.code_interpreter_call.in_progress'; +} + +/** + * Emitted when the code interpreter is actively interpreting the code snippet. + */ +export interface ResponseCodeInterpreterCallInterpretingEvent { + /** + * The unique identifier of the code interpreter tool call item. + */ + item_id: string; + + /** + * The index of the output item in the response for which the code interpreter is + * interpreting code. + */ + output_index: number; + + /** + * The sequence number of this event, used to order streaming events. + */ + sequence_number: number; + + /** + * The type of the event. Always `response.code_interpreter_call.interpreting`. + */ + type: 'response.code_interpreter_call.interpreting'; +} + +/** + * A tool call to run code. + */ +export interface ResponseCodeInterpreterToolCall { + /** + * The unique ID of the code interpreter tool call. + */ + id: string; + + /** + * The code to run, or null if not available. + */ + code: string | null; + + /** + * The ID of the container used to run the code. + */ + container_id: string; + + /** + * The outputs generated by the code interpreter, such as logs or images. Can be + * null if no outputs are available. + */ + outputs: Array | null; + + /** + * The status of the code interpreter tool call. Valid values are `in_progress`, + * `completed`, `incomplete`, `interpreting`, and `failed`. + */ + status: 'in_progress' | 'completed' | 'incomplete' | 'interpreting' | 'failed'; + + /** + * The type of the code interpreter tool call. Always `code_interpreter_call`. + */ + type: 'code_interpreter_call'; +} + +export namespace ResponseCodeInterpreterToolCall { + /** + * The logs output from the code interpreter. + */ + export interface Logs { + /** + * The logs output from the code interpreter. + */ + logs: string; + + /** + * The type of the output. Always 'logs'. + */ + type: 'logs'; + } + + /** + * The image output from the code interpreter. + */ + export interface Image { + /** + * The type of the output. Always 'image'. + */ + type: 'image'; + + /** + * The URL of the image output from the code interpreter. + */ + url: string; + } +} + +/** + * Emitted when the model response is complete. + */ +export interface ResponseCompletedEvent { + /** + * Properties of the completed response. + */ + response: Response; + + /** + * The sequence number for this event. + */ + sequence_number: number; + + /** + * The type of the event. Always `response.completed`. + */ + type: 'response.completed'; +} + +/** + * A tool call to a computer use tool. See the + * [computer use guide](https://platform.openai.com/docs/guides/tools-computer-use) + * for more information. + */ +export interface ResponseComputerToolCall { + /** + * The unique ID of the computer call. + */ + id: string; + + /** + * A click action. + */ + action: + | ResponseComputerToolCall.Click + | ResponseComputerToolCall.DoubleClick + | ResponseComputerToolCall.Drag + | ResponseComputerToolCall.Keypress + | ResponseComputerToolCall.Move + | ResponseComputerToolCall.Screenshot + | ResponseComputerToolCall.Scroll + | ResponseComputerToolCall.Type + | ResponseComputerToolCall.Wait; + + /** + * An identifier used when responding to the tool call with output. + */ + call_id: string; + + /** + * The pending safety checks for the computer call. + */ + pending_safety_checks: Array; + + /** + * The status of the item. One of `in_progress`, `completed`, or `incomplete`. + * Populated when items are returned via API. + */ + status: 'in_progress' | 'completed' | 'incomplete'; + + /** + * The type of the computer call. Always `computer_call`. + */ + type: 'computer_call'; +} + +export namespace ResponseComputerToolCall { + /** + * A click action. + */ + export interface Click { + /** + * Indicates which mouse button was pressed during the click. One of `left`, + * `right`, `wheel`, `back`, or `forward`. + */ + button: 'left' | 'right' | 'wheel' | 'back' | 'forward'; + + /** + * Specifies the event type. For a click action, this property is always set to + * `click`. + */ + type: 'click'; + + /** + * The x-coordinate where the click occurred. + */ + x: number; + + /** + * The y-coordinate where the click occurred. + */ + y: number; + } + + /** + * A double click action. + */ + export interface DoubleClick { + /** + * Specifies the event type. For a double click action, this property is always set + * to `double_click`. + */ + type: 'double_click'; + + /** + * The x-coordinate where the double click occurred. + */ + x: number; + + /** + * The y-coordinate where the double click occurred. + */ + y: number; + } + + /** + * A drag action. + */ + export interface Drag { + /** + * An array of coordinates representing the path of the drag action. Coordinates + * will appear as an array of objects, eg + * + * ``` + * [ + * { x: 100, y: 200 }, + * { x: 200, y: 300 } + * ] + * ``` + */ + path: Array; + + /** + * Specifies the event type. For a drag action, this property is always set to + * `drag`. + */ + type: 'drag'; + } + + export namespace Drag { + /** + * A series of x/y coordinate pairs in the drag path. + */ + export interface Path { + /** + * The x-coordinate. + */ + x: number; + + /** + * The y-coordinate. + */ + y: number; + } + } + + /** + * A collection of keypresses the model would like to perform. + */ + export interface Keypress { + /** + * The combination of keys the model is requesting to be pressed. This is an array + * of strings, each representing a key. + */ + keys: Array; + + /** + * Specifies the event type. For a keypress action, this property is always set to + * `keypress`. + */ + type: 'keypress'; + } + + /** + * A mouse move action. + */ + export interface Move { + /** + * Specifies the event type. For a move action, this property is always set to + * `move`. + */ + type: 'move'; + + /** + * The x-coordinate to move to. + */ + x: number; + + /** + * The y-coordinate to move to. + */ + y: number; + } + + /** + * A screenshot action. + */ + export interface Screenshot { + /** + * Specifies the event type. For a screenshot action, this property is always set + * to `screenshot`. + */ + type: 'screenshot'; + } + + /** + * A scroll action. + */ + export interface Scroll { + /** + * The horizontal scroll distance. + */ + scroll_x: number; + + /** + * The vertical scroll distance. + */ + scroll_y: number; + + /** + * Specifies the event type. For a scroll action, this property is always set to + * `scroll`. + */ + type: 'scroll'; + + /** + * The x-coordinate where the scroll occurred. + */ + x: number; + + /** + * The y-coordinate where the scroll occurred. + */ + y: number; + } + + /** + * An action to type in text. + */ + export interface Type { + /** + * The text to type. + */ + text: string; + + /** + * Specifies the event type. For a type action, this property is always set to + * `type`. + */ + type: 'type'; + } + + /** + * A wait action. + */ + export interface Wait { + /** + * Specifies the event type. For a wait action, this property is always set to + * `wait`. + */ + type: 'wait'; + } + + /** + * A pending safety check for the computer call. + */ + export interface PendingSafetyCheck { + /** + * The ID of the pending safety check. + */ + id: string; + + /** + * The type of the pending safety check. + */ + code: string; + + /** + * Details about the pending safety check. + */ + message: string; + } +} + +export interface ResponseComputerToolCallOutputItem { + /** + * The unique ID of the computer call tool output. + */ + id: string; + + /** + * The ID of the computer tool call that produced the output. + */ + call_id: string; + + /** + * A computer screenshot image used with the computer use tool. + */ + output: ResponseComputerToolCallOutputScreenshot; + + /** + * The type of the computer tool call output. Always `computer_call_output`. + */ + type: 'computer_call_output'; + + /** + * The safety checks reported by the API that have been acknowledged by the + * developer. + */ + acknowledged_safety_checks?: Array; + + /** + * The status of the message input. One of `in_progress`, `completed`, or + * `incomplete`. Populated when input items are returned via API. + */ + status?: 'in_progress' | 'completed' | 'incomplete'; +} + +export namespace ResponseComputerToolCallOutputItem { + /** + * A pending safety check for the computer call. + */ + export interface AcknowledgedSafetyCheck { + /** + * The ID of the pending safety check. + */ + id: string; + + /** + * The type of the pending safety check. + */ + code: string; + + /** + * Details about the pending safety check. + */ + message: string; + } +} + +/** + * A computer screenshot image used with the computer use tool. + */ +export interface ResponseComputerToolCallOutputScreenshot { + /** + * Specifies the event type. For a computer screenshot, this property is always set + * to `computer_screenshot`. + */ + type: 'computer_screenshot'; + + /** + * The identifier of an uploaded file that contains the screenshot. + */ + file_id?: string; + + /** + * The URL of the screenshot image. + */ + image_url?: string; +} + +/** + * Multi-modal input and output contents. + */ +export type ResponseContent = + | ResponseInputText + | ResponseInputImage + | ResponseInputFile + | ResponseOutputText + | ResponseOutputRefusal; + +/** + * Emitted when a new content part is added. + */ +export interface ResponseContentPartAddedEvent { + /** + * The index of the content part that was added. + */ + content_index: number; + + /** + * The ID of the output item that the content part was added to. + */ + item_id: string; + + /** + * The index of the output item that the content part was added to. + */ + output_index: number; + + /** + * The content part that was added. + */ + part: ResponseOutputText | ResponseOutputRefusal; + + /** + * The sequence number of this event. + */ + sequence_number: number; + + /** + * The type of the event. Always `response.content_part.added`. + */ + type: 'response.content_part.added'; +} + +/** + * Emitted when a content part is done. + */ +export interface ResponseContentPartDoneEvent { + /** + * The index of the content part that is done. + */ + content_index: number; + + /** + * The ID of the output item that the content part was added to. + */ + item_id: string; + + /** + * The index of the output item that the content part was added to. + */ + output_index: number; + + /** + * The content part that is done. + */ + part: ResponseOutputText | ResponseOutputRefusal; + + /** + * The sequence number of this event. + */ + sequence_number: number; + + /** + * The type of the event. Always `response.content_part.done`. + */ + type: 'response.content_part.done'; +} + +/** + * The conversation that this response belongs to. + */ +export interface ResponseConversationParam { + /** + * The unique ID of the conversation. + */ + id: string; +} + +/** + * An event that is emitted when a response is created. + */ +export interface ResponseCreatedEvent { + /** + * The response that was created. + */ + response: Response; + + /** + * The sequence number for this event. + */ + sequence_number: number; + + /** + * The type of the event. Always `response.created`. + */ + type: 'response.created'; +} + +/** + * A call to a custom tool created by the model. + */ +export interface ResponseCustomToolCall { + /** + * An identifier used to map this custom tool call to a tool call output. + */ + call_id: string; + + /** + * The input for the custom tool call generated by the model. + */ + input: string; + + /** + * The name of the custom tool being called. + */ + name: string; + + /** + * The type of the custom tool call. Always `custom_tool_call`. + */ + type: 'custom_tool_call'; + + /** + * The unique ID of the custom tool call in the OpenAI platform. + */ + id?: string; +} + +/** + * Event representing a delta (partial update) to the input of a custom tool call. + */ +export interface ResponseCustomToolCallInputDeltaEvent { + /** + * The incremental input data (delta) for the custom tool call. + */ + delta: string; + + /** + * Unique identifier for the API item associated with this event. + */ + item_id: string; + + /** + * The index of the output this delta applies to. + */ + output_index: number; + + /** + * The sequence number of this event. + */ + sequence_number: number; + + /** + * The event type identifier. + */ + type: 'response.custom_tool_call_input.delta'; +} + +/** + * Event indicating that input for a custom tool call is complete. + */ +export interface ResponseCustomToolCallInputDoneEvent { + /** + * The complete input data for the custom tool call. + */ + input: string; + + /** + * Unique identifier for the API item associated with this event. + */ + item_id: string; + + /** + * The index of the output this event applies to. + */ + output_index: number; + + /** + * The sequence number of this event. + */ + sequence_number: number; + + /** + * The event type identifier. + */ + type: 'response.custom_tool_call_input.done'; +} + +/** + * The output of a custom tool call from your code, being sent back to the model. + */ +export interface ResponseCustomToolCallOutput { + /** + * The call ID, used to map this custom tool call output to a custom tool call. + */ + call_id: string; + + /** + * The output from the custom tool call generated by your code. + */ + output: string; + + /** + * The type of the custom tool call output. Always `custom_tool_call_output`. + */ + type: 'custom_tool_call_output'; + + /** + * The unique ID of the custom tool call output in the OpenAI platform. + */ + id?: string; +} + +/** + * An error object returned when the model fails to generate a Response. + */ +export interface ResponseError { + /** + * The error code for the response. + */ + code: + | 'server_error' + | 'rate_limit_exceeded' + | 'invalid_prompt' + | 'vector_store_timeout' + | 'invalid_image' + | 'invalid_image_format' + | 'invalid_base64_image' + | 'invalid_image_url' + | 'image_too_large' + | 'image_too_small' + | 'image_parse_error' + | 'image_content_policy_violation' + | 'invalid_image_mode' + | 'image_file_too_large' + | 'unsupported_image_media_type' + | 'empty_image_file' + | 'failed_to_download_image' + | 'image_file_not_found'; + + /** + * A human-readable description of the error. + */ + message: string; +} + +/** + * Emitted when an error occurs. + */ +export interface ResponseErrorEvent { + /** + * The error code. + */ + code: string | null; + + /** + * The error message. + */ + message: string; + + /** + * The error parameter. + */ + param: string | null; + + /** + * The sequence number of this event. + */ + sequence_number: number; + + /** + * The type of the event. Always `error`. + */ + type: 'error'; +} + +/** + * An event that is emitted when a response fails. + */ +export interface ResponseFailedEvent { + /** + * The response that failed. + */ + response: Response; + + /** + * The sequence number of this event. + */ + sequence_number: number; + + /** + * The type of the event. Always `response.failed`. + */ + type: 'response.failed'; +} + +/** + * Emitted when a file search call is completed (results found). + */ +export interface ResponseFileSearchCallCompletedEvent { + /** + * The ID of the output item that the file search call is initiated. + */ + item_id: string; + + /** + * The index of the output item that the file search call is initiated. + */ + output_index: number; + + /** + * The sequence number of this event. + */ + sequence_number: number; + + /** + * The type of the event. Always `response.file_search_call.completed`. + */ + type: 'response.file_search_call.completed'; +} + +/** + * Emitted when a file search call is initiated. + */ +export interface ResponseFileSearchCallInProgressEvent { + /** + * The ID of the output item that the file search call is initiated. + */ + item_id: string; + + /** + * The index of the output item that the file search call is initiated. + */ + output_index: number; + + /** + * The sequence number of this event. + */ + sequence_number: number; + + /** + * The type of the event. Always `response.file_search_call.in_progress`. + */ + type: 'response.file_search_call.in_progress'; +} + +/** + * Emitted when a file search is currently searching. + */ +export interface ResponseFileSearchCallSearchingEvent { + /** + * The ID of the output item that the file search call is initiated. + */ + item_id: string; + + /** + * The index of the output item that the file search call is searching. + */ + output_index: number; + + /** + * The sequence number of this event. + */ + sequence_number: number; + + /** + * The type of the event. Always `response.file_search_call.searching`. + */ + type: 'response.file_search_call.searching'; +} + +/** + * The results of a file search tool call. See the + * [file search guide](https://platform.openai.com/docs/guides/tools-file-search) + * for more information. + */ +export interface ResponseFileSearchToolCall { + /** + * The unique ID of the file search tool call. + */ + id: string; + + /** + * The queries used to search for files. + */ + queries: Array; + + /** + * The status of the file search tool call. One of `in_progress`, `searching`, + * `incomplete` or `failed`, + */ + status: 'in_progress' | 'searching' | 'completed' | 'incomplete' | 'failed'; + + /** + * The type of the file search tool call. Always `file_search_call`. + */ + type: 'file_search_call'; + + /** + * The results of the file search tool call. + */ + results?: Array | null; +} + +export namespace ResponseFileSearchToolCall { + export interface Result { + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. Keys are strings with a maximum + * length of 64 characters. Values are strings with a maximum length of 512 + * characters, booleans, or numbers. + */ + attributes?: { [key: string]: string | number | boolean } | null; + + /** + * The unique ID of the file. + */ + file_id?: string; + + /** + * The name of the file. + */ + filename?: string; + + /** + * The relevance score of the file - a value between 0 and 1. + */ + score?: number; + + /** + * The text that was retrieved from the file. + */ + text?: string; + } +} + +/** + * An object specifying the format that the model must output. + * + * Configuring `{ "type": "json_schema" }` enables Structured Outputs, which + * ensures the model will match your supplied JSON schema. Learn more in the + * [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + * + * The default format is `{ "type": "text" }` with no additional options. + * + * **Not recommended for gpt-4o and newer models:** + * + * Setting to `{ "type": "json_object" }` enables the older JSON mode, which + * ensures the message the model generates is valid JSON. Using `json_schema` is + * preferred for models that support it. + */ +export type ResponseFormatTextConfig = + | Shared.ResponseFormatText + | ResponseFormatTextJSONSchemaConfig + | Shared.ResponseFormatJSONObject; + +/** + * JSON Schema response format. Used to generate structured JSON responses. Learn + * more about + * [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs). + */ +export interface ResponseFormatTextJSONSchemaConfig { + /** + * The name of the response format. Must be a-z, A-Z, 0-9, or contain underscores + * and dashes, with a maximum length of 64. + */ + name: string; + + /** + * The schema for the response format, described as a JSON Schema object. Learn how + * to build JSON schemas [here](https://json-schema.org/). + */ + schema: { [key: string]: unknown }; + + /** + * The type of response format being defined. Always `json_schema`. + */ + type: 'json_schema'; + + /** + * A description of what the response format is for, used by the model to determine + * how to respond in the format. + */ + description?: string; + + /** + * Whether to enable strict schema adherence when generating the output. If set to + * true, the model will always follow the exact schema defined in the `schema` + * field. Only a subset of JSON Schema is supported when `strict` is `true`. To + * learn more, read the + * [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + */ + strict?: boolean | null; +} + +/** + * Emitted when there is a partial function-call arguments delta. + */ +export interface ResponseFunctionCallArgumentsDeltaEvent { + /** + * The function-call arguments delta that is added. + */ + delta: string; + + /** + * The ID of the output item that the function-call arguments delta is added to. + */ + item_id: string; + + /** + * The index of the output item that the function-call arguments delta is added to. + */ + output_index: number; + + /** + * The sequence number of this event. + */ + sequence_number: number; + + /** + * The type of the event. Always `response.function_call_arguments.delta`. + */ + type: 'response.function_call_arguments.delta'; +} + +/** + * Emitted when function-call arguments are finalized. + */ +export interface ResponseFunctionCallArgumentsDoneEvent { + /** + * The function-call arguments. + */ + arguments: string; + + /** + * The ID of the item. + */ + item_id: string; + + /** + * The index of the output item. + */ + output_index: number; + + /** + * The sequence number of this event. + */ + sequence_number: number; + + type: 'response.function_call_arguments.done'; +} + +/** + * A tool call to run a function. See the + * [function calling guide](https://platform.openai.com/docs/guides/function-calling) + * for more information. + */ +export interface ResponseFunctionToolCall { + /** + * A JSON string of the arguments to pass to the function. + */ + arguments: string; + + /** + * The unique ID of the function tool call generated by the model. + */ + call_id: string; + + /** + * The name of the function to run. + */ + name: string; + + /** + * The type of the function tool call. Always `function_call`. + */ + type: 'function_call'; + + /** + * The unique ID of the function tool call. + */ + id?: string; + + /** + * The status of the item. One of `in_progress`, `completed`, or `incomplete`. + * Populated when items are returned via API. + */ + status?: 'in_progress' | 'completed' | 'incomplete'; +} + +/** + * A tool call to run a function. See the + * [function calling guide](https://platform.openai.com/docs/guides/function-calling) + * for more information. + */ +export interface ResponseFunctionToolCallItem extends ResponseFunctionToolCall { + /** + * The unique ID of the function tool call. + */ + id: string; +} + +export interface ResponseFunctionToolCallOutputItem { + /** + * The unique ID of the function call tool output. + */ + id: string; + + /** + * The unique ID of the function tool call generated by the model. + */ + call_id: string; + + /** + * A JSON string of the output of the function tool call. + */ + output: string; + + /** + * The type of the function tool call output. Always `function_call_output`. + */ + type: 'function_call_output'; + + /** + * The status of the item. One of `in_progress`, `completed`, or `incomplete`. + * Populated when items are returned via API. + */ + status?: 'in_progress' | 'completed' | 'incomplete'; +} + +/** + * The results of a web search tool call. See the + * [web search guide](https://platform.openai.com/docs/guides/tools-web-search) for + * more information. + */ +export interface ResponseFunctionWebSearch { + /** + * The unique ID of the web search tool call. + */ + id: string; + + /** + * The status of the web search tool call. + */ + status: 'in_progress' | 'searching' | 'completed' | 'failed'; + + /** + * The type of the web search tool call. Always `web_search_call`. + */ + type: 'web_search_call'; +} + +export namespace ResponseFunctionWebSearch { + /** + * Action type "search" - Performs a web search query. + */ + export interface Search { + /** + * The search query. + */ + query: string; + + /** + * The action type. + */ + type: 'search'; + + /** + * The sources used in the search. + */ + sources?: Array; + } + + export namespace Search { + /** + * A source used in the search. + */ + export interface Source { + /** + * The type of source. Always `url`. + */ + type: 'url'; + + /** + * The URL of the source. + */ + url: string; + } + } + + /** + * Action type "open_page" - Opens a specific URL from search results. + */ + export interface OpenPage { + /** + * The action type. + */ + type: 'open_page'; + + /** + * The URL opened by the model. + */ + url: string; + } + + /** + * Action type "find": Searches for a pattern within a loaded page. + */ + export interface Find { + /** + * The pattern or text to search for within the page. + */ + pattern: string; + + /** + * The action type. + */ + type: 'find'; + + /** + * The URL of the page searched for the pattern. + */ + url: string; + } +} + +/** + * Emitted when an image generation tool call has completed and the final image is + * available. + */ +export interface ResponseImageGenCallCompletedEvent { + /** + * The unique identifier of the image generation item being processed. + */ + item_id: string; + + /** + * The index of the output item in the response's output array. + */ + output_index: number; + + /** + * The sequence number of this event. + */ + sequence_number: number; + + /** + * The type of the event. Always 'response.image_generation_call.completed'. + */ + type: 'response.image_generation_call.completed'; +} + +/** + * Emitted when an image generation tool call is actively generating an image + * (intermediate state). + */ +export interface ResponseImageGenCallGeneratingEvent { + /** + * The unique identifier of the image generation item being processed. + */ + item_id: string; + + /** + * The index of the output item in the response's output array. + */ + output_index: number; + + /** + * The sequence number of the image generation item being processed. + */ + sequence_number: number; + + /** + * The type of the event. Always 'response.image_generation_call.generating'. + */ + type: 'response.image_generation_call.generating'; +} + +/** + * Emitted when an image generation tool call is in progress. + */ +export interface ResponseImageGenCallInProgressEvent { + /** + * The unique identifier of the image generation item being processed. + */ + item_id: string; + + /** + * The index of the output item in the response's output array. + */ + output_index: number; + + /** + * The sequence number of the image generation item being processed. + */ + sequence_number: number; + + /** + * The type of the event. Always 'response.image_generation_call.in_progress'. + */ + type: 'response.image_generation_call.in_progress'; +} + +/** + * Emitted when a partial image is available during image generation streaming. + */ +export interface ResponseImageGenCallPartialImageEvent { + /** + * The unique identifier of the image generation item being processed. + */ + item_id: string; + + /** + * The index of the output item in the response's output array. + */ + output_index: number; + + /** + * Base64-encoded partial image data, suitable for rendering as an image. + */ + partial_image_b64: string; + + /** + * 0-based index for the partial image (backend is 1-based, but this is 0-based for + * the user). + */ + partial_image_index: number; + + /** + * The sequence number of the image generation item being processed. + */ + sequence_number: number; + + /** + * The type of the event. Always 'response.image_generation_call.partial_image'. + */ + type: 'response.image_generation_call.partial_image'; +} + +/** + * Emitted when the response is in progress. + */ +export interface ResponseInProgressEvent { + /** + * The response that is in progress. + */ + response: Response; + + /** + * The sequence number of this event. + */ + sequence_number: number; + + /** + * The type of the event. Always `response.in_progress`. + */ + type: 'response.in_progress'; +} + +/** + * Specify additional output data to include in the model response. Currently + * supported values are: + * + * - `web_search_call.action.sources`: Include the sources of the web search tool + * call. + * - `code_interpreter_call.outputs`: Includes the outputs of python code execution + * in code interpreter tool call items. + * - `computer_call_output.output.image_url`: Include image urls from the computer + * call output. + * - `file_search_call.results`: Include the search results of the file search tool + * call. + * - `message.input_image.image_url`: Include image urls from the input message. + * - `computer_call_output.output.image_url`: Include image urls from the computer + * call output. + * - `reasoning.encrypted_content`: Includes an encrypted version of reasoning + * tokens in reasoning item outputs. This enables reasoning items to be used in + * multi-turn conversations when using the Responses API statelessly (like when + * the `store` parameter is set to `false`, or when an organization is enrolled + * in the zero data retention program). + * - `code_interpreter_call.outputs`: Includes the outputs of python code execution + * in code interpreter tool call items. + */ +export type ResponseIncludable = + | 'file_search_call.results' + | 'message.input_image.image_url' + | 'computer_call_output.output.image_url' + | 'reasoning.encrypted_content' + | 'code_interpreter_call.outputs'; + +/** + * An event that is emitted when a response finishes as incomplete. + */ +export interface ResponseIncompleteEvent { + /** + * The response that was incomplete. + */ + response: Response; + + /** + * The sequence number of this event. + */ + sequence_number: number; + + /** + * The type of the event. Always `response.incomplete`. + */ + type: 'response.incomplete'; +} + +/** + * A list of one or many input items to the model, containing different content + * types. + */ +export type ResponseInput = Array; + +/** + * An audio input to the model. + */ +export interface ResponseInputAudio { + /** + * Base64-encoded audio data. + */ + data: string; + + /** + * The format of the audio data. Currently supported formats are `mp3` and `wav`. + */ + format: 'mp3' | 'wav'; + + /** + * The type of the input item. Always `input_audio`. + */ + type: 'input_audio'; +} + +/** + * A text input to the model. + */ +export type ResponseInputContent = ResponseInputText | ResponseInputImage | ResponseInputFile; + +/** + * A file input to the model. + */ +export interface ResponseInputFile { + /** + * The type of the input item. Always `input_file`. + */ + type: 'input_file'; + + /** + * The content of the file to be sent to the model. + */ + file_data?: string; + + /** + * The ID of the file to be sent to the model. + */ + file_id?: string | null; + + /** + * The URL of the file to be sent to the model. + */ + file_url?: string; + + /** + * The name of the file to be sent to the model. + */ + filename?: string; +} + +/** + * An image input to the model. Learn about + * [image inputs](https://platform.openai.com/docs/guides/vision). + */ +export interface ResponseInputImage { + /** + * The detail level of the image to be sent to the model. One of `high`, `low`, or + * `auto`. Defaults to `auto`. + */ + detail: 'low' | 'high' | 'auto'; + + /** + * The type of the input item. Always `input_image`. + */ + type: 'input_image'; + + /** + * The ID of the file to be sent to the model. + */ + file_id?: string | null; + + /** + * The URL of the image to be sent to the model. A fully qualified URL or base64 + * encoded image in a data URL. + */ + image_url?: string | null; +} + +/** + * A message input to the model with a role indicating instruction following + * hierarchy. Instructions given with the `developer` or `system` role take + * precedence over instructions given with the `user` role. Messages with the + * `assistant` role are presumed to have been generated by the model in previous + * interactions. + */ +export type ResponseInputItem = + | EasyInputMessage + | ResponseInputItem.Message + | ResponseOutputMessage + | ResponseFileSearchToolCall + | ResponseComputerToolCall + | ResponseInputItem.ComputerCallOutput + | ResponseFunctionWebSearch + | ResponseFunctionToolCall + | ResponseInputItem.FunctionCallOutput + | ResponseReasoningItem + | ResponseInputItem.ImageGenerationCall + | ResponseCodeInterpreterToolCall + | ResponseInputItem.LocalShellCall + | ResponseInputItem.LocalShellCallOutput + | ResponseInputItem.McpListTools + | ResponseInputItem.McpApprovalRequest + | ResponseInputItem.McpApprovalResponse + | ResponseInputItem.McpCall + | ResponseCustomToolCallOutput + | ResponseCustomToolCall + | ResponseInputItem.ItemReference; + +export namespace ResponseInputItem { + /** + * A message input to the model with a role indicating instruction following + * hierarchy. Instructions given with the `developer` or `system` role take + * precedence over instructions given with the `user` role. + */ + export interface Message { + /** + * A list of one or many input items to the model, containing different content + * types. + */ + content: ResponsesAPI.ResponseInputMessageContentList; + + /** + * The role of the message input. One of `user`, `system`, or `developer`. + */ + role: 'user' | 'system' | 'developer'; + + /** + * The status of item. One of `in_progress`, `completed`, or `incomplete`. + * Populated when items are returned via API. + */ + status?: 'in_progress' | 'completed' | 'incomplete'; + + /** + * The type of the message input. Always set to `message`. + */ + type?: 'message'; + } + + /** + * The output of a computer tool call. + */ + export interface ComputerCallOutput { + /** + * The ID of the computer tool call that produced the output. + */ + call_id: string; + + /** + * A computer screenshot image used with the computer use tool. + */ + output: ResponsesAPI.ResponseComputerToolCallOutputScreenshot; + + /** + * The type of the computer tool call output. Always `computer_call_output`. + */ + type: 'computer_call_output'; + + /** + * The ID of the computer tool call output. + */ + id?: string | null; + + /** + * The safety checks reported by the API that have been acknowledged by the + * developer. + */ + acknowledged_safety_checks?: Array | null; + + /** + * The status of the message input. One of `in_progress`, `completed`, or + * `incomplete`. Populated when input items are returned via API. + */ + status?: 'in_progress' | 'completed' | 'incomplete' | null; + } + + export namespace ComputerCallOutput { + /** + * A pending safety check for the computer call. + */ + export interface AcknowledgedSafetyCheck { + /** + * The ID of the pending safety check. + */ + id: string; + + /** + * The type of the pending safety check. + */ + code?: string | null; + + /** + * Details about the pending safety check. + */ + message?: string | null; + } + } + + /** + * The output of a function tool call. + */ + export interface FunctionCallOutput { + /** + * The unique ID of the function tool call generated by the model. + */ + call_id: string; + + /** + * A JSON string of the output of the function tool call. + */ + output: string; + + /** + * The type of the function tool call output. Always `function_call_output`. + */ + type: 'function_call_output'; + + /** + * The unique ID of the function tool call output. Populated when this item is + * returned via API. + */ + id?: string | null; + + /** + * The status of the item. One of `in_progress`, `completed`, or `incomplete`. + * Populated when items are returned via API. + */ + status?: 'in_progress' | 'completed' | 'incomplete' | null; + } + + /** + * An image generation request made by the model. + */ + export interface ImageGenerationCall { + /** + * The unique ID of the image generation call. + */ + id: string; + + /** + * The generated image encoded in base64. + */ + result: string | null; + + /** + * The status of the image generation call. + */ + status: 'in_progress' | 'completed' | 'generating' | 'failed'; + + /** + * The type of the image generation call. Always `image_generation_call`. + */ + type: 'image_generation_call'; + } + + /** + * A tool call to run a command on the local shell. + */ + export interface LocalShellCall { + /** + * The unique ID of the local shell call. + */ + id: string; + + /** + * Execute a shell command on the server. + */ + action: LocalShellCall.Action; + + /** + * The unique ID of the local shell tool call generated by the model. + */ + call_id: string; + + /** + * The status of the local shell call. + */ + status: 'in_progress' | 'completed' | 'incomplete'; + + /** + * The type of the local shell call. Always `local_shell_call`. + */ + type: 'local_shell_call'; + } + + export namespace LocalShellCall { + /** + * Execute a shell command on the server. + */ + export interface Action { + /** + * The command to run. + */ + command: Array; + + /** + * Environment variables to set for the command. + */ + env: { [key: string]: string }; + + /** + * The type of the local shell action. Always `exec`. + */ + type: 'exec'; + + /** + * Optional timeout in milliseconds for the command. + */ + timeout_ms?: number | null; + + /** + * Optional user to run the command as. + */ + user?: string | null; + + /** + * Optional working directory to run the command in. + */ + working_directory?: string | null; + } + } + + /** + * The output of a local shell tool call. + */ + export interface LocalShellCallOutput { + /** + * The unique ID of the local shell tool call generated by the model. + */ + id: string; + + /** + * A JSON string of the output of the local shell tool call. + */ + output: string; + + /** + * The type of the local shell tool call output. Always `local_shell_call_output`. + */ + type: 'local_shell_call_output'; + + /** + * The status of the item. One of `in_progress`, `completed`, or `incomplete`. + */ + status?: 'in_progress' | 'completed' | 'incomplete' | null; + } + + /** + * A list of tools available on an MCP server. + */ + export interface McpListTools { + /** + * The unique ID of the list. + */ + id: string; + + /** + * The label of the MCP server. + */ + server_label: string; + + /** + * The tools available on the server. + */ + tools: Array; + + /** + * The type of the item. Always `mcp_list_tools`. + */ + type: 'mcp_list_tools'; + + /** + * Error message if the server could not list tools. + */ + error?: string | null; + } + + export namespace McpListTools { + /** + * A tool available on an MCP server. + */ + export interface Tool { + /** + * The JSON schema describing the tool's input. + */ + input_schema: unknown; + + /** + * The name of the tool. + */ + name: string; + + /** + * Additional annotations about the tool. + */ + annotations?: unknown | null; + + /** + * The description of the tool. + */ + description?: string | null; + } + } + + /** + * A request for human approval of a tool invocation. + */ + export interface McpApprovalRequest { + /** + * The unique ID of the approval request. + */ + id: string; + + /** + * A JSON string of arguments for the tool. + */ + arguments: string; + + /** + * The name of the tool to run. + */ + name: string; + + /** + * The label of the MCP server making the request. + */ + server_label: string; + + /** + * The type of the item. Always `mcp_approval_request`. + */ + type: 'mcp_approval_request'; + } + + /** + * A response to an MCP approval request. + */ + export interface McpApprovalResponse { + /** + * The ID of the approval request being answered. + */ + approval_request_id: string; + + /** + * Whether the request was approved. + */ + approve: boolean; + + /** + * The type of the item. Always `mcp_approval_response`. + */ + type: 'mcp_approval_response'; + + /** + * The unique ID of the approval response + */ + id?: string | null; + + /** + * Optional reason for the decision. + */ + reason?: string | null; + } + + /** + * An invocation of a tool on an MCP server. + */ + export interface McpCall { + /** + * The unique ID of the tool call. + */ + id: string; + + /** + * A JSON string of the arguments passed to the tool. + */ + arguments: string; + + /** + * The name of the tool that was run. + */ + name: string; + + /** + * The label of the MCP server running the tool. + */ + server_label: string; + + /** + * The type of the item. Always `mcp_call`. + */ + type: 'mcp_call'; + + /** + * The error from the tool call, if any. + */ + error?: string | null; + + /** + * The output from the tool call. + */ + output?: string | null; + } + + /** + * An internal identifier for an item to reference. + */ + export interface ItemReference { + /** + * The ID of the item to reference. + */ + id: string; + + /** + * The type of item to reference. Always `item_reference`. + */ + type?: 'item_reference' | null; + } +} + +/** + * A list of one or many input items to the model, containing different content + * types. + */ +export type ResponseInputMessageContentList = Array; + +export interface ResponseInputMessageItem { + /** + * The unique ID of the message input. + */ + id: string; + + /** + * A list of one or many input items to the model, containing different content + * types. + */ + content: ResponseInputMessageContentList; + + /** + * The role of the message input. One of `user`, `system`, or `developer`. + */ + role: 'user' | 'system' | 'developer'; + + /** + * The status of item. One of `in_progress`, `completed`, or `incomplete`. + * Populated when items are returned via API. + */ + status?: 'in_progress' | 'completed' | 'incomplete'; + + /** + * The type of the message input. Always set to `message`. + */ + type?: 'message'; +} + +/** + * A text input to the model. + */ +export interface ResponseInputText { + /** + * The text input to the model. + */ + text: string; + + /** + * The type of the input item. Always `input_text`. + */ + type: 'input_text'; +} + +/** + * Content item used to generate a response. + */ +export type ResponseItem = + | ResponseInputMessageItem + | ResponseOutputMessage + | ResponseFileSearchToolCall + | ResponseComputerToolCall + | ResponseComputerToolCallOutputItem + | ResponseFunctionWebSearch + | ResponseFunctionToolCallItem + | ResponseFunctionToolCallOutputItem + | ResponseItem.ImageGenerationCall + | ResponseCodeInterpreterToolCall + | ResponseItem.LocalShellCall + | ResponseItem.LocalShellCallOutput + | ResponseItem.McpListTools + | ResponseItem.McpApprovalRequest + | ResponseItem.McpApprovalResponse + | ResponseItem.McpCall; + +export namespace ResponseItem { + /** + * An image generation request made by the model. + */ + export interface ImageGenerationCall { + /** + * The unique ID of the image generation call. + */ + id: string; + + /** + * The generated image encoded in base64. + */ + result: string | null; + + /** + * The status of the image generation call. + */ + status: 'in_progress' | 'completed' | 'generating' | 'failed'; + + /** + * The type of the image generation call. Always `image_generation_call`. + */ + type: 'image_generation_call'; + } + + /** + * A tool call to run a command on the local shell. + */ + export interface LocalShellCall { + /** + * The unique ID of the local shell call. + */ + id: string; + + /** + * Execute a shell command on the server. + */ + action: LocalShellCall.Action; + + /** + * The unique ID of the local shell tool call generated by the model. + */ + call_id: string; + + /** + * The status of the local shell call. + */ + status: 'in_progress' | 'completed' | 'incomplete'; + + /** + * The type of the local shell call. Always `local_shell_call`. + */ + type: 'local_shell_call'; + } + + export namespace LocalShellCall { + /** + * Execute a shell command on the server. + */ + export interface Action { + /** + * The command to run. + */ + command: Array; + + /** + * Environment variables to set for the command. + */ + env: { [key: string]: string }; + + /** + * The type of the local shell action. Always `exec`. + */ + type: 'exec'; + + /** + * Optional timeout in milliseconds for the command. + */ + timeout_ms?: number | null; + + /** + * Optional user to run the command as. + */ + user?: string | null; + + /** + * Optional working directory to run the command in. + */ + working_directory?: string | null; + } + } + + /** + * The output of a local shell tool call. + */ + export interface LocalShellCallOutput { + /** + * The unique ID of the local shell tool call generated by the model. + */ + id: string; + + /** + * A JSON string of the output of the local shell tool call. + */ + output: string; + + /** + * The type of the local shell tool call output. Always `local_shell_call_output`. + */ + type: 'local_shell_call_output'; + + /** + * The status of the item. One of `in_progress`, `completed`, or `incomplete`. + */ + status?: 'in_progress' | 'completed' | 'incomplete' | null; + } + + /** + * A list of tools available on an MCP server. + */ + export interface McpListTools { + /** + * The unique ID of the list. + */ + id: string; + + /** + * The label of the MCP server. + */ + server_label: string; + + /** + * The tools available on the server. + */ + tools: Array; + + /** + * The type of the item. Always `mcp_list_tools`. + */ + type: 'mcp_list_tools'; + + /** + * Error message if the server could not list tools. + */ + error?: string | null; + } + + export namespace McpListTools { + /** + * A tool available on an MCP server. + */ + export interface Tool { + /** + * The JSON schema describing the tool's input. + */ + input_schema: unknown; + + /** + * The name of the tool. + */ + name: string; + + /** + * Additional annotations about the tool. + */ + annotations?: unknown | null; + + /** + * The description of the tool. + */ + description?: string | null; + } + } + + /** + * A request for human approval of a tool invocation. + */ + export interface McpApprovalRequest { + /** + * The unique ID of the approval request. + */ + id: string; + + /** + * A JSON string of arguments for the tool. + */ + arguments: string; + + /** + * The name of the tool to run. + */ + name: string; + + /** + * The label of the MCP server making the request. + */ + server_label: string; + + /** + * The type of the item. Always `mcp_approval_request`. + */ + type: 'mcp_approval_request'; + } + + /** + * A response to an MCP approval request. + */ + export interface McpApprovalResponse { + /** + * The unique ID of the approval response + */ + id: string; + + /** + * The ID of the approval request being answered. + */ + approval_request_id: string; + + /** + * Whether the request was approved. + */ + approve: boolean; + + /** + * The type of the item. Always `mcp_approval_response`. + */ + type: 'mcp_approval_response'; + + /** + * Optional reason for the decision. + */ + reason?: string | null; + } + + /** + * An invocation of a tool on an MCP server. + */ + export interface McpCall { + /** + * The unique ID of the tool call. + */ + id: string; + + /** + * A JSON string of the arguments passed to the tool. + */ + arguments: string; + + /** + * The name of the tool that was run. + */ + name: string; + + /** + * The label of the MCP server running the tool. + */ + server_label: string; + + /** + * The type of the item. Always `mcp_call`. + */ + type: 'mcp_call'; + + /** + * The error from the tool call, if any. + */ + error?: string | null; + + /** + * The output from the tool call. + */ + output?: string | null; + } +} + +/** + * Emitted when there is a delta (partial update) to the arguments of an MCP tool + * call. + */ +export interface ResponseMcpCallArgumentsDeltaEvent { + /** + * A JSON string containing the partial update to the arguments for the MCP tool + * call. + */ + delta: string; + + /** + * The unique identifier of the MCP tool call item being processed. + */ + item_id: string; + + /** + * The index of the output item in the response's output array. + */ + output_index: number; + + /** + * The sequence number of this event. + */ + sequence_number: number; + + /** + * The type of the event. Always 'response.mcp_call_arguments.delta'. + */ + type: 'response.mcp_call_arguments.delta'; +} + +/** + * Emitted when the arguments for an MCP tool call are finalized. + */ +export interface ResponseMcpCallArgumentsDoneEvent { + /** + * A JSON string containing the finalized arguments for the MCP tool call. + */ + arguments: string; + + /** + * The unique identifier of the MCP tool call item being processed. + */ + item_id: string; + + /** + * The index of the output item in the response's output array. + */ + output_index: number; + + /** + * The sequence number of this event. + */ + sequence_number: number; + + /** + * The type of the event. Always 'response.mcp_call_arguments.done'. + */ + type: 'response.mcp_call_arguments.done'; +} + +/** + * Emitted when an MCP tool call has completed successfully. + */ +export interface ResponseMcpCallCompletedEvent { + /** + * The ID of the MCP tool call item that completed. + */ + item_id: string; + + /** + * The index of the output item that completed. + */ + output_index: number; + + /** + * The sequence number of this event. + */ + sequence_number: number; + + /** + * The type of the event. Always 'response.mcp_call.completed'. + */ + type: 'response.mcp_call.completed'; +} + +/** + * Emitted when an MCP tool call has failed. + */ +export interface ResponseMcpCallFailedEvent { + /** + * The ID of the MCP tool call item that failed. + */ + item_id: string; + + /** + * The index of the output item that failed. + */ + output_index: number; + + /** + * The sequence number of this event. + */ + sequence_number: number; + + /** + * The type of the event. Always 'response.mcp_call.failed'. + */ + type: 'response.mcp_call.failed'; +} + +/** + * Emitted when an MCP tool call is in progress. + */ +export interface ResponseMcpCallInProgressEvent { + /** + * The unique identifier of the MCP tool call item being processed. + */ + item_id: string; + + /** + * The index of the output item in the response's output array. + */ + output_index: number; + + /** + * The sequence number of this event. + */ + sequence_number: number; + + /** + * The type of the event. Always 'response.mcp_call.in_progress'. + */ + type: 'response.mcp_call.in_progress'; +} + +/** + * Emitted when the list of available MCP tools has been successfully retrieved. + */ +export interface ResponseMcpListToolsCompletedEvent { + /** + * The ID of the MCP tool call item that produced this output. + */ + item_id: string; + + /** + * The index of the output item that was processed. + */ + output_index: number; + + /** + * The sequence number of this event. + */ + sequence_number: number; + + /** + * The type of the event. Always 'response.mcp_list_tools.completed'. + */ + type: 'response.mcp_list_tools.completed'; +} + +/** + * Emitted when the attempt to list available MCP tools has failed. + */ +export interface ResponseMcpListToolsFailedEvent { + /** + * The ID of the MCP tool call item that failed. + */ + item_id: string; + + /** + * The index of the output item that failed. + */ + output_index: number; + + /** + * The sequence number of this event. + */ + sequence_number: number; + + /** + * The type of the event. Always 'response.mcp_list_tools.failed'. + */ + type: 'response.mcp_list_tools.failed'; +} + +/** + * Emitted when the system is in the process of retrieving the list of available + * MCP tools. + */ +export interface ResponseMcpListToolsInProgressEvent { + /** + * The ID of the MCP tool call item that is being processed. + */ + item_id: string; + + /** + * The index of the output item that is being processed. + */ + output_index: number; + + /** + * The sequence number of this event. + */ + sequence_number: number; + + /** + * The type of the event. Always 'response.mcp_list_tools.in_progress'. + */ + type: 'response.mcp_list_tools.in_progress'; +} + +/** + * An audio output from the model. + */ +export interface ResponseOutputAudio { + /** + * Base64-encoded audio data from the model. + */ + data: string; + + /** + * The transcript of the audio data from the model. + */ + transcript: string; + + /** + * The type of the output audio. Always `output_audio`. + */ + type: 'output_audio'; +} + +/** + * An output message from the model. + */ +export type ResponseOutputItem = + | ResponseOutputMessage + | ResponseFileSearchToolCall + | ResponseFunctionToolCall + | ResponseFunctionWebSearch + | ResponseComputerToolCall + | ResponseReasoningItem + | ResponseOutputItem.ImageGenerationCall + | ResponseCodeInterpreterToolCall + | ResponseOutputItem.LocalShellCall + | ResponseOutputItem.McpCall + | ResponseOutputItem.McpListTools + | ResponseOutputItem.McpApprovalRequest + | ResponseCustomToolCall; + +export namespace ResponseOutputItem { + /** + * An image generation request made by the model. + */ + export interface ImageGenerationCall { + /** + * The unique ID of the image generation call. + */ + id: string; + + /** + * The generated image encoded in base64. + */ + result: string | null; + + /** + * The status of the image generation call. + */ + status: 'in_progress' | 'completed' | 'generating' | 'failed'; + + /** + * The type of the image generation call. Always `image_generation_call`. + */ + type: 'image_generation_call'; + } + + /** + * A tool call to run a command on the local shell. + */ + export interface LocalShellCall { + /** + * The unique ID of the local shell call. + */ + id: string; + + /** + * Execute a shell command on the server. + */ + action: LocalShellCall.Action; + + /** + * The unique ID of the local shell tool call generated by the model. + */ + call_id: string; + + /** + * The status of the local shell call. + */ + status: 'in_progress' | 'completed' | 'incomplete'; + + /** + * The type of the local shell call. Always `local_shell_call`. + */ + type: 'local_shell_call'; + } + + export namespace LocalShellCall { + /** + * Execute a shell command on the server. + */ + export interface Action { + /** + * The command to run. + */ + command: Array; + + /** + * Environment variables to set for the command. + */ + env: { [key: string]: string }; + + /** + * The type of the local shell action. Always `exec`. + */ + type: 'exec'; + + /** + * Optional timeout in milliseconds for the command. + */ + timeout_ms?: number | null; + + /** + * Optional user to run the command as. + */ + user?: string | null; + + /** + * Optional working directory to run the command in. + */ + working_directory?: string | null; + } + } + + /** + * An invocation of a tool on an MCP server. + */ + export interface McpCall { + /** + * The unique ID of the tool call. + */ + id: string; + + /** + * A JSON string of the arguments passed to the tool. + */ + arguments: string; + + /** + * The name of the tool that was run. + */ + name: string; + + /** + * The label of the MCP server running the tool. + */ + server_label: string; + + /** + * The type of the item. Always `mcp_call`. + */ + type: 'mcp_call'; + + /** + * The error from the tool call, if any. + */ + error?: string | null; + + /** + * The output from the tool call. + */ + output?: string | null; + } + + /** + * A list of tools available on an MCP server. + */ + export interface McpListTools { + /** + * The unique ID of the list. + */ + id: string; + + /** + * The label of the MCP server. + */ + server_label: string; + + /** + * The tools available on the server. + */ + tools: Array; + + /** + * The type of the item. Always `mcp_list_tools`. + */ + type: 'mcp_list_tools'; + + /** + * Error message if the server could not list tools. + */ + error?: string | null; + } + + export namespace McpListTools { + /** + * A tool available on an MCP server. + */ + export interface Tool { + /** + * The JSON schema describing the tool's input. + */ + input_schema: unknown; + + /** + * The name of the tool. + */ + name: string; + + /** + * Additional annotations about the tool. + */ + annotations?: unknown | null; + + /** + * The description of the tool. + */ + description?: string | null; + } + } + + /** + * A request for human approval of a tool invocation. + */ + export interface McpApprovalRequest { + /** + * The unique ID of the approval request. + */ + id: string; + + /** + * A JSON string of arguments for the tool. + */ + arguments: string; + + /** + * The name of the tool to run. + */ + name: string; + + /** + * The label of the MCP server making the request. + */ + server_label: string; + + /** + * The type of the item. Always `mcp_approval_request`. + */ + type: 'mcp_approval_request'; + } +} + +/** + * Emitted when a new output item is added. + */ +export interface ResponseOutputItemAddedEvent { + /** + * The output item that was added. + */ + item: ResponseOutputItem; + + /** + * The index of the output item that was added. + */ + output_index: number; + + /** + * The sequence number of this event. + */ + sequence_number: number; + + /** + * The type of the event. Always `response.output_item.added`. + */ + type: 'response.output_item.added'; +} + +/** + * Emitted when an output item is marked done. + */ +export interface ResponseOutputItemDoneEvent { + /** + * The output item that was marked done. + */ + item: ResponseOutputItem; + + /** + * The index of the output item that was marked done. + */ + output_index: number; + + /** + * The sequence number of this event. + */ + sequence_number: number; + + /** + * The type of the event. Always `response.output_item.done`. + */ + type: 'response.output_item.done'; +} + +/** + * An output message from the model. + */ +export interface ResponseOutputMessage { + /** + * The unique ID of the output message. + */ + id: string; + + /** + * The content of the output message. + */ + content: Array; + + /** + * The role of the output message. Always `assistant`. + */ + role: 'assistant'; + + /** + * The status of the message input. One of `in_progress`, `completed`, or + * `incomplete`. Populated when input items are returned via API. + */ + status: 'in_progress' | 'completed' | 'incomplete'; + + /** + * The type of the output message. Always `message`. + */ + type: 'message'; +} + +/** + * A refusal from the model. + */ +export interface ResponseOutputRefusal { + /** + * The refusal explanation from the model. + */ + refusal: string; + + /** + * The type of the refusal. Always `refusal`. + */ + type: 'refusal'; +} + +/** + * A text output from the model. + */ +export interface ResponseOutputText { + /** + * The annotations of the text output. + */ + annotations: Array< + | ResponseOutputText.FileCitation + | ResponseOutputText.URLCitation + | ResponseOutputText.ContainerFileCitation + | ResponseOutputText.FilePath + >; + + /** + * The text output from the model. + */ + text: string; + + /** + * The type of the output text. Always `output_text`. + */ + type: 'output_text'; + + logprobs?: Array; +} + +export namespace ResponseOutputText { + /** + * A citation to a file. + */ + export interface FileCitation { + /** + * The ID of the file. + */ + file_id: string; + + /** + * The filename of the file cited. + */ + filename: string; + + /** + * The index of the file in the list of files. + */ + index: number; + + /** + * The type of the file citation. Always `file_citation`. + */ + type: 'file_citation'; + } + + /** + * A citation for a web resource used to generate a model response. + */ + export interface URLCitation { + /** + * The index of the last character of the URL citation in the message. + */ + end_index: number; + + /** + * The index of the first character of the URL citation in the message. + */ + start_index: number; + + /** + * The title of the web resource. + */ + title: string; + + /** + * The type of the URL citation. Always `url_citation`. + */ + type: 'url_citation'; + + /** + * The URL of the web resource. + */ + url: string; + } + + /** + * A citation for a container file used to generate a model response. + */ + export interface ContainerFileCitation { + /** + * The ID of the container file. + */ + container_id: string; + + /** + * The index of the last character of the container file citation in the message. + */ + end_index: number; + + /** + * The ID of the file. + */ + file_id: string; + + /** + * The filename of the container file cited. + */ + filename: string; + + /** + * The index of the first character of the container file citation in the message. + */ + start_index: number; + + /** + * The type of the container file citation. Always `container_file_citation`. + */ + type: 'container_file_citation'; + } + + /** + * A path to a file. + */ + export interface FilePath { + /** + * The ID of the file. + */ + file_id: string; + + /** + * The index of the file in the list of files. + */ + index: number; + + /** + * The type of the file path. Always `file_path`. + */ + type: 'file_path'; + } + + /** + * The log probability of a token. + */ + export interface Logprob { + token: string; + + bytes: Array; + + logprob: number; + + top_logprobs: Array; + } + + export namespace Logprob { + /** + * The top log probability of a token. + */ + export interface TopLogprob { + token: string; + + bytes: Array; + + logprob: number; + } + } +} + +/** + * Emitted when an annotation is added to output text content. + */ +export interface ResponseOutputTextAnnotationAddedEvent { + /** + * The annotation object being added. (See annotation schema for details.) + */ + annotation: unknown; + + /** + * The index of the annotation within the content part. + */ + annotation_index: number; + + /** + * The index of the content part within the output item. + */ + content_index: number; + + /** + * The unique identifier of the item to which the annotation is being added. + */ + item_id: string; + + /** + * The index of the output item in the response's output array. + */ + output_index: number; + + /** + * The sequence number of this event. + */ + sequence_number: number; + + /** + * The type of the event. Always 'response.output_text.annotation.added'. + */ + type: 'response.output_text.annotation.added'; +} + +/** + * Reference to a prompt template and its variables. + * [Learn more](https://platform.openai.com/docs/guides/text?api-mode=responses#reusable-prompts). + */ +export interface ResponsePrompt { + /** + * The unique identifier of the prompt template to use. + */ + id: string; + + /** + * Optional map of values to substitute in for variables in your prompt. The + * substitution values can either be strings, or other Response input types like + * images or files. + */ + variables?: { [key: string]: string | ResponseInputText | ResponseInputImage | ResponseInputFile } | null; + + /** + * Optional version of the prompt template. + */ + version?: string | null; +} + +/** + * Emitted when a response is queued and waiting to be processed. + */ +export interface ResponseQueuedEvent { + /** + * The full response object that is queued. + */ + response: Response; + + /** + * The sequence number for this event. + */ + sequence_number: number; + + /** + * The type of the event. Always 'response.queued'. + */ + type: 'response.queued'; +} + +/** + * A description of the chain of thought used by a reasoning model while generating + * a response. Be sure to include these items in your `input` to the Responses API + * for subsequent turns of a conversation if you are manually + * [managing context](https://platform.openai.com/docs/guides/conversation-state). + */ +export interface ResponseReasoningItem { + /** + * The unique identifier of the reasoning content. + */ + id: string; + + /** + * Reasoning summary content. + */ + summary: Array; + + /** + * The type of the object. Always `reasoning`. + */ + type: 'reasoning'; + + /** + * Reasoning text content. + */ + content?: Array; + + /** + * The encrypted content of the reasoning item - populated when a response is + * generated with `reasoning.encrypted_content` in the `include` parameter. + */ + encrypted_content?: string | null; + + /** + * The status of the item. One of `in_progress`, `completed`, or `incomplete`. + * Populated when items are returned via API. + */ + status?: 'in_progress' | 'completed' | 'incomplete'; +} + +export namespace ResponseReasoningItem { + export interface Summary { + /** + * A summary of the reasoning output from the model so far. + */ + text: string; + + /** + * The type of the object. Always `summary_text`. + */ + type: 'summary_text'; + } + + export interface Content { + /** + * Reasoning text output from the model. + */ + text: string; + + /** + * The type of the object. Always `reasoning_text`. + */ + type: 'reasoning_text'; + } +} + +/** + * Emitted when a new reasoning summary part is added. + */ +export interface ResponseReasoningSummaryPartAddedEvent { + /** + * The ID of the item this summary part is associated with. + */ + item_id: string; + + /** + * The index of the output item this summary part is associated with. + */ + output_index: number; + + /** + * The summary part that was added. + */ + part: ResponseReasoningSummaryPartAddedEvent.Part; + + /** + * The sequence number of this event. + */ + sequence_number: number; + + /** + * The index of the summary part within the reasoning summary. + */ + summary_index: number; + + /** + * The type of the event. Always `response.reasoning_summary_part.added`. + */ + type: 'response.reasoning_summary_part.added'; +} + +export namespace ResponseReasoningSummaryPartAddedEvent { + /** + * The summary part that was added. + */ + export interface Part { + /** + * The text of the summary part. + */ + text: string; + + /** + * The type of the summary part. Always `summary_text`. + */ + type: 'summary_text'; + } +} + +/** + * Emitted when a reasoning summary part is completed. + */ +export interface ResponseReasoningSummaryPartDoneEvent { + /** + * The ID of the item this summary part is associated with. + */ + item_id: string; + + /** + * The index of the output item this summary part is associated with. + */ + output_index: number; + + /** + * The completed summary part. + */ + part: ResponseReasoningSummaryPartDoneEvent.Part; + + /** + * The sequence number of this event. + */ + sequence_number: number; + + /** + * The index of the summary part within the reasoning summary. + */ + summary_index: number; + + /** + * The type of the event. Always `response.reasoning_summary_part.done`. + */ + type: 'response.reasoning_summary_part.done'; +} + +export namespace ResponseReasoningSummaryPartDoneEvent { + /** + * The completed summary part. + */ + export interface Part { + /** + * The text of the summary part. + */ + text: string; + + /** + * The type of the summary part. Always `summary_text`. + */ + type: 'summary_text'; + } +} + +/** + * Emitted when a delta is added to a reasoning summary text. + */ +export interface ResponseReasoningSummaryTextDeltaEvent { + /** + * The text delta that was added to the summary. + */ + delta: string; + + /** + * The ID of the item this summary text delta is associated with. + */ + item_id: string; + + /** + * The index of the output item this summary text delta is associated with. + */ + output_index: number; + + /** + * The sequence number of this event. + */ + sequence_number: number; + + /** + * The index of the summary part within the reasoning summary. + */ + summary_index: number; + + /** + * The type of the event. Always `response.reasoning_summary_text.delta`. + */ + type: 'response.reasoning_summary_text.delta'; +} + +/** + * Emitted when a reasoning summary text is completed. + */ +export interface ResponseReasoningSummaryTextDoneEvent { + /** + * The ID of the item this summary text is associated with. + */ + item_id: string; + + /** + * The index of the output item this summary text is associated with. + */ + output_index: number; + + /** + * The sequence number of this event. + */ + sequence_number: number; + + /** + * The index of the summary part within the reasoning summary. + */ + summary_index: number; + + /** + * The full text of the completed reasoning summary. + */ + text: string; + + /** + * The type of the event. Always `response.reasoning_summary_text.done`. + */ + type: 'response.reasoning_summary_text.done'; +} + +/** + * Emitted when a delta is added to a reasoning text. + */ +export interface ResponseReasoningTextDeltaEvent { + /** + * The index of the reasoning content part this delta is associated with. + */ + content_index: number; + + /** + * The text delta that was added to the reasoning content. + */ + delta: string; + + /** + * The ID of the item this reasoning text delta is associated with. + */ + item_id: string; + + /** + * The index of the output item this reasoning text delta is associated with. + */ + output_index: number; + + /** + * The sequence number of this event. + */ + sequence_number: number; + + /** + * The type of the event. Always `response.reasoning_text.delta`. + */ + type: 'response.reasoning_text.delta'; +} + +/** + * Emitted when a reasoning text is completed. + */ +export interface ResponseReasoningTextDoneEvent { + /** + * The index of the reasoning content part. + */ + content_index: number; + + /** + * The ID of the item this reasoning text is associated with. + */ + item_id: string; + + /** + * The index of the output item this reasoning text is associated with. + */ + output_index: number; + + /** + * The sequence number of this event. + */ + sequence_number: number; + + /** + * The full text of the completed reasoning content. + */ + text: string; + + /** + * The type of the event. Always `response.reasoning_text.done`. + */ + type: 'response.reasoning_text.done'; +} + +/** + * Emitted when there is a partial refusal text. + */ +export interface ResponseRefusalDeltaEvent { + /** + * The index of the content part that the refusal text is added to. + */ + content_index: number; + + /** + * The refusal text that is added. + */ + delta: string; + + /** + * The ID of the output item that the refusal text is added to. + */ + item_id: string; + + /** + * The index of the output item that the refusal text is added to. + */ + output_index: number; + + /** + * The sequence number of this event. + */ + sequence_number: number; + + /** + * The type of the event. Always `response.refusal.delta`. + */ + type: 'response.refusal.delta'; +} + +/** + * Emitted when refusal text is finalized. + */ +export interface ResponseRefusalDoneEvent { + /** + * The index of the content part that the refusal text is finalized. + */ + content_index: number; + + /** + * The ID of the output item that the refusal text is finalized. + */ + item_id: string; + + /** + * The index of the output item that the refusal text is finalized. + */ + output_index: number; + + /** + * The refusal text that is finalized. + */ + refusal: string; + + /** + * The sequence number of this event. + */ + sequence_number: number; + + /** + * The type of the event. Always `response.refusal.done`. + */ + type: 'response.refusal.done'; +} + +/** + * The status of the response generation. One of `completed`, `failed`, + * `in_progress`, `cancelled`, `queued`, or `incomplete`. + */ +export type ResponseStatus = 'completed' | 'failed' | 'in_progress' | 'cancelled' | 'queued' | 'incomplete'; + +/** + * Emitted when there is a partial audio response. + */ +export type ResponseStreamEvent = + | ResponseAudioDeltaEvent + | ResponseAudioDoneEvent + | ResponseAudioTranscriptDeltaEvent + | ResponseAudioTranscriptDoneEvent + | ResponseCodeInterpreterCallCodeDeltaEvent + | ResponseCodeInterpreterCallCodeDoneEvent + | ResponseCodeInterpreterCallCompletedEvent + | ResponseCodeInterpreterCallInProgressEvent + | ResponseCodeInterpreterCallInterpretingEvent + | ResponseCompletedEvent + | ResponseContentPartAddedEvent + | ResponseContentPartDoneEvent + | ResponseCreatedEvent + | ResponseErrorEvent + | ResponseFileSearchCallCompletedEvent + | ResponseFileSearchCallInProgressEvent + | ResponseFileSearchCallSearchingEvent + | ResponseFunctionCallArgumentsDeltaEvent + | ResponseFunctionCallArgumentsDoneEvent + | ResponseInProgressEvent + | ResponseFailedEvent + | ResponseIncompleteEvent + | ResponseOutputItemAddedEvent + | ResponseOutputItemDoneEvent + | ResponseReasoningSummaryPartAddedEvent + | ResponseReasoningSummaryPartDoneEvent + | ResponseReasoningSummaryTextDeltaEvent + | ResponseReasoningSummaryTextDoneEvent + | ResponseReasoningTextDeltaEvent + | ResponseReasoningTextDoneEvent + | ResponseRefusalDeltaEvent + | ResponseRefusalDoneEvent + | ResponseTextDeltaEvent + | ResponseTextDoneEvent + | ResponseWebSearchCallCompletedEvent + | ResponseWebSearchCallInProgressEvent + | ResponseWebSearchCallSearchingEvent + | ResponseImageGenCallCompletedEvent + | ResponseImageGenCallGeneratingEvent + | ResponseImageGenCallInProgressEvent + | ResponseImageGenCallPartialImageEvent + | ResponseMcpCallArgumentsDeltaEvent + | ResponseMcpCallArgumentsDoneEvent + | ResponseMcpCallCompletedEvent + | ResponseMcpCallFailedEvent + | ResponseMcpCallInProgressEvent + | ResponseMcpListToolsCompletedEvent + | ResponseMcpListToolsFailedEvent + | ResponseMcpListToolsInProgressEvent + | ResponseOutputTextAnnotationAddedEvent + | ResponseQueuedEvent + | ResponseCustomToolCallInputDeltaEvent + | ResponseCustomToolCallInputDoneEvent; + +/** + * Configuration options for a text response from the model. Can be plain text or + * structured JSON data. Learn more: + * + * - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + * - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) + */ +export interface ResponseTextConfig { + /** + * An object specifying the format that the model must output. + * + * Configuring `{ "type": "json_schema" }` enables Structured Outputs, which + * ensures the model will match your supplied JSON schema. Learn more in the + * [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + * + * The default format is `{ "type": "text" }` with no additional options. + * + * **Not recommended for gpt-4o and newer models:** + * + * Setting to `{ "type": "json_object" }` enables the older JSON mode, which + * ensures the message the model generates is valid JSON. Using `json_schema` is + * preferred for models that support it. + */ + format?: ResponseFormatTextConfig; + + /** + * Constrains the verbosity of the model's response. Lower values will result in + * more concise responses, while higher values will result in more verbose + * responses. Currently supported values are `low`, `medium`, and `high`. + */ + verbosity?: 'low' | 'medium' | 'high' | null; +} + +/** + * Emitted when there is an additional text delta. + */ +export interface ResponseTextDeltaEvent { + /** + * The index of the content part that the text delta was added to. + */ + content_index: number; + + /** + * The text delta that was added. + */ + delta: string; + + /** + * The ID of the output item that the text delta was added to. + */ + item_id: string; + + /** + * The log probabilities of the tokens in the delta. + */ + logprobs: Array; + + /** + * The index of the output item that the text delta was added to. + */ + output_index: number; + + /** + * The sequence number for this event. + */ + sequence_number: number; + + /** + * The type of the event. Always `response.output_text.delta`. + */ + type: 'response.output_text.delta'; +} + +export namespace ResponseTextDeltaEvent { + /** + * A logprob is the logarithmic probability that the model assigns to producing a + * particular token at a given position in the sequence. Less-negative (higher) + * logprob values indicate greater model confidence in that token choice. + */ + export interface Logprob { + /** + * A possible text token. + */ + token: string; + + /** + * The log probability of this token. + */ + logprob: number; + + /** + * The log probability of the top 20 most likely tokens. + */ + top_logprobs?: Array; + } + + export namespace Logprob { + export interface TopLogprob { + /** + * A possible text token. + */ + token?: string; + + /** + * The log probability of this token. + */ + logprob?: number; + } + } +} + +/** + * Emitted when text content is finalized. + */ +export interface ResponseTextDoneEvent { + /** + * The index of the content part that the text content is finalized. + */ + content_index: number; + + /** + * The ID of the output item that the text content is finalized. + */ + item_id: string; + + /** + * The log probabilities of the tokens in the delta. + */ + logprobs: Array; + + /** + * The index of the output item that the text content is finalized. + */ + output_index: number; + + /** + * The sequence number for this event. + */ + sequence_number: number; + + /** + * The text content that is finalized. + */ + text: string; + + /** + * The type of the event. Always `response.output_text.done`. + */ + type: 'response.output_text.done'; +} + +export namespace ResponseTextDoneEvent { + /** + * A logprob is the logarithmic probability that the model assigns to producing a + * particular token at a given position in the sequence. Less-negative (higher) + * logprob values indicate greater model confidence in that token choice. + */ + export interface Logprob { + /** + * A possible text token. + */ + token: string; + + /** + * The log probability of this token. + */ + logprob: number; + + /** + * The log probability of the top 20 most likely tokens. + */ + top_logprobs?: Array; + } + + export namespace Logprob { + export interface TopLogprob { + /** + * A possible text token. + */ + token?: string; + + /** + * The log probability of this token. + */ + logprob?: number; + } + } +} + +/** + * Represents token usage details including input tokens, output tokens, a + * breakdown of output tokens, and the total tokens used. + */ +export interface ResponseUsage { + /** + * The number of input tokens. + */ + input_tokens: number; + + /** + * A detailed breakdown of the input tokens. + */ + input_tokens_details: ResponseUsage.InputTokensDetails; + + /** + * The number of output tokens. + */ + output_tokens: number; + + /** + * A detailed breakdown of the output tokens. + */ + output_tokens_details: ResponseUsage.OutputTokensDetails; + + /** + * The total number of tokens used. + */ + total_tokens: number; +} + +export namespace ResponseUsage { + /** + * A detailed breakdown of the input tokens. + */ + export interface InputTokensDetails { + /** + * The number of tokens that were retrieved from the cache. + * [More on prompt caching](https://platform.openai.com/docs/guides/prompt-caching). + */ + cached_tokens: number; + } + + /** + * A detailed breakdown of the output tokens. + */ + export interface OutputTokensDetails { + /** + * The number of reasoning tokens. + */ + reasoning_tokens: number; + } +} + +/** + * Emitted when a web search call is completed. + */ +export interface ResponseWebSearchCallCompletedEvent { + /** + * Unique ID for the output item associated with the web search call. + */ + item_id: string; + + /** + * The index of the output item that the web search call is associated with. + */ + output_index: number; + + /** + * The sequence number of the web search call being processed. + */ + sequence_number: number; + + /** + * The type of the event. Always `response.web_search_call.completed`. + */ + type: 'response.web_search_call.completed'; +} + +/** + * Emitted when a web search call is initiated. + */ +export interface ResponseWebSearchCallInProgressEvent { + /** + * Unique ID for the output item associated with the web search call. + */ + item_id: string; + + /** + * The index of the output item that the web search call is associated with. + */ + output_index: number; + + /** + * The sequence number of the web search call being processed. + */ + sequence_number: number; + + /** + * The type of the event. Always `response.web_search_call.in_progress`. + */ + type: 'response.web_search_call.in_progress'; +} + +/** + * Emitted when a web search call is executing. + */ +export interface ResponseWebSearchCallSearchingEvent { + /** + * Unique ID for the output item associated with the web search call. + */ + item_id: string; + + /** + * The index of the output item that the web search call is associated with. + */ + output_index: number; + + /** + * The sequence number of the web search call being processed. + */ + sequence_number: number; + + /** + * The type of the event. Always `response.web_search_call.searching`. + */ + type: 'response.web_search_call.searching'; +} + +/** + * A tool that can be used to generate a response. + */ +export type Tool = + | FunctionTool + | FileSearchTool + | ComputerTool + | Tool.WebSearchTool + | Tool.Mcp + | Tool.CodeInterpreter + | Tool.ImageGeneration + | Tool.LocalShell + | CustomTool + | WebSearchTool; + +export namespace Tool { + /** + * Search the Internet for sources related to the prompt. Learn more about the + * [web search tool](https://platform.openai.com/docs/guides/tools-web-search). + */ + export interface WebSearchTool { + /** + * The type of the web search tool. One of `web_search` or `web_search_2025_08_26`. + */ + type: 'web_search' | 'web_search_2025_08_26'; + + /** + * Filters for the search. + */ + filters?: WebSearchTool.Filters | null; + + /** + * High level guidance for the amount of context window space to use for the + * search. One of `low`, `medium`, or `high`. `medium` is the default. + */ + search_context_size?: 'low' | 'medium' | 'high'; + + /** + * The approximate location of the user. + */ + user_location?: WebSearchTool.UserLocation | null; + } + + export namespace WebSearchTool { + /** + * Filters for the search. + */ + export interface Filters { + /** + * Allowed domains for the search. If not provided, all domains are allowed. + * Subdomains of the provided domains are allowed as well. + * + * Example: `["pubmed.ncbi.nlm.nih.gov"]` + */ + allowed_domains?: Array | null; + } + + /** + * The approximate location of the user. + */ + export interface UserLocation { + /** + * Free text input for the city of the user, e.g. `San Francisco`. + */ + city?: string | null; + + /** + * The two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of + * the user, e.g. `US`. + */ + country?: string | null; + + /** + * Free text input for the region of the user, e.g. `California`. + */ + region?: string | null; + + /** + * The [IANA timezone](https://timeapi.io/documentation/iana-timezones) of the + * user, e.g. `America/Los_Angeles`. + */ + timezone?: string | null; + + /** + * The type of location approximation. Always `approximate`. + */ + type?: 'approximate'; + } + } + + /** + * Give the model access to additional tools via remote Model Context Protocol + * (MCP) servers. + * [Learn more about MCP](https://platform.openai.com/docs/guides/tools-remote-mcp). + */ + export interface Mcp { + /** + * A label for this MCP server, used to identify it in tool calls. + */ + server_label: string; + + /** + * The type of the MCP tool. Always `mcp`. + */ + type: 'mcp'; + + /** + * List of allowed tool names or a filter object. + */ + allowed_tools?: Array | Mcp.McpToolFilter | null; + + /** + * An OAuth access token that can be used with a remote MCP server, either with a + * custom MCP server URL or a service connector. Your application must handle the + * OAuth authorization flow and provide the token here. + */ + authorization?: string; + + /** + * Identifier for service connectors, like those available in ChatGPT. One of + * `server_url` or `connector_id` must be provided. Learn more about service + * connectors + * [here](https://platform.openai.com/docs/guides/tools-remote-mcp#connectors). + * + * Currently supported `connector_id` values are: + * + * - Dropbox: `connector_dropbox` + * - Gmail: `connector_gmail` + * - Google Calendar: `connector_googlecalendar` + * - Google Drive: `connector_googledrive` + * - Microsoft Teams: `connector_microsoftteams` + * - Outlook Calendar: `connector_outlookcalendar` + * - Outlook Email: `connector_outlookemail` + * - SharePoint: `connector_sharepoint` + */ + connector_id?: + | 'connector_dropbox' + | 'connector_gmail' + | 'connector_googlecalendar' + | 'connector_googledrive' + | 'connector_microsoftteams' + | 'connector_outlookcalendar' + | 'connector_outlookemail' + | 'connector_sharepoint'; + + /** + * Optional HTTP headers to send to the MCP server. Use for authentication or other + * purposes. + */ + headers?: { [key: string]: string } | null; + + /** + * Specify which of the MCP server's tools require approval. + */ + require_approval?: Mcp.McpToolApprovalFilter | 'always' | 'never' | null; + + /** + * Optional description of the MCP server, used to provide more context. + */ + server_description?: string; + + /** + * The URL for the MCP server. One of `server_url` or `connector_id` must be + * provided. + */ + server_url?: string; + } + + export namespace Mcp { + /** + * A filter object to specify which tools are allowed. + */ + export interface McpToolFilter { + /** + * Indicates whether or not a tool modifies data or is read-only. If an MCP server + * is + * [annotated with `readOnlyHint`](https://modelcontextprotocol.io/specification/2025-06-18/schema#toolannotations-readonlyhint), + * it will match this filter. + */ + read_only?: boolean; + + /** + * List of allowed tool names. + */ + tool_names?: Array; + } + + /** + * Specify which of the MCP server's tools require approval. Can be `always`, + * `never`, or a filter object associated with tools that require approval. + */ + export interface McpToolApprovalFilter { + /** + * A filter object to specify which tools are allowed. + */ + always?: McpToolApprovalFilter.Always; + + /** + * A filter object to specify which tools are allowed. + */ + never?: McpToolApprovalFilter.Never; + } + + export namespace McpToolApprovalFilter { + /** + * A filter object to specify which tools are allowed. + */ + export interface Always { + /** + * Indicates whether or not a tool modifies data or is read-only. If an MCP server + * is + * [annotated with `readOnlyHint`](https://modelcontextprotocol.io/specification/2025-06-18/schema#toolannotations-readonlyhint), + * it will match this filter. + */ + read_only?: boolean; + + /** + * List of allowed tool names. + */ + tool_names?: Array; + } + + /** + * A filter object to specify which tools are allowed. + */ + export interface Never { + /** + * Indicates whether or not a tool modifies data or is read-only. If an MCP server + * is + * [annotated with `readOnlyHint`](https://modelcontextprotocol.io/specification/2025-06-18/schema#toolannotations-readonlyhint), + * it will match this filter. + */ + read_only?: boolean; + + /** + * List of allowed tool names. + */ + tool_names?: Array; + } + } + } + + /** + * A tool that runs Python code to help generate a response to a prompt. + */ + export interface CodeInterpreter { + /** + * The code interpreter container. Can be a container ID or an object that + * specifies uploaded file IDs to make available to your code. + */ + container: string | CodeInterpreter.CodeInterpreterToolAuto; + + /** + * The type of the code interpreter tool. Always `code_interpreter`. + */ + type: 'code_interpreter'; + } + + export namespace CodeInterpreter { + /** + * Configuration for a code interpreter container. Optionally specify the IDs of + * the files to run the code on. + */ + export interface CodeInterpreterToolAuto { + /** + * Always `auto`. + */ + type: 'auto'; + + /** + * An optional list of uploaded files to make available to your code. + */ + file_ids?: Array; + } + } + + /** + * A tool that generates images using a model like `gpt-image-1`. + */ + export interface ImageGeneration { + /** + * The type of the image generation tool. Always `image_generation`. + */ + type: 'image_generation'; + + /** + * Background type for the generated image. One of `transparent`, `opaque`, or + * `auto`. Default: `auto`. + */ + background?: 'transparent' | 'opaque' | 'auto'; + + /** + * Control how much effort the model will exert to match the style and features, + * especially facial features, of input images. This parameter is only supported + * for `gpt-image-1`. Supports `high` and `low`. Defaults to `low`. + */ + input_fidelity?: 'high' | 'low' | null; + + /** + * Optional mask for inpainting. Contains `image_url` (string, optional) and + * `file_id` (string, optional). + */ + input_image_mask?: ImageGeneration.InputImageMask; + + /** + * The image generation model to use. Default: `gpt-image-1`. + */ + model?: 'gpt-image-1'; + + /** + * Moderation level for the generated image. Default: `auto`. + */ + moderation?: 'auto' | 'low'; + + /** + * Compression level for the output image. Default: 100. + */ + output_compression?: number; + + /** + * The output format of the generated image. One of `png`, `webp`, or `jpeg`. + * Default: `png`. + */ + output_format?: 'png' | 'webp' | 'jpeg'; + + /** + * Number of partial images to generate in streaming mode, from 0 (default value) + * to 3. + */ + partial_images?: number; + + /** + * The quality of the generated image. One of `low`, `medium`, `high`, or `auto`. + * Default: `auto`. + */ + quality?: 'low' | 'medium' | 'high' | 'auto'; + + /** + * The size of the generated image. One of `1024x1024`, `1024x1536`, `1536x1024`, + * or `auto`. Default: `auto`. + */ + size?: '1024x1024' | '1024x1536' | '1536x1024' | 'auto'; + } + + export namespace ImageGeneration { + /** + * Optional mask for inpainting. Contains `image_url` (string, optional) and + * `file_id` (string, optional). + */ + export interface InputImageMask { + /** + * File ID for the mask image. + */ + file_id?: string; + + /** + * Base64-encoded mask image. + */ + image_url?: string; + } + } + + /** + * A tool that allows the model to execute shell commands in a local environment. + */ + export interface LocalShell { + /** + * The type of the local shell tool. Always `local_shell`. + */ + type: 'local_shell'; + } +} + +/** + * Constrains the tools available to the model to a pre-defined set. + */ +export interface ToolChoiceAllowed { + /** + * Constrains the tools available to the model to a pre-defined set. + * + * `auto` allows the model to pick from among the allowed tools and generate a + * message. + * + * `required` requires the model to call one or more of the allowed tools. + */ + mode: 'auto' | 'required'; + + /** + * A list of tool definitions that the model should be allowed to call. + * + * For the Responses API, the list of tool definitions might look like: + * + * ```json + * [ + * { "type": "function", "name": "get_weather" }, + * { "type": "mcp", "server_label": "deepwiki" }, + * { "type": "image_generation" } + * ] + * ``` + */ + tools: Array<{ [key: string]: unknown }>; + + /** + * Allowed tool configuration type. Always `allowed_tools`. + */ + type: 'allowed_tools'; +} + +/** + * Use this option to force the model to call a specific custom tool. + */ +export interface ToolChoiceCustom { + /** + * The name of the custom tool to call. + */ + name: string; + + /** + * For custom tool calling, the type is always `custom`. + */ + type: 'custom'; +} + +/** + * Use this option to force the model to call a specific function. + */ +export interface ToolChoiceFunction { + /** + * The name of the function to call. + */ + name: string; + + /** + * For function calling, the type is always `function`. + */ + type: 'function'; +} + +/** + * Use this option to force the model to call a specific tool on a remote MCP + * server. + */ +export interface ToolChoiceMcp { + /** + * The label of the MCP server to use. + */ + server_label: string; + + /** + * For MCP tools, the type is always `mcp`. + */ + type: 'mcp'; + + /** + * The name of the tool to call on the server. + */ + name?: string | null; +} + +/** + * Controls which (if any) tool is called by the model. + * + * `none` means the model will not call any tool and instead generates a message. + * + * `auto` means the model can pick between generating a message or calling one or + * more tools. + * + * `required` means the model must call one or more tools. + */ +export type ToolChoiceOptions = 'none' | 'auto' | 'required'; + +/** + * Indicates that the model should use a built-in tool to generate a response. + * [Learn more about built-in tools](https://platform.openai.com/docs/guides/tools). + */ +export interface ToolChoiceTypes { + /** + * The type of hosted tool the model should to use. Learn more about + * [built-in tools](https://platform.openai.com/docs/guides/tools). + * + * Allowed values are: + * + * - `file_search` + * - `web_search_preview` + * - `computer_use_preview` + * - `code_interpreter` + * - `mcp` + * - `image_generation` + */ + type: + | 'file_search' + | 'web_search_preview' + | 'computer_use_preview' + | 'web_search_preview_2025_03_11' + | 'image_generation' + | 'code_interpreter' + | 'mcp'; +} + +/** + * This tool searches the web for relevant results to use in a response. Learn more + * about the + * [web search tool](https://platform.openai.com/docs/guides/tools-web-search). + */ +export interface WebSearchTool { + /** + * The type of the web search tool. One of `web_search_preview` or + * `web_search_preview_2025_03_11`. + */ + type: 'web_search_preview' | 'web_search_preview_2025_03_11'; + + /** + * High level guidance for the amount of context window space to use for the + * search. One of `low`, `medium`, or `high`. `medium` is the default. + */ + search_context_size?: 'low' | 'medium' | 'high'; + + /** + * The user's location. + */ + user_location?: WebSearchTool.UserLocation | null; +} + +export namespace WebSearchTool { + /** + * The user's location. + */ + export interface UserLocation { + /** + * The type of location approximation. Always `approximate`. + */ + type: 'approximate'; + + /** + * Free text input for the city of the user, e.g. `San Francisco`. + */ + city?: string | null; + + /** + * The two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of + * the user, e.g. `US`. + */ + country?: string | null; + + /** + * Free text input for the region of the user, e.g. `California`. + */ + region?: string | null; + + /** + * The [IANA timezone](https://timeapi.io/documentation/iana-timezones) of the + * user, e.g. `America/Los_Angeles`. + */ + timezone?: string | null; + } +} + +export type ResponseCreateParams = ResponseCreateParamsNonStreaming | ResponseCreateParamsStreaming; + +export interface ResponseCreateParamsBase { + /** + * Whether to run the model response in the background. + * [Learn more](https://platform.openai.com/docs/guides/background). + */ + background?: boolean | null; + + /** + * The conversation that this response belongs to. Items from this conversation are + * prepended to `input_items` for this response request. Input items and output + * items from this response are automatically added to this conversation after this + * response completes. + */ + conversation?: string | ResponseConversationParam | null; + + /** + * Specify additional output data to include in the model response. Currently + * supported values are: + * + * - `web_search_call.action.sources`: Include the sources of the web search tool + * call. + * - `code_interpreter_call.outputs`: Includes the outputs of python code execution + * in code interpreter tool call items. + * - `computer_call_output.output.image_url`: Include image urls from the computer + * call output. + * - `file_search_call.results`: Include the search results of the file search tool + * call. + * - `message.input_image.image_url`: Include image urls from the input message. + * - `computer_call_output.output.image_url`: Include image urls from the computer + * call output. + * - `reasoning.encrypted_content`: Includes an encrypted version of reasoning + * tokens in reasoning item outputs. This enables reasoning items to be used in + * multi-turn conversations when using the Responses API statelessly (like when + * the `store` parameter is set to `false`, or when an organization is enrolled + * in the zero data retention program). + * - `code_interpreter_call.outputs`: Includes the outputs of python code execution + * in code interpreter tool call items. + */ + include?: Array | null; + + /** + * Text, image, or file inputs to the model, used to generate a response. + * + * Learn more: + * + * - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + * - [Image inputs](https://platform.openai.com/docs/guides/images) + * - [File inputs](https://platform.openai.com/docs/guides/pdf-files) + * - [Conversation state](https://platform.openai.com/docs/guides/conversation-state) + * - [Function calling](https://platform.openai.com/docs/guides/function-calling) + */ + input?: string | ResponseInput; + + /** + * A system (or developer) message inserted into the model's context. + * + * When using along with `previous_response_id`, the instructions from a previous + * response will not be carried over to the next response. This makes it simple to + * swap out system (or developer) messages in new responses. + */ + instructions?: string | null; + + /** + * An upper bound for the number of tokens that can be generated for a response, + * including visible output tokens and + * [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). + */ + max_output_tokens?: number | null; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; + + /** + * Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI offers a + * wide range of models with different capabilities, performance characteristics, + * and price points. Refer to the + * [model guide](https://platform.openai.com/docs/models) to browse and compare + * available models. + */ + model?: Shared.ResponsesModel; + + /** + * Whether to allow the model to run tool calls in parallel. + */ + parallel_tool_calls?: boolean | null; + + /** + * The unique ID of the previous response to the model. Use this to create + * multi-turn conversations. Learn more about + * [conversation state](https://platform.openai.com/docs/guides/conversation-state). + * Cannot be used in conjunction with `conversation`. + */ + previous_response_id?: string | null; + + /** + * Reference to a prompt template and its variables. + * [Learn more](https://platform.openai.com/docs/guides/text?api-mode=responses#reusable-prompts). + */ + prompt?: ResponsePrompt | null; + + /** + * Used by OpenAI to cache responses for similar requests to optimize your cache + * hit rates. Replaces the `user` field. + * [Learn more](https://platform.openai.com/docs/guides/prompt-caching). + */ + prompt_cache_key?: string; + + /** + * **gpt-5 and o-series models only** + * + * Configuration options for + * [reasoning models](https://platform.openai.com/docs/guides/reasoning). + */ + reasoning?: Shared.Reasoning | null; + + /** + * A stable identifier used to help detect users of your application that may be + * violating OpenAI's usage policies. The IDs should be a string that uniquely + * identifies each user. We recommend hashing their username or email address, in + * order to avoid sending us any identifying information. + * [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers). + */ + safety_identifier?: string; + + /** + * Specifies the latency tier to use for processing the request. This parameter is + * relevant for customers subscribed to the scale tier service: + * + * - If set to 'auto', then the request will be processed with the service tier + * configured in the Project settings. Unless otherwise configured, the Project + * will use 'default'. + * - If set to 'default', then the request will be processed with the standard + * pricing and performance for the selected model. + * - If set to '[flex](https://platform.openai.com/docs/guides/flex-processing)' or + * '[priority](https://openai.com/api-priority-processing/)', then the request + * will be processed with the corresponding service tier. + * - When not set, the default behavior is 'auto'. + * + * When this parameter is set, the response body will include the `service_tier` + * utilized. + */ + service_tier?: 'auto' | 'default' | 'flex' | 'scale' | 'priority' | null; + + /** + * Whether to store the generated model response for later retrieval via API. + */ + store?: boolean | null; + + /** + * If set to true, the model response data will be streamed to the client as it is + * generated using + * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + * See the + * [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming) + * for more information. + */ + stream?: boolean | null; + + /** + * Options for streaming responses. Only set this when you set `stream: true`. + */ + stream_options?: ResponseCreateParams.StreamOptions | null; + + /** + * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + * make the output more random, while lower values like 0.2 will make it more + * focused and deterministic. We generally recommend altering this or `top_p` but + * not both. + */ + temperature?: number | null; + + /** + * Configuration options for a text response from the model. Can be plain text or + * structured JSON data. Learn more: + * + * - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + * - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) + */ + text?: ResponseTextConfig; + + /** + * How the model should select which tool (or tools) to use when generating a + * response. See the `tools` parameter to see how to specify which tools the model + * can call. + */ + tool_choice?: + | ToolChoiceOptions + | ToolChoiceAllowed + | ToolChoiceTypes + | ToolChoiceFunction + | ToolChoiceMcp + | ToolChoiceCustom; + + /** + * An array of tools the model may call while generating a response. You can + * specify which tool to use by setting the `tool_choice` parameter. + * + * The two categories of tools you can provide the model are: + * + * - **Built-in tools**: Tools that are provided by OpenAI that extend the model's + * capabilities, like + * [web search](https://platform.openai.com/docs/guides/tools-web-search) or + * [file search](https://platform.openai.com/docs/guides/tools-file-search). + * Learn more about + * [built-in tools](https://platform.openai.com/docs/guides/tools). + * - **Function calls (custom tools)**: Functions that are defined by you, enabling + * the model to call your own code with strongly typed arguments and outputs. + * Learn more about + * [function calling](https://platform.openai.com/docs/guides/function-calling). + * You can also use custom tools to call your own code. + */ + tools?: Array; + + /** + * An alternative to sampling with temperature, called nucleus sampling, where the + * model considers the results of the tokens with top_p probability mass. So 0.1 + * means only the tokens comprising the top 10% probability mass are considered. + * + * We generally recommend altering this or `temperature` but not both. + */ + top_p?: number | null; + + /** + * The truncation strategy to use for the model response. + * + * - `auto`: If the context of this response and previous ones exceeds the model's + * context window size, the model will truncate the response to fit the context + * window by dropping input items in the middle of the conversation. + * - `disabled` (default): If a model response will exceed the context window size + * for a model, the request will fail with a 400 error. + */ + truncation?: 'auto' | 'disabled' | null; + + /** + * @deprecated This field is being replaced by `safety_identifier` and + * `prompt_cache_key`. Use `prompt_cache_key` instead to maintain caching + * optimizations. A stable identifier for your end-users. Used to boost cache hit + * rates by better bucketing similar requests and to help OpenAI detect and prevent + * abuse. + * [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers). + */ + user?: string; +} + +export namespace ResponseCreateParams { + /** + * Options for streaming responses. Only set this when you set `stream: true`. + */ + export interface StreamOptions { + /** + * When true, stream obfuscation will be enabled. Stream obfuscation adds random + * characters to an `obfuscation` field on streaming delta events to normalize + * payload sizes as a mitigation to certain side-channel attacks. These obfuscation + * fields are included by default, but add a small amount of overhead to the data + * stream. You can set `include_obfuscation` to false to optimize for bandwidth if + * you trust the network links between your application and the OpenAI API. + */ + include_obfuscation?: boolean; + } + + export type ResponseCreateParamsNonStreaming = ResponsesAPI.ResponseCreateParamsNonStreaming; + export type ResponseCreateParamsStreaming = ResponsesAPI.ResponseCreateParamsStreaming; +} + +export interface ResponseCreateParamsNonStreaming extends ResponseCreateParamsBase { + /** + * If set to true, the model response data will be streamed to the client as it is + * generated using + * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + * See the + * [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming) + * for more information. + */ + stream?: false | null; +} + +export interface ResponseCreateParamsStreaming extends ResponseCreateParamsBase { + /** + * If set to true, the model response data will be streamed to the client as it is + * generated using + * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + * See the + * [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming) + * for more information. + */ + stream: true; +} + +export type ResponseRetrieveParams = ResponseRetrieveParamsNonStreaming | ResponseRetrieveParamsStreaming; + +export interface ResponseRetrieveParamsBase { + /** + * Additional fields to include in the response. See the `include` parameter for + * Response creation above for more information. + */ + include?: Array; + + /** + * When true, stream obfuscation will be enabled. Stream obfuscation adds random + * characters to an `obfuscation` field on streaming delta events to normalize + * payload sizes as a mitigation to certain side-channel attacks. These obfuscation + * fields are included by default, but add a small amount of overhead to the data + * stream. You can set `include_obfuscation` to false to optimize for bandwidth if + * you trust the network links between your application and the OpenAI API. + */ + include_obfuscation?: boolean; + + /** + * The sequence number of the event after which to start streaming. + */ + starting_after?: number; + + /** + * If set to true, the model response data will be streamed to the client as it is + * generated using + * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + * See the + * [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming) + * for more information. + */ + stream?: boolean; +} + +export namespace ResponseRetrieveParams { + export type ResponseRetrieveParamsNonStreaming = ResponsesAPI.ResponseRetrieveParamsNonStreaming; + export type ResponseRetrieveParamsStreaming = ResponsesAPI.ResponseRetrieveParamsStreaming; +} + +export interface ResponseRetrieveParamsNonStreaming extends ResponseRetrieveParamsBase { + /** + * If set to true, the model response data will be streamed to the client as it is + * generated using + * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + * See the + * [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming) + * for more information. + */ + stream?: false; +} + +export interface ResponseRetrieveParamsStreaming extends ResponseRetrieveParamsBase { + /** + * If set to true, the model response data will be streamed to the client as it is + * generated using + * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + * See the + * [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming) + * for more information. + */ + stream: true; +} + +Responses.InputItems = InputItems; + +export declare namespace Responses { + export { + type ComputerTool as ComputerTool, + type CustomTool as CustomTool, + type EasyInputMessage as EasyInputMessage, + type FileSearchTool as FileSearchTool, + type FunctionTool as FunctionTool, + type Response as Response, + type ResponseAudioDeltaEvent as ResponseAudioDeltaEvent, + type ResponseAudioDoneEvent as ResponseAudioDoneEvent, + type ResponseAudioTranscriptDeltaEvent as ResponseAudioTranscriptDeltaEvent, + type ResponseAudioTranscriptDoneEvent as ResponseAudioTranscriptDoneEvent, + type ResponseCodeInterpreterCallCodeDeltaEvent as ResponseCodeInterpreterCallCodeDeltaEvent, + type ResponseCodeInterpreterCallCodeDoneEvent as ResponseCodeInterpreterCallCodeDoneEvent, + type ResponseCodeInterpreterCallCompletedEvent as ResponseCodeInterpreterCallCompletedEvent, + type ResponseCodeInterpreterCallInProgressEvent as ResponseCodeInterpreterCallInProgressEvent, + type ResponseCodeInterpreterCallInterpretingEvent as ResponseCodeInterpreterCallInterpretingEvent, + type ResponseCodeInterpreterToolCall as ResponseCodeInterpreterToolCall, + type ResponseCompletedEvent as ResponseCompletedEvent, + type ResponseComputerToolCall as ResponseComputerToolCall, + type ResponseComputerToolCallOutputItem as ResponseComputerToolCallOutputItem, + type ResponseComputerToolCallOutputScreenshot as ResponseComputerToolCallOutputScreenshot, + type ResponseContent as ResponseContent, + type ResponseContentPartAddedEvent as ResponseContentPartAddedEvent, + type ResponseContentPartDoneEvent as ResponseContentPartDoneEvent, + type ResponseConversationParam as ResponseConversationParam, + type ResponseCreatedEvent as ResponseCreatedEvent, + type ResponseCustomToolCall as ResponseCustomToolCall, + type ResponseCustomToolCallInputDeltaEvent as ResponseCustomToolCallInputDeltaEvent, + type ResponseCustomToolCallInputDoneEvent as ResponseCustomToolCallInputDoneEvent, + type ResponseCustomToolCallOutput as ResponseCustomToolCallOutput, + type ResponseError as ResponseError, + type ResponseErrorEvent as ResponseErrorEvent, + type ResponseFailedEvent as ResponseFailedEvent, + type ResponseFileSearchCallCompletedEvent as ResponseFileSearchCallCompletedEvent, + type ResponseFileSearchCallInProgressEvent as ResponseFileSearchCallInProgressEvent, + type ResponseFileSearchCallSearchingEvent as ResponseFileSearchCallSearchingEvent, + type ResponseFileSearchToolCall as ResponseFileSearchToolCall, + type ResponseFormatTextConfig as ResponseFormatTextConfig, + type ResponseFormatTextJSONSchemaConfig as ResponseFormatTextJSONSchemaConfig, + type ResponseFunctionCallArgumentsDeltaEvent as ResponseFunctionCallArgumentsDeltaEvent, + type ResponseFunctionCallArgumentsDoneEvent as ResponseFunctionCallArgumentsDoneEvent, + type ResponseFunctionToolCall as ResponseFunctionToolCall, + type ResponseFunctionToolCallItem as ResponseFunctionToolCallItem, + type ResponseFunctionToolCallOutputItem as ResponseFunctionToolCallOutputItem, + type ResponseFunctionWebSearch as ResponseFunctionWebSearch, + type ResponseImageGenCallCompletedEvent as ResponseImageGenCallCompletedEvent, + type ResponseImageGenCallGeneratingEvent as ResponseImageGenCallGeneratingEvent, + type ResponseImageGenCallInProgressEvent as ResponseImageGenCallInProgressEvent, + type ResponseImageGenCallPartialImageEvent as ResponseImageGenCallPartialImageEvent, + type ResponseInProgressEvent as ResponseInProgressEvent, + type ResponseIncludable as ResponseIncludable, + type ResponseIncompleteEvent as ResponseIncompleteEvent, + type ResponseInput as ResponseInput, + type ResponseInputAudio as ResponseInputAudio, + type ResponseInputContent as ResponseInputContent, + type ResponseInputFile as ResponseInputFile, + type ResponseInputImage as ResponseInputImage, + type ResponseInputItem as ResponseInputItem, + type ResponseInputMessageContentList as ResponseInputMessageContentList, + type ResponseInputMessageItem as ResponseInputMessageItem, + type ResponseInputText as ResponseInputText, + type ResponseItem as ResponseItem, + type ResponseMcpCallArgumentsDeltaEvent as ResponseMcpCallArgumentsDeltaEvent, + type ResponseMcpCallArgumentsDoneEvent as ResponseMcpCallArgumentsDoneEvent, + type ResponseMcpCallCompletedEvent as ResponseMcpCallCompletedEvent, + type ResponseMcpCallFailedEvent as ResponseMcpCallFailedEvent, + type ResponseMcpCallInProgressEvent as ResponseMcpCallInProgressEvent, + type ResponseMcpListToolsCompletedEvent as ResponseMcpListToolsCompletedEvent, + type ResponseMcpListToolsFailedEvent as ResponseMcpListToolsFailedEvent, + type ResponseMcpListToolsInProgressEvent as ResponseMcpListToolsInProgressEvent, + type ResponseOutputAudio as ResponseOutputAudio, + type ResponseOutputItem as ResponseOutputItem, + type ResponseOutputItemAddedEvent as ResponseOutputItemAddedEvent, + type ResponseOutputItemDoneEvent as ResponseOutputItemDoneEvent, + type ResponseOutputMessage as ResponseOutputMessage, + type ResponseOutputRefusal as ResponseOutputRefusal, + type ResponseOutputText as ResponseOutputText, + type ResponseOutputTextAnnotationAddedEvent as ResponseOutputTextAnnotationAddedEvent, + type ResponsePrompt as ResponsePrompt, + type ResponseQueuedEvent as ResponseQueuedEvent, + type ResponseReasoningItem as ResponseReasoningItem, + type ResponseReasoningSummaryPartAddedEvent as ResponseReasoningSummaryPartAddedEvent, + type ResponseReasoningSummaryPartDoneEvent as ResponseReasoningSummaryPartDoneEvent, + type ResponseReasoningSummaryTextDeltaEvent as ResponseReasoningSummaryTextDeltaEvent, + type ResponseReasoningSummaryTextDoneEvent as ResponseReasoningSummaryTextDoneEvent, + type ResponseReasoningTextDeltaEvent as ResponseReasoningTextDeltaEvent, + type ResponseReasoningTextDoneEvent as ResponseReasoningTextDoneEvent, + type ResponseRefusalDeltaEvent as ResponseRefusalDeltaEvent, + type ResponseRefusalDoneEvent as ResponseRefusalDoneEvent, + type ResponseStatus as ResponseStatus, + type ResponseStreamEvent as ResponseStreamEvent, + type ResponseTextConfig as ResponseTextConfig, + type ResponseTextDeltaEvent as ResponseTextDeltaEvent, + type ResponseTextDoneEvent as ResponseTextDoneEvent, + type ResponseUsage as ResponseUsage, + type ResponseWebSearchCallCompletedEvent as ResponseWebSearchCallCompletedEvent, + type ResponseWebSearchCallInProgressEvent as ResponseWebSearchCallInProgressEvent, + type ResponseWebSearchCallSearchingEvent as ResponseWebSearchCallSearchingEvent, + type Tool as Tool, + type ToolChoiceAllowed as ToolChoiceAllowed, + type ToolChoiceCustom as ToolChoiceCustom, + type ToolChoiceFunction as ToolChoiceFunction, + type ToolChoiceMcp as ToolChoiceMcp, + type ToolChoiceOptions as ToolChoiceOptions, + type ToolChoiceTypes as ToolChoiceTypes, + type WebSearchTool as WebSearchTool, + type ResponseCreateParams as ResponseCreateParams, + type ResponseCreateParamsNonStreaming as ResponseCreateParamsNonStreaming, + type ResponseCreateParamsStreaming as ResponseCreateParamsStreaming, + type ResponseRetrieveParams as ResponseRetrieveParams, + type ResponseRetrieveParamsNonStreaming as ResponseRetrieveParamsNonStreaming, + type ResponseRetrieveParamsStreaming as ResponseRetrieveParamsStreaming, + }; + + export { + InputItems as InputItems, + type ResponseItemList as ResponseItemList, + type InputItemListParams as InputItemListParams, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/shared.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/shared.ts new file mode 100644 index 0000000000000000000000000000000000000000..3c2503ba8406593226082abf825e1e3eb2544c3c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/shared.ts @@ -0,0 +1,383 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export type AllModels = + | (string & {}) + | ChatModel + | 'o1-pro' + | 'o1-pro-2025-03-19' + | 'o3-pro' + | 'o3-pro-2025-06-10' + | 'o3-deep-research' + | 'o3-deep-research-2025-06-26' + | 'o4-mini-deep-research' + | 'o4-mini-deep-research-2025-06-26' + | 'computer-use-preview' + | 'computer-use-preview-2025-03-11'; + +export type ChatModel = + | 'gpt-5' + | 'gpt-5-mini' + | 'gpt-5-nano' + | 'gpt-5-2025-08-07' + | 'gpt-5-mini-2025-08-07' + | 'gpt-5-nano-2025-08-07' + | 'gpt-5-chat-latest' + | 'gpt-4.1' + | 'gpt-4.1-mini' + | 'gpt-4.1-nano' + | 'gpt-4.1-2025-04-14' + | 'gpt-4.1-mini-2025-04-14' + | 'gpt-4.1-nano-2025-04-14' + | 'o4-mini' + | 'o4-mini-2025-04-16' + | 'o3' + | 'o3-2025-04-16' + | 'o3-mini' + | 'o3-mini-2025-01-31' + | 'o1' + | 'o1-2024-12-17' + | 'o1-preview' + | 'o1-preview-2024-09-12' + | 'o1-mini' + | 'o1-mini-2024-09-12' + | 'gpt-4o' + | 'gpt-4o-2024-11-20' + | 'gpt-4o-2024-08-06' + | 'gpt-4o-2024-05-13' + | 'gpt-4o-audio-preview' + | 'gpt-4o-audio-preview-2024-10-01' + | 'gpt-4o-audio-preview-2024-12-17' + | 'gpt-4o-audio-preview-2025-06-03' + | 'gpt-4o-mini-audio-preview' + | 'gpt-4o-mini-audio-preview-2024-12-17' + | 'gpt-4o-search-preview' + | 'gpt-4o-mini-search-preview' + | 'gpt-4o-search-preview-2025-03-11' + | 'gpt-4o-mini-search-preview-2025-03-11' + | 'chatgpt-4o-latest' + | 'codex-mini-latest' + | 'gpt-4o-mini' + | 'gpt-4o-mini-2024-07-18' + | 'gpt-4-turbo' + | 'gpt-4-turbo-2024-04-09' + | 'gpt-4-0125-preview' + | 'gpt-4-turbo-preview' + | 'gpt-4-1106-preview' + | 'gpt-4-vision-preview' + | 'gpt-4' + | 'gpt-4-0314' + | 'gpt-4-0613' + | 'gpt-4-32k' + | 'gpt-4-32k-0314' + | 'gpt-4-32k-0613' + | 'gpt-3.5-turbo' + | 'gpt-3.5-turbo-16k' + | 'gpt-3.5-turbo-0301' + | 'gpt-3.5-turbo-0613' + | 'gpt-3.5-turbo-1106' + | 'gpt-3.5-turbo-0125' + | 'gpt-3.5-turbo-16k-0613'; + +/** + * A filter used to compare a specified attribute key to a given value using a + * defined comparison operation. + */ +export interface ComparisonFilter { + /** + * The key to compare against the value. + */ + key: string; + + /** + * Specifies the comparison operator: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`. + * + * - `eq`: equals + * - `ne`: not equal + * - `gt`: greater than + * - `gte`: greater than or equal + * - `lt`: less than + * - `lte`: less than or equal + */ + type: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte'; + + /** + * The value to compare against the attribute key; supports string, number, or + * boolean types. + */ + value: string | number | boolean; +} + +/** + * Combine multiple filters using `and` or `or`. + */ +export interface CompoundFilter { + /** + * Array of filters to combine. Items can be `ComparisonFilter` or + * `CompoundFilter`. + */ + filters: Array; + + /** + * Type of operation: `and` or `or`. + */ + type: 'and' | 'or'; +} + +/** + * The input format for the custom tool. Default is unconstrained text. + */ +export type CustomToolInputFormat = CustomToolInputFormat.Text | CustomToolInputFormat.Grammar; + +export namespace CustomToolInputFormat { + /** + * Unconstrained free-form text. + */ + export interface Text { + /** + * Unconstrained text format. Always `text`. + */ + type: 'text'; + } + + /** + * A grammar defined by the user. + */ + export interface Grammar { + /** + * The grammar definition. + */ + definition: string; + + /** + * The syntax of the grammar definition. One of `lark` or `regex`. + */ + syntax: 'lark' | 'regex'; + + /** + * Grammar format. Always `grammar`. + */ + type: 'grammar'; + } +} + +export interface ErrorObject { + code: string | null; + + message: string; + + param: string | null; + + type: string; +} + +export interface FunctionDefinition { + /** + * The name of the function to be called. Must be a-z, A-Z, 0-9, or contain + * underscores and dashes, with a maximum length of 64. + */ + name: string; + + /** + * A description of what the function does, used by the model to choose when and + * how to call the function. + */ + description?: string; + + /** + * The parameters the functions accepts, described as a JSON Schema object. See the + * [guide](https://platform.openai.com/docs/guides/function-calling) for examples, + * and the + * [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for + * documentation about the format. + * + * Omitting `parameters` defines a function with an empty parameter list. + */ + parameters?: FunctionParameters; + + /** + * Whether to enable strict schema adherence when generating the function call. If + * set to true, the model will follow the exact schema defined in the `parameters` + * field. Only a subset of JSON Schema is supported when `strict` is `true`. Learn + * more about Structured Outputs in the + * [function calling guide](https://platform.openai.com/docs/guides/function-calling). + */ + strict?: boolean | null; +} + +/** + * The parameters the functions accepts, described as a JSON Schema object. See the + * [guide](https://platform.openai.com/docs/guides/function-calling) for examples, + * and the + * [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for + * documentation about the format. + * + * Omitting `parameters` defines a function with an empty parameter list. + */ +export type FunctionParameters = { [key: string]: unknown }; + +/** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ +export type Metadata = { [key: string]: string }; + +/** + * **gpt-5 and o-series models only** + * + * Configuration options for + * [reasoning models](https://platform.openai.com/docs/guides/reasoning). + */ +export interface Reasoning { + /** + * Constrains effort on reasoning for + * [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently + * supported values are `minimal`, `low`, `medium`, and `high`. Reducing reasoning + * effort can result in faster responses and fewer tokens used on reasoning in a + * response. + */ + effort?: ReasoningEffort | null; + + /** + * @deprecated **Deprecated:** use `summary` instead. + * + * A summary of the reasoning performed by the model. This can be useful for + * debugging and understanding the model's reasoning process. One of `auto`, + * `concise`, or `detailed`. + */ + generate_summary?: 'auto' | 'concise' | 'detailed' | null; + + /** + * A summary of the reasoning performed by the model. This can be useful for + * debugging and understanding the model's reasoning process. One of `auto`, + * `concise`, or `detailed`. + */ + summary?: 'auto' | 'concise' | 'detailed' | null; +} + +/** + * Constrains effort on reasoning for + * [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently + * supported values are `minimal`, `low`, `medium`, and `high`. Reducing reasoning + * effort can result in faster responses and fewer tokens used on reasoning in a + * response. + */ +export type ReasoningEffort = 'minimal' | 'low' | 'medium' | 'high' | null; + +/** + * JSON object response format. An older method of generating JSON responses. Using + * `json_schema` is recommended for models that support it. Note that the model + * will not generate JSON without a system or user message instructing it to do so. + */ +export interface ResponseFormatJSONObject { + /** + * The type of response format being defined. Always `json_object`. + */ + type: 'json_object'; +} + +/** + * JSON Schema response format. Used to generate structured JSON responses. Learn + * more about + * [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs). + */ +export interface ResponseFormatJSONSchema { + /** + * Structured Outputs configuration options, including a JSON Schema. + */ + json_schema: ResponseFormatJSONSchema.JSONSchema; + + /** + * The type of response format being defined. Always `json_schema`. + */ + type: 'json_schema'; +} + +export namespace ResponseFormatJSONSchema { + /** + * Structured Outputs configuration options, including a JSON Schema. + */ + export interface JSONSchema { + /** + * The name of the response format. Must be a-z, A-Z, 0-9, or contain underscores + * and dashes, with a maximum length of 64. + */ + name: string; + + /** + * A description of what the response format is for, used by the model to determine + * how to respond in the format. + */ + description?: string; + + /** + * The schema for the response format, described as a JSON Schema object. Learn how + * to build JSON schemas [here](https://json-schema.org/). + */ + schema?: { [key: string]: unknown }; + + /** + * Whether to enable strict schema adherence when generating the output. If set to + * true, the model will always follow the exact schema defined in the `schema` + * field. Only a subset of JSON Schema is supported when `strict` is `true`. To + * learn more, read the + * [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + */ + strict?: boolean | null; + } +} + +/** + * Default response format. Used to generate text responses. + */ +export interface ResponseFormatText { + /** + * The type of response format being defined. Always `text`. + */ + type: 'text'; +} + +/** + * A custom grammar for the model to follow when generating text. Learn more in the + * [custom grammars guide](https://platform.openai.com/docs/guides/custom-grammars). + */ +export interface ResponseFormatTextGrammar { + /** + * The custom grammar for the model to follow. + */ + grammar: string; + + /** + * The type of response format being defined. Always `grammar`. + */ + type: 'grammar'; +} + +/** + * Configure the model to generate valid Python code. See the + * [custom grammars guide](https://platform.openai.com/docs/guides/custom-grammars) + * for more details. + */ +export interface ResponseFormatTextPython { + /** + * The type of response format being defined. Always `python`. + */ + type: 'python'; +} + +export type ResponsesModel = + | (string & {}) + | ChatModel + | 'o1-pro' + | 'o1-pro-2025-03-19' + | 'o3-pro' + | 'o3-pro-2025-06-10' + | 'o3-deep-research' + | 'o3-deep-research-2025-06-26' + | 'o4-mini-deep-research' + | 'o4-mini-deep-research-2025-06-26' + | 'computer-use-preview' + | 'computer-use-preview-2025-03-11'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/uploads.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/uploads.ts new file mode 100644 index 0000000000000000000000000000000000000000..a6ab87fbeeb3b9cca2e593fb305d0dfb77e66452 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/uploads.ts @@ -0,0 +1,3 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export * from './uploads/index'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/uploads/index.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/uploads/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..200d3567ecf4573349603e494e7d45f94174c7fa --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/uploads/index.ts @@ -0,0 +1,4 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export { Parts, type UploadPart, type PartCreateParams } from './parts'; +export { Uploads, type Upload, type UploadCreateParams, type UploadCompleteParams } from './uploads'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/uploads/parts.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/uploads/parts.ts new file mode 100644 index 0000000000000000000000000000000000000000..4e3509f9f91b139180fef829bd77bb38b6ea3a7a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/uploads/parts.ts @@ -0,0 +1,66 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../core/resource'; +import { APIPromise } from '../../core/api-promise'; +import { type Uploadable } from '../../core/uploads'; +import { RequestOptions } from '../../internal/request-options'; +import { multipartFormRequestOptions } from '../../internal/uploads'; +import { path } from '../../internal/utils/path'; + +export class Parts extends APIResource { + /** + * Adds a + * [Part](https://platform.openai.com/docs/api-reference/uploads/part-object) to an + * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object. + * A Part represents a chunk of bytes from the file you are trying to upload. + * + * Each Part can be at most 64 MB, and you can add Parts until you hit the Upload + * maximum of 8 GB. + * + * It is possible to add multiple Parts in parallel. You can decide the intended + * order of the Parts when you + * [complete the Upload](https://platform.openai.com/docs/api-reference/uploads/complete). + */ + create(uploadID: string, body: PartCreateParams, options?: RequestOptions): APIPromise { + return this._client.post( + path`/uploads/${uploadID}/parts`, + multipartFormRequestOptions({ body, ...options }, this._client), + ); + } +} + +/** + * The upload Part represents a chunk of bytes we can add to an Upload object. + */ +export interface UploadPart { + /** + * The upload Part unique identifier, which can be referenced in API endpoints. + */ + id: string; + + /** + * The Unix timestamp (in seconds) for when the Part was created. + */ + created_at: number; + + /** + * The object type, which is always `upload.part`. + */ + object: 'upload.part'; + + /** + * The ID of the Upload object that this Part was added to. + */ + upload_id: string; +} + +export interface PartCreateParams { + /** + * The chunk of bytes for this Part. + */ + data: Uploadable; +} + +export declare namespace Parts { + export { type UploadPart as UploadPart, type PartCreateParams as PartCreateParams }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/uploads/uploads.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/uploads/uploads.ts new file mode 100644 index 0000000000000000000000000000000000000000..537f6257cb27bfa3c7863d058f169b734b584710 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/uploads/uploads.ts @@ -0,0 +1,195 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../core/resource'; +import * as FilesAPI from '../files'; +import * as PartsAPI from './parts'; +import { PartCreateParams, Parts, UploadPart } from './parts'; +import { APIPromise } from '../../core/api-promise'; +import { RequestOptions } from '../../internal/request-options'; +import { path } from '../../internal/utils/path'; + +export class Uploads extends APIResource { + parts: PartsAPI.Parts = new PartsAPI.Parts(this._client); + + /** + * Creates an intermediate + * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object + * that you can add + * [Parts](https://platform.openai.com/docs/api-reference/uploads/part-object) to. + * Currently, an Upload can accept at most 8 GB in total and expires after an hour + * after you create it. + * + * Once you complete the Upload, we will create a + * [File](https://platform.openai.com/docs/api-reference/files/object) object that + * contains all the parts you uploaded. This File is usable in the rest of our + * platform as a regular File object. + * + * For certain `purpose` values, the correct `mime_type` must be specified. Please + * refer to documentation for the + * [supported MIME types for your use case](https://platform.openai.com/docs/assistants/tools/file-search#supported-files). + * + * For guidance on the proper filename extensions for each purpose, please follow + * the documentation on + * [creating a File](https://platform.openai.com/docs/api-reference/files/create). + */ + create(body: UploadCreateParams, options?: RequestOptions): APIPromise { + return this._client.post('/uploads', { body, ...options }); + } + + /** + * Cancels the Upload. No Parts may be added after an Upload is cancelled. + */ + cancel(uploadID: string, options?: RequestOptions): APIPromise { + return this._client.post(path`/uploads/${uploadID}/cancel`, options); + } + + /** + * Completes the + * [Upload](https://platform.openai.com/docs/api-reference/uploads/object). + * + * Within the returned Upload object, there is a nested + * [File](https://platform.openai.com/docs/api-reference/files/object) object that + * is ready to use in the rest of the platform. + * + * You can specify the order of the Parts by passing in an ordered list of the Part + * IDs. + * + * The number of bytes uploaded upon completion must match the number of bytes + * initially specified when creating the Upload object. No Parts may be added after + * an Upload is completed. + */ + complete(uploadID: string, body: UploadCompleteParams, options?: RequestOptions): APIPromise { + return this._client.post(path`/uploads/${uploadID}/complete`, { body, ...options }); + } +} + +/** + * The Upload object can accept byte chunks in the form of Parts. + */ +export interface Upload { + /** + * The Upload unique identifier, which can be referenced in API endpoints. + */ + id: string; + + /** + * The intended number of bytes to be uploaded. + */ + bytes: number; + + /** + * The Unix timestamp (in seconds) for when the Upload was created. + */ + created_at: number; + + /** + * The Unix timestamp (in seconds) for when the Upload will expire. + */ + expires_at: number; + + /** + * The name of the file to be uploaded. + */ + filename: string; + + /** + * The object type, which is always "upload". + */ + object: 'upload'; + + /** + * The intended purpose of the file. + * [Please refer here](https://platform.openai.com/docs/api-reference/files/object#files/object-purpose) + * for acceptable values. + */ + purpose: string; + + /** + * The status of the Upload. + */ + status: 'pending' | 'completed' | 'cancelled' | 'expired'; + + /** + * The `File` object represents a document that has been uploaded to OpenAI. + */ + file?: FilesAPI.FileObject | null; +} + +export interface UploadCreateParams { + /** + * The number of bytes in the file you are uploading. + */ + bytes: number; + + /** + * The name of the file to upload. + */ + filename: string; + + /** + * The MIME type of the file. + * + * This must fall within the supported MIME types for your file purpose. See the + * supported MIME types for assistants and vision. + */ + mime_type: string; + + /** + * The intended purpose of the uploaded file. + * + * See the + * [documentation on File purposes](https://platform.openai.com/docs/api-reference/files/create#files-create-purpose). + */ + purpose: FilesAPI.FilePurpose; + + /** + * The expiration policy for a file. By default, files with `purpose=batch` expire + * after 30 days and all other files are persisted until they are manually deleted. + */ + expires_after?: UploadCreateParams.ExpiresAfter; +} + +export namespace UploadCreateParams { + /** + * The expiration policy for a file. By default, files with `purpose=batch` expire + * after 30 days and all other files are persisted until they are manually deleted. + */ + export interface ExpiresAfter { + /** + * Anchor timestamp after which the expiration policy applies. Supported anchors: + * `created_at`. + */ + anchor: 'created_at'; + + /** + * The number of seconds after the anchor time that the file will expire. Must be + * between 3600 (1 hour) and 2592000 (30 days). + */ + seconds: number; + } +} + +export interface UploadCompleteParams { + /** + * The ordered list of Part IDs. + */ + part_ids: Array; + + /** + * The optional md5 checksum for the file contents to verify if the bytes uploaded + * matches what you expect. + */ + md5?: string; +} + +Uploads.Parts = Parts; + +export declare namespace Uploads { + export { + type Upload as Upload, + type UploadCreateParams as UploadCreateParams, + type UploadCompleteParams as UploadCompleteParams, + }; + + export { Parts as Parts, type UploadPart as UploadPart, type PartCreateParams as PartCreateParams }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/vector-stores.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/vector-stores.ts new file mode 100644 index 0000000000000000000000000000000000000000..e7a343120649ece60aadbd753db3a236ec29f6fd --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/vector-stores.ts @@ -0,0 +1,3 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export * from './vector-stores/index'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/vector-stores/file-batches.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/vector-stores/file-batches.ts new file mode 100644 index 0000000000000000000000000000000000000000..75b69b62f314f11f1dda2fbaa1b5102f70974582 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/vector-stores/file-batches.ts @@ -0,0 +1,332 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../core/resource'; +import * as FilesAPI from './files'; +import { VectorStoreFilesPage } from './files'; +import * as VectorStoresAPI from './vector-stores'; +import { APIPromise } from '../../core/api-promise'; +import { CursorPage, type CursorPageParams, PagePromise } from '../../core/pagination'; +import { buildHeaders } from '../../internal/headers'; +import { RequestOptions } from '../../internal/request-options'; +import { sleep } from '../../internal/utils/sleep'; +import { type Uploadable } from '../../uploads'; +import { allSettledWithThrow } from '../../lib/Util'; +import { path } from '../../internal/utils/path'; + +export class FileBatches extends APIResource { + /** + * Create a vector store file batch. + */ + create( + vectorStoreID: string, + body: FileBatchCreateParams, + options?: RequestOptions, + ): APIPromise { + return this._client.post(path`/vector_stores/${vectorStoreID}/file_batches`, { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + + /** + * Retrieves a vector store file batch. + */ + retrieve( + batchID: string, + params: FileBatchRetrieveParams, + options?: RequestOptions, + ): APIPromise { + const { vector_store_id } = params; + return this._client.get(path`/vector_stores/${vector_store_id}/file_batches/${batchID}`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + + /** + * Cancel a vector store file batch. This attempts to cancel the processing of + * files in this batch as soon as possible. + */ + cancel( + batchID: string, + params: FileBatchCancelParams, + options?: RequestOptions, + ): APIPromise { + const { vector_store_id } = params; + return this._client.post(path`/vector_stores/${vector_store_id}/file_batches/${batchID}/cancel`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + + /** + * Create a vector store batch and poll until all files have been processed. + */ + async createAndPoll( + vectorStoreId: string, + body: FileBatchCreateParams, + options?: RequestOptions & { pollIntervalMs?: number }, + ): Promise { + const batch = await this.create(vectorStoreId, body); + return await this.poll(vectorStoreId, batch.id, options); + } + + /** + * Returns a list of vector store files in a batch. + */ + listFiles( + batchID: string, + params: FileBatchListFilesParams, + options?: RequestOptions, + ): PagePromise { + const { vector_store_id, ...query } = params; + return this._client.getAPIList( + path`/vector_stores/${vector_store_id}/file_batches/${batchID}/files`, + CursorPage, + { query, ...options, headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]) }, + ); + } + + /** + * Wait for the given file batch to be processed. + * + * Note: this will return even if one of the files failed to process, you need to + * check batch.file_counts.failed_count to handle this case. + */ + async poll( + vectorStoreID: string, + batchID: string, + options?: RequestOptions & { pollIntervalMs?: number }, + ): Promise { + const headers = buildHeaders([ + options?.headers, + { + 'X-Stainless-Poll-Helper': 'true', + 'X-Stainless-Custom-Poll-Interval': options?.pollIntervalMs?.toString() ?? undefined, + }, + ]); + + while (true) { + const { data: batch, response } = await this.retrieve( + batchID, + { vector_store_id: vectorStoreID }, + { + ...options, + headers, + }, + ).withResponse(); + + switch (batch.status) { + case 'in_progress': + let sleepInterval = 5000; + + if (options?.pollIntervalMs) { + sleepInterval = options.pollIntervalMs; + } else { + const headerInterval = response.headers.get('openai-poll-after-ms'); + if (headerInterval) { + const headerIntervalMs = parseInt(headerInterval); + if (!isNaN(headerIntervalMs)) { + sleepInterval = headerIntervalMs; + } + } + } + await sleep(sleepInterval); + break; + case 'failed': + case 'cancelled': + case 'completed': + return batch; + } + } + } + + /** + * Uploads the given files concurrently and then creates a vector store file batch. + * + * The concurrency limit is configurable using the `maxConcurrency` parameter. + */ + async uploadAndPoll( + vectorStoreId: string, + { files, fileIds = [] }: { files: Uploadable[]; fileIds?: string[] }, + options?: RequestOptions & { pollIntervalMs?: number; maxConcurrency?: number }, + ): Promise { + if (files == null || files.length == 0) { + throw new Error( + `No \`files\` provided to process. If you've already uploaded files you should use \`.createAndPoll()\` instead`, + ); + } + + const configuredConcurrency = options?.maxConcurrency ?? 5; + + // We cap the number of workers at the number of files (so we don't start any unnecessary workers) + const concurrencyLimit = Math.min(configuredConcurrency, files.length); + + const client = this._client; + const fileIterator = files.values(); + const allFileIds: string[] = [...fileIds]; + + // This code is based on this design. The libraries don't accommodate our environment limits. + // https://stackoverflow.com/questions/40639432/what-is-the-best-way-to-limit-concurrency-when-using-es6s-promise-all + async function processFiles(iterator: IterableIterator) { + for (let item of iterator) { + const fileObj = await client.files.create({ file: item, purpose: 'assistants' }, options); + allFileIds.push(fileObj.id); + } + } + + // Start workers to process results + const workers = Array(concurrencyLimit).fill(fileIterator).map(processFiles); + + // Wait for all processing to complete. + await allSettledWithThrow(workers); + + return await this.createAndPoll(vectorStoreId, { + file_ids: allFileIds, + }); + } +} + +/** + * A batch of files attached to a vector store. + */ +export interface VectorStoreFileBatch { + /** + * The identifier, which can be referenced in API endpoints. + */ + id: string; + + /** + * The Unix timestamp (in seconds) for when the vector store files batch was + * created. + */ + created_at: number; + + file_counts: VectorStoreFileBatch.FileCounts; + + /** + * The object type, which is always `vector_store.file_batch`. + */ + object: 'vector_store.files_batch'; + + /** + * The status of the vector store files batch, which can be either `in_progress`, + * `completed`, `cancelled` or `failed`. + */ + status: 'in_progress' | 'completed' | 'cancelled' | 'failed'; + + /** + * The ID of the + * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) + * that the [File](https://platform.openai.com/docs/api-reference/files) is + * attached to. + */ + vector_store_id: string; +} + +export namespace VectorStoreFileBatch { + export interface FileCounts { + /** + * The number of files that where cancelled. + */ + cancelled: number; + + /** + * The number of files that have been processed. + */ + completed: number; + + /** + * The number of files that have failed to process. + */ + failed: number; + + /** + * The number of files that are currently being processed. + */ + in_progress: number; + + /** + * The total number of files. + */ + total: number; + } +} + +export interface FileBatchCreateParams { + /** + * A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that + * the vector store should use. Useful for tools like `file_search` that can access + * files. + */ + file_ids: Array; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. Keys are strings with a maximum + * length of 64 characters. Values are strings with a maximum length of 512 + * characters, booleans, or numbers. + */ + attributes?: { [key: string]: string | number | boolean } | null; + + /** + * The chunking strategy used to chunk the file(s). If not set, will use the `auto` + * strategy. Only applicable if `file_ids` is non-empty. + */ + chunking_strategy?: VectorStoresAPI.FileChunkingStrategyParam; +} + +export interface FileBatchRetrieveParams { + /** + * The ID of the vector store that the file batch belongs to. + */ + vector_store_id: string; +} + +export interface FileBatchCancelParams { + /** + * The ID of the vector store that the file batch belongs to. + */ + vector_store_id: string; +} + +export interface FileBatchListFilesParams extends CursorPageParams { + /** + * Path param: The ID of the vector store that the files belong to. + */ + vector_store_id: string; + + /** + * Query param: A cursor for use in pagination. `before` is an object ID that + * defines your place in the list. For instance, if you make a list request and + * receive 100 objects, starting with obj_foo, your subsequent call can include + * before=obj_foo in order to fetch the previous page of the list. + */ + before?: string; + + /** + * Query param: Filter by file status. One of `in_progress`, `completed`, `failed`, + * `cancelled`. + */ + filter?: 'in_progress' | 'completed' | 'failed' | 'cancelled'; + + /** + * Query param: Sort order by the `created_at` timestamp of the objects. `asc` for + * ascending order and `desc` for descending order. + */ + order?: 'asc' | 'desc'; +} + +export declare namespace FileBatches { + export { + type VectorStoreFileBatch as VectorStoreFileBatch, + type FileBatchCreateParams as FileBatchCreateParams, + type FileBatchRetrieveParams as FileBatchRetrieveParams, + type FileBatchCancelParams as FileBatchCancelParams, + type FileBatchListFilesParams as FileBatchListFilesParams, + }; +} + +export { type VectorStoreFilesPage }; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/vector-stores/files.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/vector-stores/files.ts new file mode 100644 index 0000000000000000000000000000000000000000..d0cad22c4559baedcab72dc35f6cb4c40071c18f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/vector-stores/files.ts @@ -0,0 +1,394 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../core/resource'; +import * as VectorStoresAPI from './vector-stores'; +import { APIPromise } from '../../core/api-promise'; +import { CursorPage, type CursorPageParams, PagePromise, Page } from '../../core/pagination'; +import { buildHeaders } from '../../internal/headers'; +import { RequestOptions } from '../../internal/request-options'; +import { sleep } from '../../internal/utils'; +import { Uploadable } from '../../uploads'; +import { path } from '../../internal/utils/path'; + +export class Files extends APIResource { + /** + * Create a vector store file by attaching a + * [File](https://platform.openai.com/docs/api-reference/files) to a + * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object). + */ + create( + vectorStoreID: string, + body: FileCreateParams, + options?: RequestOptions, + ): APIPromise { + return this._client.post(path`/vector_stores/${vectorStoreID}/files`, { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + + /** + * Retrieves a vector store file. + */ + retrieve( + fileID: string, + params: FileRetrieveParams, + options?: RequestOptions, + ): APIPromise { + const { vector_store_id } = params; + return this._client.get(path`/vector_stores/${vector_store_id}/files/${fileID}`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + + /** + * Update attributes on a vector store file. + */ + update(fileID: string, params: FileUpdateParams, options?: RequestOptions): APIPromise { + const { vector_store_id, ...body } = params; + return this._client.post(path`/vector_stores/${vector_store_id}/files/${fileID}`, { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + + /** + * Returns a list of vector store files. + */ + list( + vectorStoreID: string, + query: FileListParams | null | undefined = {}, + options?: RequestOptions, + ): PagePromise { + return this._client.getAPIList(path`/vector_stores/${vectorStoreID}/files`, CursorPage, { + query, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + + /** + * Delete a vector store file. This will remove the file from the vector store but + * the file itself will not be deleted. To delete the file, use the + * [delete file](https://platform.openai.com/docs/api-reference/files/delete) + * endpoint. + */ + delete( + fileID: string, + params: FileDeleteParams, + options?: RequestOptions, + ): APIPromise { + const { vector_store_id } = params; + return this._client.delete(path`/vector_stores/${vector_store_id}/files/${fileID}`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + + /** + * Attach a file to the given vector store and wait for it to be processed. + */ + async createAndPoll( + vectorStoreId: string, + body: FileCreateParams, + options?: RequestOptions & { pollIntervalMs?: number }, + ): Promise { + const file = await this.create(vectorStoreId, body, options); + return await this.poll(vectorStoreId, file.id, options); + } + /** + * Wait for the vector store file to finish processing. + * + * Note: this will return even if the file failed to process, you need to check + * file.last_error and file.status to handle these cases + */ + async poll( + vectorStoreID: string, + fileID: string, + options?: RequestOptions & { pollIntervalMs?: number }, + ): Promise { + const headers = buildHeaders([ + options?.headers, + { + 'X-Stainless-Poll-Helper': 'true', + 'X-Stainless-Custom-Poll-Interval': options?.pollIntervalMs?.toString() ?? undefined, + }, + ]); + + while (true) { + const fileResponse = await this.retrieve( + fileID, + { + vector_store_id: vectorStoreID, + }, + { ...options, headers }, + ).withResponse(); + + const file = fileResponse.data; + + switch (file.status) { + case 'in_progress': + let sleepInterval = 5000; + + if (options?.pollIntervalMs) { + sleepInterval = options.pollIntervalMs; + } else { + const headerInterval = fileResponse.response.headers.get('openai-poll-after-ms'); + if (headerInterval) { + const headerIntervalMs = parseInt(headerInterval); + if (!isNaN(headerIntervalMs)) { + sleepInterval = headerIntervalMs; + } + } + } + await sleep(sleepInterval); + break; + case 'failed': + case 'completed': + return file; + } + } + } + /** + * Upload a file to the `files` API and then attach it to the given vector store. + * + * Note the file will be asynchronously processed (you can use the alternative + * polling helper method to wait for processing to complete). + */ + async upload(vectorStoreId: string, file: Uploadable, options?: RequestOptions): Promise { + const fileInfo = await this._client.files.create({ file: file, purpose: 'assistants' }, options); + return this.create(vectorStoreId, { file_id: fileInfo.id }, options); + } + /** + * Add a file to a vector store and poll until processing is complete. + */ + async uploadAndPoll( + vectorStoreId: string, + file: Uploadable, + options?: RequestOptions & { pollIntervalMs?: number }, + ): Promise { + const fileInfo = await this.upload(vectorStoreId, file, options); + return await this.poll(vectorStoreId, fileInfo.id, options); + } + + /** + * Retrieve the parsed contents of a vector store file. + */ + content( + fileID: string, + params: FileContentParams, + options?: RequestOptions, + ): PagePromise { + const { vector_store_id } = params; + return this._client.getAPIList( + path`/vector_stores/${vector_store_id}/files/${fileID}/content`, + Page, + { ...options, headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]) }, + ); + } +} + +export type VectorStoreFilesPage = CursorPage; + +// Note: no pagination actually occurs yet, this is for forwards-compatibility. +export type FileContentResponsesPage = Page; + +/** + * A list of files attached to a vector store. + */ +export interface VectorStoreFile { + /** + * The identifier, which can be referenced in API endpoints. + */ + id: string; + + /** + * The Unix timestamp (in seconds) for when the vector store file was created. + */ + created_at: number; + + /** + * The last error associated with this vector store file. Will be `null` if there + * are no errors. + */ + last_error: VectorStoreFile.LastError | null; + + /** + * The object type, which is always `vector_store.file`. + */ + object: 'vector_store.file'; + + /** + * The status of the vector store file, which can be either `in_progress`, + * `completed`, `cancelled`, or `failed`. The status `completed` indicates that the + * vector store file is ready for use. + */ + status: 'in_progress' | 'completed' | 'cancelled' | 'failed'; + + /** + * The total vector store usage in bytes. Note that this may be different from the + * original file size. + */ + usage_bytes: number; + + /** + * The ID of the + * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) + * that the [File](https://platform.openai.com/docs/api-reference/files) is + * attached to. + */ + vector_store_id: string; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. Keys are strings with a maximum + * length of 64 characters. Values are strings with a maximum length of 512 + * characters, booleans, or numbers. + */ + attributes?: { [key: string]: string | number | boolean } | null; + + /** + * The strategy used to chunk the file. + */ + chunking_strategy?: VectorStoresAPI.FileChunkingStrategy; +} + +export namespace VectorStoreFile { + /** + * The last error associated with this vector store file. Will be `null` if there + * are no errors. + */ + export interface LastError { + /** + * One of `server_error` or `rate_limit_exceeded`. + */ + code: 'server_error' | 'unsupported_file' | 'invalid_file'; + + /** + * A human-readable description of the error. + */ + message: string; + } +} + +export interface VectorStoreFileDeleted { + id: string; + + deleted: boolean; + + object: 'vector_store.file.deleted'; +} + +export interface FileContentResponse { + /** + * The text content + */ + text?: string; + + /** + * The content type (currently only `"text"`) + */ + type?: string; +} + +export interface FileCreateParams { + /** + * A [File](https://platform.openai.com/docs/api-reference/files) ID that the + * vector store should use. Useful for tools like `file_search` that can access + * files. + */ + file_id: string; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. Keys are strings with a maximum + * length of 64 characters. Values are strings with a maximum length of 512 + * characters, booleans, or numbers. + */ + attributes?: { [key: string]: string | number | boolean } | null; + + /** + * The chunking strategy used to chunk the file(s). If not set, will use the `auto` + * strategy. Only applicable if `file_ids` is non-empty. + */ + chunking_strategy?: VectorStoresAPI.FileChunkingStrategyParam; +} + +export interface FileRetrieveParams { + /** + * The ID of the vector store that the file belongs to. + */ + vector_store_id: string; +} + +export interface FileUpdateParams { + /** + * Path param: The ID of the vector store the file belongs to. + */ + vector_store_id: string; + + /** + * Body param: Set of 16 key-value pairs that can be attached to an object. This + * can be useful for storing additional information about the object in a + * structured format, and querying for objects via API or the dashboard. Keys are + * strings with a maximum length of 64 characters. Values are strings with a + * maximum length of 512 characters, booleans, or numbers. + */ + attributes: { [key: string]: string | number | boolean } | null; +} + +export interface FileListParams extends CursorPageParams { + /** + * A cursor for use in pagination. `before` is an object ID that defines your place + * in the list. For instance, if you make a list request and receive 100 objects, + * starting with obj_foo, your subsequent call can include before=obj_foo in order + * to fetch the previous page of the list. + */ + before?: string; + + /** + * Filter by file status. One of `in_progress`, `completed`, `failed`, `cancelled`. + */ + filter?: 'in_progress' | 'completed' | 'failed' | 'cancelled'; + + /** + * Sort order by the `created_at` timestamp of the objects. `asc` for ascending + * order and `desc` for descending order. + */ + order?: 'asc' | 'desc'; +} + +export interface FileDeleteParams { + /** + * The ID of the vector store that the file belongs to. + */ + vector_store_id: string; +} + +export interface FileContentParams { + /** + * The ID of the vector store. + */ + vector_store_id: string; +} + +export declare namespace Files { + export { + type VectorStoreFile as VectorStoreFile, + type VectorStoreFileDeleted as VectorStoreFileDeleted, + type FileContentResponse as FileContentResponse, + type VectorStoreFilesPage as VectorStoreFilesPage, + type FileContentResponsesPage as FileContentResponsesPage, + type FileCreateParams as FileCreateParams, + type FileRetrieveParams as FileRetrieveParams, + type FileUpdateParams as FileUpdateParams, + type FileListParams as FileListParams, + type FileDeleteParams as FileDeleteParams, + type FileContentParams as FileContentParams, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/vector-stores/index.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/vector-stores/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..cbcb3622109bb3717330f7f34e50f35a032d8a8c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/vector-stores/index.ts @@ -0,0 +1,43 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export { + FileBatches, + type VectorStoreFileBatch, + type FileBatchCreateParams, + type FileBatchRetrieveParams, + type FileBatchCancelParams, + type FileBatchListFilesParams, +} from './file-batches'; +export { + Files, + type VectorStoreFile, + type VectorStoreFileDeleted, + type FileContentResponse, + type FileCreateParams, + type FileRetrieveParams, + type FileUpdateParams, + type FileListParams, + type FileDeleteParams, + type FileContentParams, + type VectorStoreFilesPage, + type FileContentResponsesPage, +} from './files'; +export { + VectorStores, + type AutoFileChunkingStrategyParam, + type FileChunkingStrategy, + type FileChunkingStrategyParam, + type OtherFileChunkingStrategyObject, + type StaticFileChunkingStrategy, + type StaticFileChunkingStrategyObject, + type StaticFileChunkingStrategyObjectParam, + type VectorStore, + type VectorStoreDeleted, + type VectorStoreSearchResponse, + type VectorStoreCreateParams, + type VectorStoreUpdateParams, + type VectorStoreListParams, + type VectorStoreSearchParams, + type VectorStoresPage, + type VectorStoreSearchResponsesPage, +} from './vector-stores'; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/vector-stores/vector-stores.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/vector-stores/vector-stores.ts new file mode 100644 index 0000000000000000000000000000000000000000..4026c0f1556fed7483cd837e36936f98b043b354 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/vector-stores/vector-stores.ts @@ -0,0 +1,556 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { APIResource } from '../../core/resource'; +import * as Shared from '../shared'; +import * as FileBatchesAPI from './file-batches'; +import { + FileBatchCancelParams, + FileBatchCreateParams, + FileBatchListFilesParams, + FileBatchRetrieveParams, + FileBatches, + VectorStoreFileBatch, +} from './file-batches'; +import * as FilesAPI from './files'; +import { + FileContentParams, + FileContentResponse, + FileContentResponsesPage, + FileCreateParams, + FileDeleteParams, + FileListParams, + FileRetrieveParams, + FileUpdateParams, + Files, + VectorStoreFile, + VectorStoreFileDeleted, + VectorStoreFilesPage, +} from './files'; +import { APIPromise } from '../../core/api-promise'; +import { CursorPage, type CursorPageParams, Page, PagePromise } from '../../core/pagination'; +import { buildHeaders } from '../../internal/headers'; +import { RequestOptions } from '../../internal/request-options'; +import { path } from '../../internal/utils/path'; + +export class VectorStores extends APIResource { + files: FilesAPI.Files = new FilesAPI.Files(this._client); + fileBatches: FileBatchesAPI.FileBatches = new FileBatchesAPI.FileBatches(this._client); + + /** + * Create a vector store. + */ + create(body: VectorStoreCreateParams, options?: RequestOptions): APIPromise { + return this._client.post('/vector_stores', { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + + /** + * Retrieves a vector store. + */ + retrieve(vectorStoreID: string, options?: RequestOptions): APIPromise { + return this._client.get(path`/vector_stores/${vectorStoreID}`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + + /** + * Modifies a vector store. + */ + update( + vectorStoreID: string, + body: VectorStoreUpdateParams, + options?: RequestOptions, + ): APIPromise { + return this._client.post(path`/vector_stores/${vectorStoreID}`, { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + + /** + * Returns a list of vector stores. + */ + list( + query: VectorStoreListParams | null | undefined = {}, + options?: RequestOptions, + ): PagePromise { + return this._client.getAPIList('/vector_stores', CursorPage, { + query, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + + /** + * Delete a vector store. + */ + delete(vectorStoreID: string, options?: RequestOptions): APIPromise { + return this._client.delete(path`/vector_stores/${vectorStoreID}`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + + /** + * Search a vector store for relevant chunks based on a query and file attributes + * filter. + */ + search( + vectorStoreID: string, + body: VectorStoreSearchParams, + options?: RequestOptions, + ): PagePromise { + return this._client.getAPIList( + path`/vector_stores/${vectorStoreID}/search`, + Page, + { + body, + method: 'post', + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }, + ); + } +} + +export type VectorStoresPage = CursorPage; + +// Note: no pagination actually occurs yet, this is for forwards-compatibility. +export type VectorStoreSearchResponsesPage = Page; + +/** + * The default strategy. This strategy currently uses a `max_chunk_size_tokens` of + * `800` and `chunk_overlap_tokens` of `400`. + */ +export interface AutoFileChunkingStrategyParam { + /** + * Always `auto`. + */ + type: 'auto'; +} + +/** + * The strategy used to chunk the file. + */ +export type FileChunkingStrategy = StaticFileChunkingStrategyObject | OtherFileChunkingStrategyObject; + +/** + * The chunking strategy used to chunk the file(s). If not set, will use the `auto` + * strategy. Only applicable if `file_ids` is non-empty. + */ +export type FileChunkingStrategyParam = AutoFileChunkingStrategyParam | StaticFileChunkingStrategyObjectParam; + +/** + * This is returned when the chunking strategy is unknown. Typically, this is + * because the file was indexed before the `chunking_strategy` concept was + * introduced in the API. + */ +export interface OtherFileChunkingStrategyObject { + /** + * Always `other`. + */ + type: 'other'; +} + +export interface StaticFileChunkingStrategy { + /** + * The number of tokens that overlap between chunks. The default value is `400`. + * + * Note that the overlap must not exceed half of `max_chunk_size_tokens`. + */ + chunk_overlap_tokens: number; + + /** + * The maximum number of tokens in each chunk. The default value is `800`. The + * minimum value is `100` and the maximum value is `4096`. + */ + max_chunk_size_tokens: number; +} + +export interface StaticFileChunkingStrategyObject { + static: StaticFileChunkingStrategy; + + /** + * Always `static`. + */ + type: 'static'; +} + +/** + * Customize your own chunking strategy by setting chunk size and chunk overlap. + */ +export interface StaticFileChunkingStrategyObjectParam { + static: StaticFileChunkingStrategy; + + /** + * Always `static`. + */ + type: 'static'; +} + +/** + * A vector store is a collection of processed files can be used by the + * `file_search` tool. + */ +export interface VectorStore { + /** + * The identifier, which can be referenced in API endpoints. + */ + id: string; + + /** + * The Unix timestamp (in seconds) for when the vector store was created. + */ + created_at: number; + + file_counts: VectorStore.FileCounts; + + /** + * The Unix timestamp (in seconds) for when the vector store was last active. + */ + last_active_at: number | null; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata: Shared.Metadata | null; + + /** + * The name of the vector store. + */ + name: string; + + /** + * The object type, which is always `vector_store`. + */ + object: 'vector_store'; + + /** + * The status of the vector store, which can be either `expired`, `in_progress`, or + * `completed`. A status of `completed` indicates that the vector store is ready + * for use. + */ + status: 'expired' | 'in_progress' | 'completed'; + + /** + * The total number of bytes used by the files in the vector store. + */ + usage_bytes: number; + + /** + * The expiration policy for a vector store. + */ + expires_after?: VectorStore.ExpiresAfter; + + /** + * The Unix timestamp (in seconds) for when the vector store will expire. + */ + expires_at?: number | null; +} + +export namespace VectorStore { + export interface FileCounts { + /** + * The number of files that were cancelled. + */ + cancelled: number; + + /** + * The number of files that have been successfully processed. + */ + completed: number; + + /** + * The number of files that have failed to process. + */ + failed: number; + + /** + * The number of files that are currently being processed. + */ + in_progress: number; + + /** + * The total number of files. + */ + total: number; + } + + /** + * The expiration policy for a vector store. + */ + export interface ExpiresAfter { + /** + * Anchor timestamp after which the expiration policy applies. Supported anchors: + * `last_active_at`. + */ + anchor: 'last_active_at'; + + /** + * The number of days after the anchor time that the vector store will expire. + */ + days: number; + } +} + +export interface VectorStoreDeleted { + id: string; + + deleted: boolean; + + object: 'vector_store.deleted'; +} + +export interface VectorStoreSearchResponse { + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. Keys are strings with a maximum + * length of 64 characters. Values are strings with a maximum length of 512 + * characters, booleans, or numbers. + */ + attributes: { [key: string]: string | number | boolean } | null; + + /** + * Content chunks from the file. + */ + content: Array; + + /** + * The ID of the vector store file. + */ + file_id: string; + + /** + * The name of the vector store file. + */ + filename: string; + + /** + * The similarity score for the result. + */ + score: number; +} + +export namespace VectorStoreSearchResponse { + export interface Content { + /** + * The text content returned from search. + */ + text: string; + + /** + * The type of content. + */ + type: 'text'; + } +} + +export interface VectorStoreCreateParams { + /** + * The chunking strategy used to chunk the file(s). If not set, will use the `auto` + * strategy. Only applicable if `file_ids` is non-empty. + */ + chunking_strategy?: FileChunkingStrategyParam; + + /** + * The expiration policy for a vector store. + */ + expires_after?: VectorStoreCreateParams.ExpiresAfter; + + /** + * A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that + * the vector store should use. Useful for tools like `file_search` that can access + * files. + */ + file_ids?: Array; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; + + /** + * The name of the vector store. + */ + name?: string; +} + +export namespace VectorStoreCreateParams { + /** + * The expiration policy for a vector store. + */ + export interface ExpiresAfter { + /** + * Anchor timestamp after which the expiration policy applies. Supported anchors: + * `last_active_at`. + */ + anchor: 'last_active_at'; + + /** + * The number of days after the anchor time that the vector store will expire. + */ + days: number; + } +} + +export interface VectorStoreUpdateParams { + /** + * The expiration policy for a vector store. + */ + expires_after?: VectorStoreUpdateParams.ExpiresAfter | null; + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful + * for storing additional information about the object in a structured format, and + * querying for objects via API or the dashboard. + * + * Keys are strings with a maximum length of 64 characters. Values are strings with + * a maximum length of 512 characters. + */ + metadata?: Shared.Metadata | null; + + /** + * The name of the vector store. + */ + name?: string | null; +} + +export namespace VectorStoreUpdateParams { + /** + * The expiration policy for a vector store. + */ + export interface ExpiresAfter { + /** + * Anchor timestamp after which the expiration policy applies. Supported anchors: + * `last_active_at`. + */ + anchor: 'last_active_at'; + + /** + * The number of days after the anchor time that the vector store will expire. + */ + days: number; + } +} + +export interface VectorStoreListParams extends CursorPageParams { + /** + * A cursor for use in pagination. `before` is an object ID that defines your place + * in the list. For instance, if you make a list request and receive 100 objects, + * starting with obj_foo, your subsequent call can include before=obj_foo in order + * to fetch the previous page of the list. + */ + before?: string; + + /** + * Sort order by the `created_at` timestamp of the objects. `asc` for ascending + * order and `desc` for descending order. + */ + order?: 'asc' | 'desc'; +} + +export interface VectorStoreSearchParams { + /** + * A query string for a search + */ + query: string | Array; + + /** + * A filter to apply based on file attributes. + */ + filters?: Shared.ComparisonFilter | Shared.CompoundFilter; + + /** + * The maximum number of results to return. This number should be between 1 and 50 + * inclusive. + */ + max_num_results?: number; + + /** + * Ranking options for search. + */ + ranking_options?: VectorStoreSearchParams.RankingOptions; + + /** + * Whether to rewrite the natural language query for vector search. + */ + rewrite_query?: boolean; +} + +export namespace VectorStoreSearchParams { + /** + * Ranking options for search. + */ + export interface RankingOptions { + /** + * Enable re-ranking; set to `none` to disable, which can help reduce latency. + */ + ranker?: 'none' | 'auto' | 'default-2024-11-15'; + + score_threshold?: number; + } +} + +VectorStores.Files = Files; +VectorStores.FileBatches = FileBatches; + +export declare namespace VectorStores { + export { + type AutoFileChunkingStrategyParam as AutoFileChunkingStrategyParam, + type FileChunkingStrategy as FileChunkingStrategy, + type FileChunkingStrategyParam as FileChunkingStrategyParam, + type OtherFileChunkingStrategyObject as OtherFileChunkingStrategyObject, + type StaticFileChunkingStrategy as StaticFileChunkingStrategy, + type StaticFileChunkingStrategyObject as StaticFileChunkingStrategyObject, + type StaticFileChunkingStrategyObjectParam as StaticFileChunkingStrategyObjectParam, + type VectorStore as VectorStore, + type VectorStoreDeleted as VectorStoreDeleted, + type VectorStoreSearchResponse as VectorStoreSearchResponse, + type VectorStoresPage as VectorStoresPage, + type VectorStoreSearchResponsesPage as VectorStoreSearchResponsesPage, + type VectorStoreCreateParams as VectorStoreCreateParams, + type VectorStoreUpdateParams as VectorStoreUpdateParams, + type VectorStoreListParams as VectorStoreListParams, + type VectorStoreSearchParams as VectorStoreSearchParams, + }; + + export { + Files as Files, + type VectorStoreFile as VectorStoreFile, + type VectorStoreFileDeleted as VectorStoreFileDeleted, + type FileContentResponse as FileContentResponse, + type VectorStoreFilesPage as VectorStoreFilesPage, + type FileContentResponsesPage as FileContentResponsesPage, + type FileCreateParams as FileCreateParams, + type FileRetrieveParams as FileRetrieveParams, + type FileUpdateParams as FileUpdateParams, + type FileListParams as FileListParams, + type FileDeleteParams as FileDeleteParams, + type FileContentParams as FileContentParams, + }; + + export { + FileBatches as FileBatches, + type VectorStoreFileBatch as VectorStoreFileBatch, + type FileBatchCreateParams as FileBatchCreateParams, + type FileBatchRetrieveParams as FileBatchRetrieveParams, + type FileBatchCancelParams as FileBatchCancelParams, + type FileBatchListFilesParams as FileBatchListFilesParams, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/webhooks.ts b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/webhooks.ts new file mode 100644 index 0000000000000000000000000000000000000000..fa337478b0c2ec8e4cb9846c227286700773d04d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/openai/src/resources/webhooks.ts @@ -0,0 +1,767 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { InvalidWebhookSignatureError } from '../error'; +import { APIResource } from '../core/resource'; +import { buildHeaders, HeadersLike } from '../internal/headers'; + +export class Webhooks extends APIResource { + /** + * Validates that the given payload was sent by OpenAI and parses the payload. + */ + async unwrap( + payload: string, + headers: HeadersLike, + secret: string | undefined | null = this._client.webhookSecret, + tolerance: number = 300, + ): Promise { + await this.verifySignature(payload, headers, secret, tolerance); + + return JSON.parse(payload) as UnwrapWebhookEvent; + } + + /** + * Validates whether or not the webhook payload was sent by OpenAI. + * + * An error will be raised if the webhook payload was not sent by OpenAI. + * + * @param payload - The webhook payload + * @param headers - The webhook headers + * @param secret - The webhook secret (optional, will use client secret if not provided) + * @param tolerance - Maximum age of the webhook in seconds (default: 300 = 5 minutes) + */ + async verifySignature( + payload: string, + headers: HeadersLike, + secret: string | undefined | null = this._client.webhookSecret, + tolerance: number = 300, + ): Promise { + if ( + typeof crypto === 'undefined' || + typeof crypto.subtle.importKey !== 'function' || + typeof crypto.subtle.verify !== 'function' + ) { + throw new Error('Webhook signature verification is only supported when the `crypto` global is defined'); + } + + this.#validateSecret(secret); + + const headersObj = buildHeaders([headers]).values; + const signatureHeader = this.#getRequiredHeader(headersObj, 'webhook-signature'); + const timestamp = this.#getRequiredHeader(headersObj, 'webhook-timestamp'); + const webhookId = this.#getRequiredHeader(headersObj, 'webhook-id'); + + // Validate timestamp to prevent replay attacks + const timestampSeconds = parseInt(timestamp, 10); + if (isNaN(timestampSeconds)) { + throw new InvalidWebhookSignatureError('Invalid webhook timestamp format'); + } + + const nowSeconds = Math.floor(Date.now() / 1000); + + if (nowSeconds - timestampSeconds > tolerance) { + throw new InvalidWebhookSignatureError('Webhook timestamp is too old'); + } + + if (timestampSeconds > nowSeconds + tolerance) { + throw new InvalidWebhookSignatureError('Webhook timestamp is too new'); + } + + // Extract signatures from v1, format + // The signature header can have multiple values, separated by spaces. + // Each value is in the format v1,. We should accept if any match. + const signatures = signatureHeader + .split(' ') + .map((part) => (part.startsWith('v1,') ? part.substring(3) : part)); + + // Decode the secret if it starts with whsec_ + const decodedSecret = + secret.startsWith('whsec_') ? + Buffer.from(secret.replace('whsec_', ''), 'base64') + : Buffer.from(secret, 'utf-8'); + + // Create the signed payload: {webhook_id}.{timestamp}.{payload} + const signedPayload = webhookId ? `${webhookId}.${timestamp}.${payload}` : `${timestamp}.${payload}`; + + // Import the secret as a cryptographic key for HMAC + const key = await crypto.subtle.importKey( + 'raw', + decodedSecret, + { name: 'HMAC', hash: 'SHA-256' }, + false, + ['verify'], + ); + + // Check if any signature matches using timing-safe WebCrypto verify + for (const signature of signatures) { + try { + const signatureBytes = Buffer.from(signature, 'base64'); + const isValid = await crypto.subtle.verify( + 'HMAC', + key, + signatureBytes, + new TextEncoder().encode(signedPayload), + ); + + if (isValid) { + return; // Valid signature found + } + } catch { + // Invalid base64 or signature format, continue to next signature + continue; + } + } + + throw new InvalidWebhookSignatureError( + 'The given webhook signature does not match the expected signature', + ); + } + + #validateSecret(secret: string | null | undefined): asserts secret is string { + if (typeof secret !== 'string' || secret.length === 0) { + throw new Error( + `The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function`, + ); + } + } + + #getRequiredHeader(headers: Headers, name: string): string { + if (!headers) { + throw new Error(`Headers are required`); + } + + const value = headers.get(name); + + if (value === null || value === undefined) { + throw new Error(`Missing required header: ${name}`); + } + + return value; + } +} + +/** + * Sent when a batch API request has been cancelled. + */ +export interface BatchCancelledWebhookEvent { + /** + * The unique ID of the event. + */ + id: string; + + /** + * The Unix timestamp (in seconds) of when the batch API request was cancelled. + */ + created_at: number; + + /** + * Event data payload. + */ + data: BatchCancelledWebhookEvent.Data; + + /** + * The type of the event. Always `batch.cancelled`. + */ + type: 'batch.cancelled'; + + /** + * The object of the event. Always `event`. + */ + object?: 'event'; +} + +export namespace BatchCancelledWebhookEvent { + /** + * Event data payload. + */ + export interface Data { + /** + * The unique ID of the batch API request. + */ + id: string; + } +} + +/** + * Sent when a batch API request has been completed. + */ +export interface BatchCompletedWebhookEvent { + /** + * The unique ID of the event. + */ + id: string; + + /** + * The Unix timestamp (in seconds) of when the batch API request was completed. + */ + created_at: number; + + /** + * Event data payload. + */ + data: BatchCompletedWebhookEvent.Data; + + /** + * The type of the event. Always `batch.completed`. + */ + type: 'batch.completed'; + + /** + * The object of the event. Always `event`. + */ + object?: 'event'; +} + +export namespace BatchCompletedWebhookEvent { + /** + * Event data payload. + */ + export interface Data { + /** + * The unique ID of the batch API request. + */ + id: string; + } +} + +/** + * Sent when a batch API request has expired. + */ +export interface BatchExpiredWebhookEvent { + /** + * The unique ID of the event. + */ + id: string; + + /** + * The Unix timestamp (in seconds) of when the batch API request expired. + */ + created_at: number; + + /** + * Event data payload. + */ + data: BatchExpiredWebhookEvent.Data; + + /** + * The type of the event. Always `batch.expired`. + */ + type: 'batch.expired'; + + /** + * The object of the event. Always `event`. + */ + object?: 'event'; +} + +export namespace BatchExpiredWebhookEvent { + /** + * Event data payload. + */ + export interface Data { + /** + * The unique ID of the batch API request. + */ + id: string; + } +} + +/** + * Sent when a batch API request has failed. + */ +export interface BatchFailedWebhookEvent { + /** + * The unique ID of the event. + */ + id: string; + + /** + * The Unix timestamp (in seconds) of when the batch API request failed. + */ + created_at: number; + + /** + * Event data payload. + */ + data: BatchFailedWebhookEvent.Data; + + /** + * The type of the event. Always `batch.failed`. + */ + type: 'batch.failed'; + + /** + * The object of the event. Always `event`. + */ + object?: 'event'; +} + +export namespace BatchFailedWebhookEvent { + /** + * Event data payload. + */ + export interface Data { + /** + * The unique ID of the batch API request. + */ + id: string; + } +} + +/** + * Sent when an eval run has been canceled. + */ +export interface EvalRunCanceledWebhookEvent { + /** + * The unique ID of the event. + */ + id: string; + + /** + * The Unix timestamp (in seconds) of when the eval run was canceled. + */ + created_at: number; + + /** + * Event data payload. + */ + data: EvalRunCanceledWebhookEvent.Data; + + /** + * The type of the event. Always `eval.run.canceled`. + */ + type: 'eval.run.canceled'; + + /** + * The object of the event. Always `event`. + */ + object?: 'event'; +} + +export namespace EvalRunCanceledWebhookEvent { + /** + * Event data payload. + */ + export interface Data { + /** + * The unique ID of the eval run. + */ + id: string; + } +} + +/** + * Sent when an eval run has failed. + */ +export interface EvalRunFailedWebhookEvent { + /** + * The unique ID of the event. + */ + id: string; + + /** + * The Unix timestamp (in seconds) of when the eval run failed. + */ + created_at: number; + + /** + * Event data payload. + */ + data: EvalRunFailedWebhookEvent.Data; + + /** + * The type of the event. Always `eval.run.failed`. + */ + type: 'eval.run.failed'; + + /** + * The object of the event. Always `event`. + */ + object?: 'event'; +} + +export namespace EvalRunFailedWebhookEvent { + /** + * Event data payload. + */ + export interface Data { + /** + * The unique ID of the eval run. + */ + id: string; + } +} + +/** + * Sent when an eval run has succeeded. + */ +export interface EvalRunSucceededWebhookEvent { + /** + * The unique ID of the event. + */ + id: string; + + /** + * The Unix timestamp (in seconds) of when the eval run succeeded. + */ + created_at: number; + + /** + * Event data payload. + */ + data: EvalRunSucceededWebhookEvent.Data; + + /** + * The type of the event. Always `eval.run.succeeded`. + */ + type: 'eval.run.succeeded'; + + /** + * The object of the event. Always `event`. + */ + object?: 'event'; +} + +export namespace EvalRunSucceededWebhookEvent { + /** + * Event data payload. + */ + export interface Data { + /** + * The unique ID of the eval run. + */ + id: string; + } +} + +/** + * Sent when a fine-tuning job has been cancelled. + */ +export interface FineTuningJobCancelledWebhookEvent { + /** + * The unique ID of the event. + */ + id: string; + + /** + * The Unix timestamp (in seconds) of when the fine-tuning job was cancelled. + */ + created_at: number; + + /** + * Event data payload. + */ + data: FineTuningJobCancelledWebhookEvent.Data; + + /** + * The type of the event. Always `fine_tuning.job.cancelled`. + */ + type: 'fine_tuning.job.cancelled'; + + /** + * The object of the event. Always `event`. + */ + object?: 'event'; +} + +export namespace FineTuningJobCancelledWebhookEvent { + /** + * Event data payload. + */ + export interface Data { + /** + * The unique ID of the fine-tuning job. + */ + id: string; + } +} + +/** + * Sent when a fine-tuning job has failed. + */ +export interface FineTuningJobFailedWebhookEvent { + /** + * The unique ID of the event. + */ + id: string; + + /** + * The Unix timestamp (in seconds) of when the fine-tuning job failed. + */ + created_at: number; + + /** + * Event data payload. + */ + data: FineTuningJobFailedWebhookEvent.Data; + + /** + * The type of the event. Always `fine_tuning.job.failed`. + */ + type: 'fine_tuning.job.failed'; + + /** + * The object of the event. Always `event`. + */ + object?: 'event'; +} + +export namespace FineTuningJobFailedWebhookEvent { + /** + * Event data payload. + */ + export interface Data { + /** + * The unique ID of the fine-tuning job. + */ + id: string; + } +} + +/** + * Sent when a fine-tuning job has succeeded. + */ +export interface FineTuningJobSucceededWebhookEvent { + /** + * The unique ID of the event. + */ + id: string; + + /** + * The Unix timestamp (in seconds) of when the fine-tuning job succeeded. + */ + created_at: number; + + /** + * Event data payload. + */ + data: FineTuningJobSucceededWebhookEvent.Data; + + /** + * The type of the event. Always `fine_tuning.job.succeeded`. + */ + type: 'fine_tuning.job.succeeded'; + + /** + * The object of the event. Always `event`. + */ + object?: 'event'; +} + +export namespace FineTuningJobSucceededWebhookEvent { + /** + * Event data payload. + */ + export interface Data { + /** + * The unique ID of the fine-tuning job. + */ + id: string; + } +} + +/** + * Sent when a background response has been cancelled. + */ +export interface ResponseCancelledWebhookEvent { + /** + * The unique ID of the event. + */ + id: string; + + /** + * The Unix timestamp (in seconds) of when the model response was cancelled. + */ + created_at: number; + + /** + * Event data payload. + */ + data: ResponseCancelledWebhookEvent.Data; + + /** + * The type of the event. Always `response.cancelled`. + */ + type: 'response.cancelled'; + + /** + * The object of the event. Always `event`. + */ + object?: 'event'; +} + +export namespace ResponseCancelledWebhookEvent { + /** + * Event data payload. + */ + export interface Data { + /** + * The unique ID of the model response. + */ + id: string; + } +} + +/** + * Sent when a background response has been completed. + */ +export interface ResponseCompletedWebhookEvent { + /** + * The unique ID of the event. + */ + id: string; + + /** + * The Unix timestamp (in seconds) of when the model response was completed. + */ + created_at: number; + + /** + * Event data payload. + */ + data: ResponseCompletedWebhookEvent.Data; + + /** + * The type of the event. Always `response.completed`. + */ + type: 'response.completed'; + + /** + * The object of the event. Always `event`. + */ + object?: 'event'; +} + +export namespace ResponseCompletedWebhookEvent { + /** + * Event data payload. + */ + export interface Data { + /** + * The unique ID of the model response. + */ + id: string; + } +} + +/** + * Sent when a background response has failed. + */ +export interface ResponseFailedWebhookEvent { + /** + * The unique ID of the event. + */ + id: string; + + /** + * The Unix timestamp (in seconds) of when the model response failed. + */ + created_at: number; + + /** + * Event data payload. + */ + data: ResponseFailedWebhookEvent.Data; + + /** + * The type of the event. Always `response.failed`. + */ + type: 'response.failed'; + + /** + * The object of the event. Always `event`. + */ + object?: 'event'; +} + +export namespace ResponseFailedWebhookEvent { + /** + * Event data payload. + */ + export interface Data { + /** + * The unique ID of the model response. + */ + id: string; + } +} + +/** + * Sent when a background response has been interrupted. + */ +export interface ResponseIncompleteWebhookEvent { + /** + * The unique ID of the event. + */ + id: string; + + /** + * The Unix timestamp (in seconds) of when the model response was interrupted. + */ + created_at: number; + + /** + * Event data payload. + */ + data: ResponseIncompleteWebhookEvent.Data; + + /** + * The type of the event. Always `response.incomplete`. + */ + type: 'response.incomplete'; + + /** + * The object of the event. Always `event`. + */ + object?: 'event'; +} + +export namespace ResponseIncompleteWebhookEvent { + /** + * Event data payload. + */ + export interface Data { + /** + * The unique ID of the model response. + */ + id: string; + } +} + +/** + * Sent when a batch API request has been cancelled. + */ +export type UnwrapWebhookEvent = + | BatchCancelledWebhookEvent + | BatchCompletedWebhookEvent + | BatchExpiredWebhookEvent + | BatchFailedWebhookEvent + | EvalRunCanceledWebhookEvent + | EvalRunFailedWebhookEvent + | EvalRunSucceededWebhookEvent + | FineTuningJobCancelledWebhookEvent + | FineTuningJobFailedWebhookEvent + | FineTuningJobSucceededWebhookEvent + | ResponseCancelledWebhookEvent + | ResponseCompletedWebhookEvent + | ResponseFailedWebhookEvent + | ResponseIncompleteWebhookEvent; + +export declare namespace Webhooks { + export { + type BatchCancelledWebhookEvent as BatchCancelledWebhookEvent, + type BatchCompletedWebhookEvent as BatchCompletedWebhookEvent, + type BatchExpiredWebhookEvent as BatchExpiredWebhookEvent, + type BatchFailedWebhookEvent as BatchFailedWebhookEvent, + type EvalRunCanceledWebhookEvent as EvalRunCanceledWebhookEvent, + type EvalRunFailedWebhookEvent as EvalRunFailedWebhookEvent, + type EvalRunSucceededWebhookEvent as EvalRunSucceededWebhookEvent, + type FineTuningJobCancelledWebhookEvent as FineTuningJobCancelledWebhookEvent, + type FineTuningJobFailedWebhookEvent as FineTuningJobFailedWebhookEvent, + type FineTuningJobSucceededWebhookEvent as FineTuningJobSucceededWebhookEvent, + type ResponseCancelledWebhookEvent as ResponseCancelledWebhookEvent, + type ResponseCompletedWebhookEvent as ResponseCompletedWebhookEvent, + type ResponseFailedWebhookEvent as ResponseFailedWebhookEvent, + type ResponseIncompleteWebhookEvent as ResponseIncompleteWebhookEvent, + type UnwrapWebhookEvent as UnwrapWebhookEvent, + }; +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/toad-cache/dist/toad-cache.cjs b/novas/novacore-zephyr/claude-code-router/node_modules/toad-cache/dist/toad-cache.cjs new file mode 100644 index 0000000000000000000000000000000000000000..057840996c2837de209d797b3756fd21bb8dcf63 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/toad-cache/dist/toad-cache.cjs @@ -0,0 +1,878 @@ +/** + * toad-cache + * + * @copyright 2024 Igor Savin + * @license MIT + * @version 3.7.0 + */ +'use strict'; + +class FifoMap { + constructor(max = 1000, ttlInMsecs = 0) { + if (isNaN(max) || max < 0) { + throw new Error('Invalid max value') + } + + if (isNaN(ttlInMsecs) || ttlInMsecs < 0) { + throw new Error('Invalid ttl value') + } + + this.first = null; + this.items = new Map(); + this.last = null; + this.max = max; + this.ttl = ttlInMsecs; + } + + get size() { + return this.items.size + } + + clear() { + this.items = new Map(); + this.first = null; + this.last = null; + } + + delete(key) { + if (this.items.has(key)) { + const deletedItem = this.items.get(key); + + this.items.delete(key); + + if (deletedItem.prev !== null) { + deletedItem.prev.next = deletedItem.next; + } + + if (deletedItem.next !== null) { + deletedItem.next.prev = deletedItem.prev; + } + + if (this.first === deletedItem) { + this.first = deletedItem.next; + } + + if (this.last === deletedItem) { + this.last = deletedItem.prev; + } + } + } + + deleteMany(keys) { + for (var i = 0; i < keys.length; i++) { + this.delete(keys[i]); + } + } + + evict() { + if (this.size > 0) { + const item = this.first; + + this.items.delete(item.key); + + if (this.size === 0) { + this.first = null; + this.last = null; + } else { + this.first = item.next; + this.first.prev = null; + } + } + } + + expiresAt(key) { + if (this.items.has(key)) { + return this.items.get(key).expiry + } + } + + get(key) { + if (this.items.has(key)) { + const item = this.items.get(key); + + if (this.ttl > 0 && item.expiry <= Date.now()) { + this.delete(key); + return + } + + return item.value + } + } + + getMany(keys) { + const result = []; + + for (var i = 0; i < keys.length; i++) { + result.push(this.get(keys[i])); + } + + return result + } + + keys() { + return this.items.keys() + } + + set(key, value) { + // Replace existing item + if (this.items.has(key)) { + const item = this.items.get(key); + item.value = value; + + item.expiry = this.ttl > 0 ? Date.now() + this.ttl : this.ttl; + + return + } + + // Add new item + if (this.max > 0 && this.size === this.max) { + this.evict(); + } + + const item = { + expiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl, + key: key, + prev: this.last, + next: null, + value, + }; + this.items.set(key, item); + + if (this.size === 1) { + this.first = item; + } else { + this.last.next = item; + } + + this.last = item; + } +} + +class LruMap { + constructor(max = 1000, ttlInMsecs = 0) { + if (isNaN(max) || max < 0) { + throw new Error('Invalid max value') + } + + if (isNaN(ttlInMsecs) || ttlInMsecs < 0) { + throw new Error('Invalid ttl value') + } + + this.first = null; + this.items = new Map(); + this.last = null; + this.max = max; + this.ttl = ttlInMsecs; + } + + get size() { + return this.items.size + } + + bumpLru(item) { + if (this.last === item) { + return // Item is already the last one, no need to bump + } + + const last = this.last; + const next = item.next; + const prev = item.prev; + + if (this.first === item) { + this.first = next; + } + + item.next = null; + item.prev = last; + last.next = item; + + if (prev !== null) { + prev.next = next; + } + + if (next !== null) { + next.prev = prev; + } + + this.last = item; + } + + clear() { + this.items = new Map(); + this.first = null; + this.last = null; + } + + delete(key) { + if (this.items.has(key)) { + const item = this.items.get(key); + + this.items.delete(key); + + if (item.prev !== null) { + item.prev.next = item.next; + } + + if (item.next !== null) { + item.next.prev = item.prev; + } + + if (this.first === item) { + this.first = item.next; + } + + if (this.last === item) { + this.last = item.prev; + } + } + } + + deleteMany(keys) { + for (var i = 0; i < keys.length; i++) { + this.delete(keys[i]); + } + } + + evict() { + if (this.size > 0) { + const item = this.first; + + this.items.delete(item.key); + + if (this.size === 0) { + this.first = null; + this.last = null; + } else { + this.first = item.next; + this.first.prev = null; + } + } + } + + expiresAt(key) { + if (this.items.has(key)) { + return this.items.get(key).expiry + } + } + + get(key) { + if (this.items.has(key)) { + const item = this.items.get(key); + + // Item has already expired + if (this.ttl > 0 && item.expiry <= Date.now()) { + this.delete(key); + return + } + + // Item is still fresh + this.bumpLru(item); + return item.value + } + } + + getMany(keys) { + const result = []; + + for (var i = 0; i < keys.length; i++) { + result.push(this.get(keys[i])); + } + + return result + } + + keys() { + return this.items.keys() + } + + set(key, value) { + // Replace existing item + if (this.items.has(key)) { + const item = this.items.get(key); + item.value = value; + + item.expiry = this.ttl > 0 ? Date.now() + this.ttl : this.ttl; + + if (this.last !== item) { + this.bumpLru(item); + } + + return + } + + // Add new item + if (this.max > 0 && this.size === this.max) { + this.evict(); + } + + const item = { + expiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl, + key: key, + prev: this.last, + next: null, + value, + }; + this.items.set(key, item); + + if (this.size === 1) { + this.first = item; + } else { + this.last.next = item; + } + + this.last = item; + } +} + +class LruObject { + constructor(max = 1000, ttlInMsecs = 0) { + if (isNaN(max) || max < 0) { + throw new Error('Invalid max value') + } + + if (isNaN(ttlInMsecs) || ttlInMsecs < 0) { + throw new Error('Invalid ttl value') + } + + this.first = null; + this.items = Object.create(null); + this.last = null; + this.size = 0; + this.max = max; + this.ttl = ttlInMsecs; + } + + bumpLru(item) { + if (this.last === item) { + return // Item is already the last one, no need to bump + } + + const last = this.last; + const next = item.next; + const prev = item.prev; + + if (this.first === item) { + this.first = next; + } + + item.next = null; + item.prev = last; + last.next = item; + + if (prev !== null) { + prev.next = next; + } + + if (next !== null) { + next.prev = prev; + } + + this.last = item; + } + + clear() { + this.items = Object.create(null); + this.first = null; + this.last = null; + this.size = 0; + } + + delete(key) { + if (Object.prototype.hasOwnProperty.call(this.items, key)) { + const item = this.items[key]; + + delete this.items[key]; + this.size--; + + if (item.prev !== null) { + item.prev.next = item.next; + } + + if (item.next !== null) { + item.next.prev = item.prev; + } + + if (this.first === item) { + this.first = item.next; + } + + if (this.last === item) { + this.last = item.prev; + } + } + } + + deleteMany(keys) { + for (var i = 0; i < keys.length; i++) { + this.delete(keys[i]); + } + } + + evict() { + if (this.size > 0) { + const item = this.first; + + delete this.items[item.key]; + + if (--this.size === 0) { + this.first = null; + this.last = null; + } else { + this.first = item.next; + this.first.prev = null; + } + } + } + + expiresAt(key) { + if (Object.prototype.hasOwnProperty.call(this.items, key)) { + return this.items[key].expiry + } + } + + get(key) { + if (Object.prototype.hasOwnProperty.call(this.items, key)) { + const item = this.items[key]; + + // Item has already expired + if (this.ttl > 0 && item.expiry <= Date.now()) { + this.delete(key); + return + } + + // Item is still fresh + this.bumpLru(item); + return item.value + } + } + + getMany(keys) { + const result = []; + + for (var i = 0; i < keys.length; i++) { + result.push(this.get(keys[i])); + } + + return result + } + + keys() { + return Object.keys(this.items) + } + + set(key, value) { + // Replace existing item + if (Object.prototype.hasOwnProperty.call(this.items, key)) { + const item = this.items[key]; + item.value = value; + + item.expiry = this.ttl > 0 ? Date.now() + this.ttl : this.ttl; + + if (this.last !== item) { + this.bumpLru(item); + } + + return + } + + // Add new item + if (this.max > 0 && this.size === this.max) { + this.evict(); + } + + const item = { + expiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl, + key: key, + prev: this.last, + next: null, + value, + }; + this.items[key] = item; + + if (++this.size === 1) { + this.first = item; + } else { + this.last.next = item; + } + + this.last = item; + } +} + +class HitStatisticsRecord { + constructor() { + this.records = {}; + } + + initForCache(cacheId, currentTimeStamp) { + this.records[cacheId] = { + [currentTimeStamp]: { + cacheSize: 0, + hits: 0, + falsyHits: 0, + emptyHits: 0, + misses: 0, + expirations: 0, + evictions: 0, + invalidateOne: 0, + invalidateAll: 0, + sets: 0, + }, + }; + } + + resetForCache(cacheId) { + for (let key of Object.keys(this.records[cacheId])) { + this.records[cacheId][key] = { + cacheSize: 0, + hits: 0, + falsyHits: 0, + emptyHits: 0, + misses: 0, + expirations: 0, + evictions: 0, + invalidateOne: 0, + invalidateAll: 0, + sets: 0, + }; + } + } + + getStatistics() { + return this.records + } +} + +/** + * + * @param {Date} date + * @returns {string} + */ +function getTimestamp(date) { + return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date + .getDate() + .toString() + .padStart(2, '0')}` +} + +class HitStatistics { + constructor(cacheId, statisticTtlInHours, globalStatisticsRecord) { + this.cacheId = cacheId; + this.statisticTtlInHours = statisticTtlInHours; + + this.collectionStart = new Date(); + this.currentTimeStamp = getTimestamp(this.collectionStart); + + this.records = globalStatisticsRecord || new HitStatisticsRecord(); + this.records.initForCache(this.cacheId, this.currentTimeStamp); + } + + get currentRecord() { + // safety net + /* c8 ignore next 14 */ + if (!this.records.records[this.cacheId][this.currentTimeStamp]) { + this.records.records[this.cacheId][this.currentTimeStamp] = { + cacheSize: 0, + hits: 0, + falsyHits: 0, + emptyHits: 0, + misses: 0, + expirations: 0, + evictions: 0, + sets: 0, + invalidateOne: 0, + invalidateAll: 0, + }; + } + + return this.records.records[this.cacheId][this.currentTimeStamp] + } + + hoursPassed() { + return (Date.now() - this.collectionStart) / 1000 / 60 / 60 + } + + addHit() { + this.archiveIfNeeded(); + this.currentRecord.hits++; + } + addFalsyHit() { + this.archiveIfNeeded(); + this.currentRecord.falsyHits++; + } + + addEmptyHit() { + this.archiveIfNeeded(); + this.currentRecord.emptyHits++; + } + + addMiss() { + this.archiveIfNeeded(); + this.currentRecord.misses++; + } + + addEviction() { + this.archiveIfNeeded(); + this.currentRecord.evictions++; + } + + setCacheSize(currentSize) { + this.archiveIfNeeded(); + this.currentRecord.cacheSize = currentSize; + } + + addExpiration() { + this.archiveIfNeeded(); + this.currentRecord.expirations++; + } + + addSet() { + this.archiveIfNeeded(); + this.currentRecord.sets++; + } + + addInvalidateOne() { + this.archiveIfNeeded(); + this.currentRecord.invalidateOne++; + } + + addInvalidateAll() { + this.archiveIfNeeded(); + this.currentRecord.invalidateAll++; + } + + getStatistics() { + return this.records.getStatistics() + } + + archiveIfNeeded() { + if (this.hoursPassed() >= this.statisticTtlInHours) { + this.collectionStart = new Date(); + this.currentTimeStamp = getTimestamp(this.collectionStart); + this.records.initForCache(this.cacheId, this.currentTimeStamp); + } + } +} + +class LruObjectHitStatistics extends LruObject { + constructor(max, ttlInMsecs, cacheId, globalStatisticsRecord, statisticTtlInHours) { + super(max || 1000, ttlInMsecs || 0); + + if (!cacheId) { + throw new Error('Cache id is mandatory') + } + + this.hitStatistics = new HitStatistics( + cacheId, + statisticTtlInHours !== undefined ? statisticTtlInHours : 24, + globalStatisticsRecord, + ); + } + + getStatistics() { + return this.hitStatistics.getStatistics() + } + + set(key, value) { + super.set(key, value); + this.hitStatistics.addSet(); + this.hitStatistics.setCacheSize(this.size); + } + + evict() { + super.evict(); + this.hitStatistics.addEviction(); + this.hitStatistics.setCacheSize(this.size); + } + + delete(key, isExpiration = false) { + super.delete(key); + + if (!isExpiration) { + this.hitStatistics.addInvalidateOne(); + } + this.hitStatistics.setCacheSize(this.size); + } + + clear() { + super.clear(); + + this.hitStatistics.addInvalidateAll(); + this.hitStatistics.setCacheSize(this.size); + } + + get(key) { + if (Object.prototype.hasOwnProperty.call(this.items, key)) { + const item = this.items[key]; + + // Item has already expired + if (this.ttl > 0 && item.expiry <= Date.now()) { + this.delete(key, true); + this.hitStatistics.addExpiration(); + return + } + + // Item is still fresh + this.bumpLru(item); + if (!item.value) { + this.hitStatistics.addFalsyHit(); + } + if (item.value === undefined || item.value === null || item.value === '') { + this.hitStatistics.addEmptyHit(); + } + this.hitStatistics.addHit(); + return item.value + } + this.hitStatistics.addMiss(); + } +} + +class FifoObject { + constructor(max = 1000, ttlInMsecs = 0) { + if (isNaN(max) || max < 0) { + throw new Error('Invalid max value') + } + + if (isNaN(ttlInMsecs) || ttlInMsecs < 0) { + throw new Error('Invalid ttl value') + } + + this.first = null; + this.items = Object.create(null); + this.last = null; + this.size = 0; + this.max = max; + this.ttl = ttlInMsecs; + } + + clear() { + this.items = Object.create(null); + this.first = null; + this.last = null; + this.size = 0; + } + + delete(key) { + if (Object.prototype.hasOwnProperty.call(this.items, key)) { + const deletedItem = this.items[key]; + + delete this.items[key]; + this.size--; + + if (deletedItem.prev !== null) { + deletedItem.prev.next = deletedItem.next; + } + + if (deletedItem.next !== null) { + deletedItem.next.prev = deletedItem.prev; + } + + if (this.first === deletedItem) { + this.first = deletedItem.next; + } + + if (this.last === deletedItem) { + this.last = deletedItem.prev; + } + } + } + + deleteMany(keys) { + for (var i = 0; i < keys.length; i++) { + this.delete(keys[i]); + } + } + + evict() { + if (this.size > 0) { + const item = this.first; + + delete this.items[item.key]; + + if (--this.size === 0) { + this.first = null; + this.last = null; + } else { + this.first = item.next; + this.first.prev = null; + } + } + } + + expiresAt(key) { + if (Object.prototype.hasOwnProperty.call(this.items, key)) { + return this.items[key].expiry + } + } + + get(key) { + if (Object.prototype.hasOwnProperty.call(this.items, key)) { + const item = this.items[key]; + + if (this.ttl > 0 && item.expiry <= Date.now()) { + this.delete(key); + return + } + + return item.value + } + } + + getMany(keys) { + const result = []; + + for (var i = 0; i < keys.length; i++) { + result.push(this.get(keys[i])); + } + + return result + } + + keys() { + return Object.keys(this.items) + } + + set(key, value) { + // Replace existing item + if (Object.prototype.hasOwnProperty.call(this.items, key)) { + const item = this.items[key]; + item.value = value; + + item.expiry = this.ttl > 0 ? Date.now() + this.ttl : this.ttl; + + return + } + + // Add new item + if (this.max > 0 && this.size === this.max) { + this.evict(); + } + + const item = { + expiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl, + key: key, + prev: this.last, + next: null, + value, + }; + this.items[key] = item; + + if (++this.size === 1) { + this.first = item; + } else { + this.last.next = item; + } + + this.last = item; + } +} + +exports.Fifo = FifoObject; +exports.FifoMap = FifoMap; +exports.FifoObject = FifoObject; +exports.HitStatisticsRecord = HitStatisticsRecord; +exports.Lru = LruObject; +exports.LruHitStatistics = LruObjectHitStatistics; +exports.LruMap = LruMap; +exports.LruObject = LruObject; +exports.LruObjectHitStatistics = LruObjectHitStatistics; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/toad-cache/dist/toad-cache.mjs b/novas/novacore-zephyr/claude-code-router/node_modules/toad-cache/dist/toad-cache.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ea43d86c86cf03e1e45344b49ddd5940a7887259 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/toad-cache/dist/toad-cache.mjs @@ -0,0 +1,852 @@ +/** + * toad-cache + * + * @copyright 2024 Igor Savin + * @license MIT + * @version 3.7.0 + */ +class FifoMap { + constructor(max = 1000, ttlInMsecs = 0) { + if (isNaN(max) || max < 0) { + throw new Error('Invalid max value') + } + + if (isNaN(ttlInMsecs) || ttlInMsecs < 0) { + throw new Error('Invalid ttl value') + } + + this.first = null; + this.items = new Map(); + this.last = null; + this.max = max; + this.ttl = ttlInMsecs; + } + + get size() { + return this.items.size + } + + clear() { + this.items = new Map(); + this.first = null; + this.last = null; + } + + delete(key) { + if (this.items.has(key)) { + const deletedItem = this.items.get(key); + + this.items.delete(key); + + if (deletedItem.prev !== null) { + deletedItem.prev.next = deletedItem.next; + } + + if (deletedItem.next !== null) { + deletedItem.next.prev = deletedItem.prev; + } + + if (this.first === deletedItem) { + this.first = deletedItem.next; + } + + if (this.last === deletedItem) { + this.last = deletedItem.prev; + } + } + } + + deleteMany(keys) { + for (var i = 0; i < keys.length; i++) { + this.delete(keys[i]); + } + } + + evict() { + if (this.size > 0) { + const item = this.first; + + this.items.delete(item.key); + + if (this.size === 0) { + this.first = null; + this.last = null; + } else { + this.first = item.next; + this.first.prev = null; + } + } + } + + expiresAt(key) { + if (this.items.has(key)) { + return this.items.get(key).expiry + } + } + + get(key) { + if (this.items.has(key)) { + const item = this.items.get(key); + + if (this.ttl > 0 && item.expiry <= Date.now()) { + this.delete(key); + return + } + + return item.value + } + } + + getMany(keys) { + const result = []; + + for (var i = 0; i < keys.length; i++) { + result.push(this.get(keys[i])); + } + + return result + } + + keys() { + return this.items.keys() + } + + set(key, value) { + // Replace existing item + if (this.items.has(key)) { + const item = this.items.get(key); + item.value = value; + + item.expiry = this.ttl > 0 ? Date.now() + this.ttl : this.ttl; + + return + } + + // Add new item + if (this.max > 0 && this.size === this.max) { + this.evict(); + } + + const item = { + expiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl, + key: key, + prev: this.last, + next: null, + value, + }; + this.items.set(key, item); + + if (this.size === 1) { + this.first = item; + } else { + this.last.next = item; + } + + this.last = item; + } +}class LruMap { + constructor(max = 1000, ttlInMsecs = 0) { + if (isNaN(max) || max < 0) { + throw new Error('Invalid max value') + } + + if (isNaN(ttlInMsecs) || ttlInMsecs < 0) { + throw new Error('Invalid ttl value') + } + + this.first = null; + this.items = new Map(); + this.last = null; + this.max = max; + this.ttl = ttlInMsecs; + } + + get size() { + return this.items.size + } + + bumpLru(item) { + if (this.last === item) { + return // Item is already the last one, no need to bump + } + + const last = this.last; + const next = item.next; + const prev = item.prev; + + if (this.first === item) { + this.first = next; + } + + item.next = null; + item.prev = last; + last.next = item; + + if (prev !== null) { + prev.next = next; + } + + if (next !== null) { + next.prev = prev; + } + + this.last = item; + } + + clear() { + this.items = new Map(); + this.first = null; + this.last = null; + } + + delete(key) { + if (this.items.has(key)) { + const item = this.items.get(key); + + this.items.delete(key); + + if (item.prev !== null) { + item.prev.next = item.next; + } + + if (item.next !== null) { + item.next.prev = item.prev; + } + + if (this.first === item) { + this.first = item.next; + } + + if (this.last === item) { + this.last = item.prev; + } + } + } + + deleteMany(keys) { + for (var i = 0; i < keys.length; i++) { + this.delete(keys[i]); + } + } + + evict() { + if (this.size > 0) { + const item = this.first; + + this.items.delete(item.key); + + if (this.size === 0) { + this.first = null; + this.last = null; + } else { + this.first = item.next; + this.first.prev = null; + } + } + } + + expiresAt(key) { + if (this.items.has(key)) { + return this.items.get(key).expiry + } + } + + get(key) { + if (this.items.has(key)) { + const item = this.items.get(key); + + // Item has already expired + if (this.ttl > 0 && item.expiry <= Date.now()) { + this.delete(key); + return + } + + // Item is still fresh + this.bumpLru(item); + return item.value + } + } + + getMany(keys) { + const result = []; + + for (var i = 0; i < keys.length; i++) { + result.push(this.get(keys[i])); + } + + return result + } + + keys() { + return this.items.keys() + } + + set(key, value) { + // Replace existing item + if (this.items.has(key)) { + const item = this.items.get(key); + item.value = value; + + item.expiry = this.ttl > 0 ? Date.now() + this.ttl : this.ttl; + + if (this.last !== item) { + this.bumpLru(item); + } + + return + } + + // Add new item + if (this.max > 0 && this.size === this.max) { + this.evict(); + } + + const item = { + expiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl, + key: key, + prev: this.last, + next: null, + value, + }; + this.items.set(key, item); + + if (this.size === 1) { + this.first = item; + } else { + this.last.next = item; + } + + this.last = item; + } +}class LruObject { + constructor(max = 1000, ttlInMsecs = 0) { + if (isNaN(max) || max < 0) { + throw new Error('Invalid max value') + } + + if (isNaN(ttlInMsecs) || ttlInMsecs < 0) { + throw new Error('Invalid ttl value') + } + + this.first = null; + this.items = Object.create(null); + this.last = null; + this.size = 0; + this.max = max; + this.ttl = ttlInMsecs; + } + + bumpLru(item) { + if (this.last === item) { + return // Item is already the last one, no need to bump + } + + const last = this.last; + const next = item.next; + const prev = item.prev; + + if (this.first === item) { + this.first = next; + } + + item.next = null; + item.prev = last; + last.next = item; + + if (prev !== null) { + prev.next = next; + } + + if (next !== null) { + next.prev = prev; + } + + this.last = item; + } + + clear() { + this.items = Object.create(null); + this.first = null; + this.last = null; + this.size = 0; + } + + delete(key) { + if (Object.prototype.hasOwnProperty.call(this.items, key)) { + const item = this.items[key]; + + delete this.items[key]; + this.size--; + + if (item.prev !== null) { + item.prev.next = item.next; + } + + if (item.next !== null) { + item.next.prev = item.prev; + } + + if (this.first === item) { + this.first = item.next; + } + + if (this.last === item) { + this.last = item.prev; + } + } + } + + deleteMany(keys) { + for (var i = 0; i < keys.length; i++) { + this.delete(keys[i]); + } + } + + evict() { + if (this.size > 0) { + const item = this.first; + + delete this.items[item.key]; + + if (--this.size === 0) { + this.first = null; + this.last = null; + } else { + this.first = item.next; + this.first.prev = null; + } + } + } + + expiresAt(key) { + if (Object.prototype.hasOwnProperty.call(this.items, key)) { + return this.items[key].expiry + } + } + + get(key) { + if (Object.prototype.hasOwnProperty.call(this.items, key)) { + const item = this.items[key]; + + // Item has already expired + if (this.ttl > 0 && item.expiry <= Date.now()) { + this.delete(key); + return + } + + // Item is still fresh + this.bumpLru(item); + return item.value + } + } + + getMany(keys) { + const result = []; + + for (var i = 0; i < keys.length; i++) { + result.push(this.get(keys[i])); + } + + return result + } + + keys() { + return Object.keys(this.items) + } + + set(key, value) { + // Replace existing item + if (Object.prototype.hasOwnProperty.call(this.items, key)) { + const item = this.items[key]; + item.value = value; + + item.expiry = this.ttl > 0 ? Date.now() + this.ttl : this.ttl; + + if (this.last !== item) { + this.bumpLru(item); + } + + return + } + + // Add new item + if (this.max > 0 && this.size === this.max) { + this.evict(); + } + + const item = { + expiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl, + key: key, + prev: this.last, + next: null, + value, + }; + this.items[key] = item; + + if (++this.size === 1) { + this.first = item; + } else { + this.last.next = item; + } + + this.last = item; + } +}class HitStatisticsRecord { + constructor() { + this.records = {}; + } + + initForCache(cacheId, currentTimeStamp) { + this.records[cacheId] = { + [currentTimeStamp]: { + cacheSize: 0, + hits: 0, + falsyHits: 0, + emptyHits: 0, + misses: 0, + expirations: 0, + evictions: 0, + invalidateOne: 0, + invalidateAll: 0, + sets: 0, + }, + }; + } + + resetForCache(cacheId) { + for (let key of Object.keys(this.records[cacheId])) { + this.records[cacheId][key] = { + cacheSize: 0, + hits: 0, + falsyHits: 0, + emptyHits: 0, + misses: 0, + expirations: 0, + evictions: 0, + invalidateOne: 0, + invalidateAll: 0, + sets: 0, + }; + } + } + + getStatistics() { + return this.records + } +}/** + * + * @param {Date} date + * @returns {string} + */ +function getTimestamp(date) { + return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date + .getDate() + .toString() + .padStart(2, '0')}` +}class HitStatistics { + constructor(cacheId, statisticTtlInHours, globalStatisticsRecord) { + this.cacheId = cacheId; + this.statisticTtlInHours = statisticTtlInHours; + + this.collectionStart = new Date(); + this.currentTimeStamp = getTimestamp(this.collectionStart); + + this.records = globalStatisticsRecord || new HitStatisticsRecord(); + this.records.initForCache(this.cacheId, this.currentTimeStamp); + } + + get currentRecord() { + // safety net + /* c8 ignore next 14 */ + if (!this.records.records[this.cacheId][this.currentTimeStamp]) { + this.records.records[this.cacheId][this.currentTimeStamp] = { + cacheSize: 0, + hits: 0, + falsyHits: 0, + emptyHits: 0, + misses: 0, + expirations: 0, + evictions: 0, + sets: 0, + invalidateOne: 0, + invalidateAll: 0, + }; + } + + return this.records.records[this.cacheId][this.currentTimeStamp] + } + + hoursPassed() { + return (Date.now() - this.collectionStart) / 1000 / 60 / 60 + } + + addHit() { + this.archiveIfNeeded(); + this.currentRecord.hits++; + } + addFalsyHit() { + this.archiveIfNeeded(); + this.currentRecord.falsyHits++; + } + + addEmptyHit() { + this.archiveIfNeeded(); + this.currentRecord.emptyHits++; + } + + addMiss() { + this.archiveIfNeeded(); + this.currentRecord.misses++; + } + + addEviction() { + this.archiveIfNeeded(); + this.currentRecord.evictions++; + } + + setCacheSize(currentSize) { + this.archiveIfNeeded(); + this.currentRecord.cacheSize = currentSize; + } + + addExpiration() { + this.archiveIfNeeded(); + this.currentRecord.expirations++; + } + + addSet() { + this.archiveIfNeeded(); + this.currentRecord.sets++; + } + + addInvalidateOne() { + this.archiveIfNeeded(); + this.currentRecord.invalidateOne++; + } + + addInvalidateAll() { + this.archiveIfNeeded(); + this.currentRecord.invalidateAll++; + } + + getStatistics() { + return this.records.getStatistics() + } + + archiveIfNeeded() { + if (this.hoursPassed() >= this.statisticTtlInHours) { + this.collectionStart = new Date(); + this.currentTimeStamp = getTimestamp(this.collectionStart); + this.records.initForCache(this.cacheId, this.currentTimeStamp); + } + } +}class LruObjectHitStatistics extends LruObject { + constructor(max, ttlInMsecs, cacheId, globalStatisticsRecord, statisticTtlInHours) { + super(max || 1000, ttlInMsecs || 0); + + if (!cacheId) { + throw new Error('Cache id is mandatory') + } + + this.hitStatistics = new HitStatistics( + cacheId, + statisticTtlInHours !== undefined ? statisticTtlInHours : 24, + globalStatisticsRecord, + ); + } + + getStatistics() { + return this.hitStatistics.getStatistics() + } + + set(key, value) { + super.set(key, value); + this.hitStatistics.addSet(); + this.hitStatistics.setCacheSize(this.size); + } + + evict() { + super.evict(); + this.hitStatistics.addEviction(); + this.hitStatistics.setCacheSize(this.size); + } + + delete(key, isExpiration = false) { + super.delete(key); + + if (!isExpiration) { + this.hitStatistics.addInvalidateOne(); + } + this.hitStatistics.setCacheSize(this.size); + } + + clear() { + super.clear(); + + this.hitStatistics.addInvalidateAll(); + this.hitStatistics.setCacheSize(this.size); + } + + get(key) { + if (Object.prototype.hasOwnProperty.call(this.items, key)) { + const item = this.items[key]; + + // Item has already expired + if (this.ttl > 0 && item.expiry <= Date.now()) { + this.delete(key, true); + this.hitStatistics.addExpiration(); + return + } + + // Item is still fresh + this.bumpLru(item); + if (!item.value) { + this.hitStatistics.addFalsyHit(); + } + if (item.value === undefined || item.value === null || item.value === '') { + this.hitStatistics.addEmptyHit(); + } + this.hitStatistics.addHit(); + return item.value + } + this.hitStatistics.addMiss(); + } +}class FifoObject { + constructor(max = 1000, ttlInMsecs = 0) { + if (isNaN(max) || max < 0) { + throw new Error('Invalid max value') + } + + if (isNaN(ttlInMsecs) || ttlInMsecs < 0) { + throw new Error('Invalid ttl value') + } + + this.first = null; + this.items = Object.create(null); + this.last = null; + this.size = 0; + this.max = max; + this.ttl = ttlInMsecs; + } + + clear() { + this.items = Object.create(null); + this.first = null; + this.last = null; + this.size = 0; + } + + delete(key) { + if (Object.prototype.hasOwnProperty.call(this.items, key)) { + const deletedItem = this.items[key]; + + delete this.items[key]; + this.size--; + + if (deletedItem.prev !== null) { + deletedItem.prev.next = deletedItem.next; + } + + if (deletedItem.next !== null) { + deletedItem.next.prev = deletedItem.prev; + } + + if (this.first === deletedItem) { + this.first = deletedItem.next; + } + + if (this.last === deletedItem) { + this.last = deletedItem.prev; + } + } + } + + deleteMany(keys) { + for (var i = 0; i < keys.length; i++) { + this.delete(keys[i]); + } + } + + evict() { + if (this.size > 0) { + const item = this.first; + + delete this.items[item.key]; + + if (--this.size === 0) { + this.first = null; + this.last = null; + } else { + this.first = item.next; + this.first.prev = null; + } + } + } + + expiresAt(key) { + if (Object.prototype.hasOwnProperty.call(this.items, key)) { + return this.items[key].expiry + } + } + + get(key) { + if (Object.prototype.hasOwnProperty.call(this.items, key)) { + const item = this.items[key]; + + if (this.ttl > 0 && item.expiry <= Date.now()) { + this.delete(key); + return + } + + return item.value + } + } + + getMany(keys) { + const result = []; + + for (var i = 0; i < keys.length; i++) { + result.push(this.get(keys[i])); + } + + return result + } + + keys() { + return Object.keys(this.items) + } + + set(key, value) { + // Replace existing item + if (Object.prototype.hasOwnProperty.call(this.items, key)) { + const item = this.items[key]; + item.value = value; + + item.expiry = this.ttl > 0 ? Date.now() + this.ttl : this.ttl; + + return + } + + // Add new item + if (this.max > 0 && this.size === this.max) { + this.evict(); + } + + const item = { + expiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl, + key: key, + prev: this.last, + next: null, + value, + }; + this.items[key] = item; + + if (++this.size === 1) { + this.first = item; + } else { + this.last.next = item; + } + + this.last = item; + } +}export{FifoObject as Fifo,FifoMap,FifoObject,HitStatisticsRecord,LruObject as Lru,LruObjectHitStatistics as LruHitStatistics,LruMap,LruObject,LruObjectHitStatistics}; \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/Agent.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/Agent.md new file mode 100644 index 0000000000000000000000000000000000000000..2a8e30bac1461c3971a288ea995965f02489a01d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/Agent.md @@ -0,0 +1,83 @@ +# Agent + +Extends: `undici.Dispatcher` + +Agent allows dispatching requests against multiple different origins. + +Requests are not guaranteed to be dispatched in order of invocation. + +## `new undici.Agent([options])` + +Arguments: + +* **options** `AgentOptions` (optional) + +Returns: `Agent` + +### Parameter: `AgentOptions` + +Extends: [`PoolOptions`](/docs/docs/api/Pool.md#parameter-pooloptions) + +* **factory** `(origin: URL, opts: Object) => Dispatcher` - Default: `(origin, opts) => new Pool(origin, opts)` + +## Instance Properties + +### `Agent.closed` + +Implements [Client.closed](/docs/docs/api/Client.md#clientclosed) + +### `Agent.destroyed` + +Implements [Client.destroyed](/docs/docs/api/Client.md#clientdestroyed) + +## Instance Methods + +### `Agent.close([callback])` + +Implements [`Dispatcher.close([callback])`](/docs/docs/api/Dispatcher.md#dispatcherclosecallback-promise). + +### `Agent.destroy([error, callback])` + +Implements [`Dispatcher.destroy([error, callback])`](/docs/docs/api/Dispatcher.md#dispatcherdestroyerror-callback-promise). + +### `Agent.dispatch(options, handler: AgentDispatchOptions)` + +Implements [`Dispatcher.dispatch(options, handler)`](/docs/docs/api/Dispatcher.md#dispatcherdispatchoptions-handler). + +#### Parameter: `AgentDispatchOptions` + +Extends: [`DispatchOptions`](/docs/docs/api/Dispatcher.md#parameter-dispatchoptions) + +* **origin** `string | URL` + +Implements [`Dispatcher.destroy([error, callback])`](/docs/docs/api/Dispatcher.md#dispatcherdestroyerror-callback-promise). + +### `Agent.connect(options[, callback])` + +See [`Dispatcher.connect(options[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherconnectoptions-callback). + +### `Agent.dispatch(options, handler)` + +Implements [`Dispatcher.dispatch(options, handler)`](/docs/docs/api/Dispatcher.md#dispatcherdispatchoptions-handler). + +### `Agent.pipeline(options, handler)` + +See [`Dispatcher.pipeline(options, handler)`](/docs/docs/api/Dispatcher.md#dispatcherpipelineoptions-handler). + +### `Agent.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](/docs/docs/api/Dispatcher.md#dispatcherrequestoptions-callback). + +### `Agent.stream(options, factory[, callback])` + +See [`Dispatcher.stream(options, factory[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherstreamoptions-factory-callback). + +### `Agent.upgrade(options[, callback])` + +See [`Dispatcher.upgrade(options[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherupgradeoptions-callback). + +### `Agent.stats()` + +Returns an object of stats by origin in the format of `Record` + +See [`PoolStats`](/docs/docs/api/PoolStats.md) and [`ClientStats`](/docs/docs/api/ClientStats.md). diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/BalancedPool.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/BalancedPool.md new file mode 100644 index 0000000000000000000000000000000000000000..df267fe727054a94d3a35cd2a4dabd8fb5b84c39 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/BalancedPool.md @@ -0,0 +1,99 @@ +# Class: BalancedPool + +Extends: `undici.Dispatcher` + +A pool of [Pool](/docs/docs/api/Pool.md) instances connected to multiple upstreams. + +Requests are not guaranteed to be dispatched in order of invocation. + +## `new BalancedPool(upstreams [, options])` + +Arguments: + +* **upstreams** `URL | string | string[]` - It should only include the **protocol, hostname, and port**. +* **options** `BalancedPoolOptions` (optional) + +### Parameter: `BalancedPoolOptions` + +Extends: [`PoolOptions`](/docs/docs/api/Pool.md#parameter-pooloptions) + +* **factory** `(origin: URL, opts: Object) => Dispatcher` - Default: `(origin, opts) => new Pool(origin, opts)` + +The `PoolOptions` are passed to each of the `Pool` instances being created. +## Instance Properties + +### `BalancedPool.upstreams` + +Returns an array of upstreams that were previously added. + +### `BalancedPool.closed` + +Implements [Client.closed](/docs/docs/api/Client.md#clientclosed) + +### `BalancedPool.destroyed` + +Implements [Client.destroyed](/docs/docs/api/Client.md#clientdestroyed) + +### `Pool.stats` + +Returns [`PoolStats`](/docs/docs/api/PoolStats.md) instance for this pool. + +## Instance Methods + +### `BalancedPool.addUpstream(upstream)` + +Add an upstream. + +Arguments: + +* **upstream** `string` - It should only include the **protocol, hostname, and port**. + +### `BalancedPool.removeUpstream(upstream)` + +Removes an upstream that was previously added. + +### `BalancedPool.close([callback])` + +Implements [`Dispatcher.close([callback])`](/docs/docs/api/Dispatcher.md#dispatcherclosecallback-promise). + +### `BalancedPool.destroy([error, callback])` + +Implements [`Dispatcher.destroy([error, callback])`](/docs/docs/api/Dispatcher.md#dispatcherdestroyerror-callback-promise). + +### `BalancedPool.connect(options[, callback])` + +See [`Dispatcher.connect(options[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherconnectoptions-callback). + +### `BalancedPool.dispatch(options, handlers)` + +Implements [`Dispatcher.dispatch(options, handlers)`](/docs/docs/api/Dispatcher.md#dispatcherdispatchoptions-handler). + +### `BalancedPool.pipeline(options, handler)` + +See [`Dispatcher.pipeline(options, handler)`](/docs/docs/api/Dispatcher.md#dispatcherpipelineoptions-handler). + +### `BalancedPool.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](/docs/docs/api/Dispatcher.md#dispatcherrequestoptions-callback). + +### `BalancedPool.stream(options, factory[, callback])` + +See [`Dispatcher.stream(options, factory[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherstreamoptions-factory-callback). + +### `BalancedPool.upgrade(options[, callback])` + +See [`Dispatcher.upgrade(options[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherupgradeoptions-callback). + +## Instance Events + +### Event: `'connect'` + +See [Dispatcher Event: `'connect'`](/docs/docs/api/Dispatcher.md#event-connect). + +### Event: `'disconnect'` + +See [Dispatcher Event: `'disconnect'`](/docs/docs/api/Dispatcher.md#event-disconnect). + +### Event: `'drain'` + +See [Dispatcher Event: `'drain'`](/docs/docs/api/Dispatcher.md#event-drain). diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/CacheStorage.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/CacheStorage.md new file mode 100644 index 0000000000000000000000000000000000000000..08ee99fab148cea2b8de9e2d27efdc6fa417fbd0 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/CacheStorage.md @@ -0,0 +1,30 @@ +# CacheStorage + +Undici exposes a W3C spec-compliant implementation of [CacheStorage](https://developer.mozilla.org/en-US/docs/Web/API/CacheStorage) and [Cache](https://developer.mozilla.org/en-US/docs/Web/API/Cache). + +## Opening a Cache + +Undici exports a top-level CacheStorage instance. You can open a new Cache, or duplicate a Cache with an existing name, by using `CacheStorage.prototype.open`. If you open a Cache with the same name as an already-existing Cache, its list of cached Responses will be shared between both instances. + +```mjs +import { caches } from 'undici' + +const cache_1 = await caches.open('v1') +const cache_2 = await caches.open('v1') + +// Although .open() creates a new instance, +assert(cache_1 !== cache_2) +// The same Response is matched in both. +assert.deepStrictEqual(await cache_1.match('/req'), await cache_2.match('/req')) +``` + +## Deleting a Cache + +If a Cache is deleted, the cached Responses/Requests can still be used. + +```mjs +const response = await cache_1.match('/req') +await caches.delete('v1') + +await response.text() // the Response's body +``` diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/CacheStore.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/CacheStore.md new file mode 100644 index 0000000000000000000000000000000000000000..00ceb9606418898fceace4dadb57d1d43253645e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/CacheStore.md @@ -0,0 +1,151 @@ +# Cache Store + +A Cache Store is responsible for storing and retrieving cached responses. +It is also responsible for deciding which specific response to use based off of +a response's `Vary` header (if present). It is expected to be compliant with +[RFC-9111](https://www.rfc-editor.org/rfc/rfc9111.html). + +## Pre-built Cache Stores + +### `MemoryCacheStore` + +The `MemoryCacheStore` stores the responses in-memory. + +**Options** + +- `maxSize` - The maximum total size in bytes of all stored responses. Default `104857600` (100MB). +- `maxCount` - The maximum amount of responses to store. Default `1024`. +- `maxEntrySize` - The maximum size in bytes that a response's body can be. If a response's body is greater than or equal to this, the response will not be cached. Default `5242880` (5MB). + +### Getters + +#### `MemoryCacheStore.size` + +Returns the current total size in bytes of all stored responses. + +### Methods + +#### `MemoryCacheStore.isFull()` + +Returns a boolean indicating whether the cache has reached its maximum size or count. + +### Events + +#### `'maxSizeExceeded'` + +Emitted when the cache exceeds its maximum size or count limits. The event payload contains `size`, `maxSize`, `count`, and `maxCount` properties. + + +### `SqliteCacheStore` + +The `SqliteCacheStore` stores the responses in a SQLite database. +Under the hood, it uses Node.js' [`node:sqlite`](https://nodejs.org/api/sqlite.html) api. +The `SqliteCacheStore` is only exposed if the `node:sqlite` api is present. + +**Options** + +- `location` - The location of the SQLite database to use. Default `:memory:`. +- `maxCount` - The maximum number of entries to store in the database. Default `Infinity`. +- `maxEntrySize` - The maximum size in bytes that a response's body can be. If a response's body is greater than or equal to this, the response will not be cached. Default `Infinity`. + +## Defining a Custom Cache Store + +The store must implement the following functions: + +### Getter: `isFull` + +Optional. This tells the cache interceptor if the store is full or not. If this is true, +the cache interceptor will not attempt to cache the response. + +### Function: `get` + +Parameters: + +* **req** `Dispatcher.RequestOptions` - Incoming request + +Returns: `GetResult | Promise | undefined` - If the request is cached, the cached response is returned. If the request's method is anything other than HEAD, the response is also returned. +If the request isn't cached, `undefined` is returned. + +Response properties: + +* **response** `CacheValue` - The cached response data. +* **body** `Readable | undefined` - The response's body. + +### Function: `createWriteStream` + +Parameters: + +* **req** `Dispatcher.RequestOptions` - Incoming request +* **value** `CacheValue` - Response to store + +Returns: `Writable | undefined` - If the store is full, return `undefined`. Otherwise, return a writable so that the cache interceptor can stream the body and trailers to the store. + +## `CacheValue` + +This is an interface containing the majority of a response's data (minus the body). + +### Property `statusCode` + +`number` - The response's HTTP status code. + +### Property `statusMessage` + +`string` - The response's HTTP status message. + +### Property `rawHeaders` + +`Buffer[]` - The response's headers. + +### Property `vary` + +`Record | undefined` - The headers defined by the response's `Vary` header +and their respective values for later comparison + +For example, for a response like +``` +Vary: content-encoding, accepts +content-encoding: utf8 +accepts: application/json +``` + +This would be +```js +{ + 'content-encoding': 'utf8', + accepts: 'application/json' +} +``` + +### Property `cachedAt` + +`number` - Time in millis that this value was cached. + +### Property `staleAt` + +`number` - Time in millis that this value is considered stale. + +### Property `deleteAt` + +`number` - Time in millis that this value is to be deleted from the cache. This +is either the same sa staleAt or the `max-stale` caching directive. + +The store must not return a response after the time defined in this property. + +## `CacheStoreReadable` + +This extends Node's [`Readable`](https://nodejs.org/api/stream.html#class-streamreadable) +and defines extra properties relevant to the cache interceptor. + +### Getter: `value` + +The response's [`CacheStoreValue`](/docs/docs/api/CacheStore.md#cachestorevalue) + +## `CacheStoreWriteable` + +This extends Node's [`Writable`](https://nodejs.org/api/stream.html#class-streamwritable) +and defines extra properties relevant to the cache interceptor. + +### Setter: `rawTrailers` + +If the response has trailers, the cache interceptor will pass them to the cache +interceptor through this method. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/Client.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/Client.md new file mode 100644 index 0000000000000000000000000000000000000000..eab6ddc45acd3ecd216047c7746e1ba77b9a5964 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/Client.md @@ -0,0 +1,281 @@ +# Class: Client + +Extends: `undici.Dispatcher` + +A basic HTTP/1.1 client, mapped on top a single TCP/TLS connection. Pipelining is disabled by default. + +Requests are not guaranteed to be dispatched in order of invocation. + +## `new Client(url[, options])` + +Arguments: + +* **url** `URL | string` - Should only include the **protocol, hostname, and port**. +* **options** `ClientOptions` (optional) + +Returns: `Client` + +### Parameter: `ClientOptions` + +* **bodyTimeout** `number | null` (optional) - Default: `300e3` - The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Defaults to 300 seconds. Please note the `timeout` will be reset if you keep writing data to the socket everytime. +* **headersTimeout** `number | null` (optional) - Default: `300e3` - The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers while not sending the request. Defaults to 300 seconds. +* **keepAliveMaxTimeout** `number | null` (optional) - Default: `600e3` - The maximum allowed `keepAliveTimeout`, in milliseconds, when overridden by *keep-alive* hints from the server. Defaults to 10 minutes. +* **keepAliveTimeout** `number | null` (optional) - Default: `4e3` - The timeout, in milliseconds, after which a socket without active requests will time out. Monitors time between activity on a connected socket. This value may be overridden by *keep-alive* hints from the server. See [MDN: HTTP - Headers - Keep-Alive directives](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Keep-Alive#directives) for more details. Defaults to 4 seconds. +* **keepAliveTimeoutThreshold** `number | null` (optional) - Default: `2e3` - A number of milliseconds subtracted from server *keep-alive* hints when overriding `keepAliveTimeout` to account for timing inaccuracies caused by e.g. transport latency. Defaults to 2 seconds. +* **maxHeaderSize** `number | null` (optional) - Default: `--max-http-header-size` or `16384` - The maximum length of request headers in bytes. Defaults to Node.js' --max-http-header-size or 16KiB. +* **maxResponseSize** `number | null` (optional) - Default: `-1` - The maximum length of response body in bytes. Set to `-1` to disable. +* **pipelining** `number | null` (optional) - Default: `1` - The amount of concurrent requests to be sent over the single TCP/TLS connection according to [RFC7230](https://tools.ietf.org/html/rfc7230#section-6.3.2). Carefully consider your workload and environment before enabling concurrent requests as pipelining may reduce performance if used incorrectly. Pipelining is sensitive to network stack settings as well as head of line blocking caused by e.g. long running requests. Set to `0` to disable keep-alive connections. +* **connect** `ConnectOptions | Function | null` (optional) - Default: `null`. +* **strictContentLength** `Boolean` (optional) - Default: `true` - Whether to treat request content length mismatches as errors. If true, an error is thrown when the request content-length header doesn't match the length of the request body. +* **autoSelectFamily**: `boolean` (optional) - Default: depends on local Node version, on Node 18.13.0 and above is `false`. Enables a family autodetection algorithm that loosely implements section 5 of [RFC 8305](https://tools.ietf.org/html/rfc8305#section-5). See [here](https://nodejs.org/api/net.html#socketconnectoptions-connectlistener) for more details. This option is ignored if not supported by the current Node version. +* **autoSelectFamilyAttemptTimeout**: `number` - Default: depends on local Node version, on Node 18.13.0 and above is `250`. The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option. See [here](https://nodejs.org/api/net.html#socketconnectoptions-connectlistener) for more details. +* **allowH2**: `boolean` - Default: `false`. Enables support for H2 if the server has assigned bigger priority to it through ALPN negotiation. +* **maxConcurrentStreams**: `number` - Default: `100`. Dictates the maximum number of concurrent streams for a single H2 session. It can be overridden by a SETTINGS remote frame. + +> **Notes about HTTP/2** +> - It only works under TLS connections. h2c is not supported. +> - The server must support HTTP/2 and choose it as the protocol during the ALPN negotiation. +> - The server must not have a bigger priority for HTTP/1.1 than HTTP/2. +> - Pseudo headers are automatically attached to the request. If you try to set them, they will be overwritten. +> - The `:path` header is automatically set to the request path. +> - The `:method` header is automatically set to the request method. +> - The `:scheme` header is automatically set to the request scheme. +> - The `:authority` header is automatically set to the request `host[:port]`. +> - `PUSH` frames are yet not supported. + +#### Parameter: `ConnectOptions` + +Every Tls option, see [here](https://nodejs.org/api/tls.html#tls_tls_connect_options_callback). +Furthermore, the following options can be passed: + +* **socketPath** `string | null` (optional) - Default: `null` - An IPC endpoint, either Unix domain socket or Windows named pipe. +* **maxCachedSessions** `number | null` (optional) - Default: `100` - Maximum number of TLS cached sessions. Use 0 to disable TLS session caching. Default: 100. +* **timeout** `number | null` (optional) - In milliseconds, Default `10e3`. +* **servername** `string | null` (optional) +* **keepAlive** `boolean | null` (optional) - Default: `true` - TCP keep-alive enabled +* **keepAliveInitialDelay** `number | null` (optional) - Default: `60000` - TCP keep-alive interval for the socket in milliseconds + +### Example - Basic Client instantiation + +This will instantiate the undici Client, but it will not connect to the origin until something is queued. Consider using `client.connect` to prematurely connect to the origin, or just call `client.request`. + +```js +'use strict' +import { Client } from 'undici' + +const client = new Client('http://localhost:3000') +``` + +### Example - Custom connector + +This will allow you to perform some additional check on the socket that will be used for the next request. + +```js +'use strict' +import { Client, buildConnector } from 'undici' + +const connector = buildConnector({ rejectUnauthorized: false }) +const client = new Client('https://localhost:3000', { + connect (opts, cb) { + connector(opts, (err, socket) => { + if (err) { + cb(err) + } else if (/* assertion */) { + socket.destroy() + cb(new Error('kaboom')) + } else { + cb(null, socket) + } + }) + } +}) +``` + +## Instance Methods + +### `Client.close([callback])` + +Implements [`Dispatcher.close([callback])`](/docs/docs/api/Dispatcher.md#dispatcherclosecallback-promise). + +### `Client.destroy([error, callback])` + +Implements [`Dispatcher.destroy([error, callback])`](/docs/docs/api/Dispatcher.md#dispatcherdestroyerror-callback-promise). + +Waits until socket is closed before invoking the callback (or returning a promise if no callback is provided). + +### `Client.connect(options[, callback])` + +See [`Dispatcher.connect(options[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherconnectoptions-callback). + +### `Client.dispatch(options, handlers)` + +Implements [`Dispatcher.dispatch(options, handlers)`](/docs/docs/api/Dispatcher.md#dispatcherdispatchoptions-handler). + +### `Client.pipeline(options, handler)` + +See [`Dispatcher.pipeline(options, handler)`](/docs/docs/api/Dispatcher.md#dispatcherpipelineoptions-handler). + +### `Client.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](/docs/docs/api/Dispatcher.md#dispatcherrequestoptions-callback). + +### `Client.stream(options, factory[, callback])` + +See [`Dispatcher.stream(options, factory[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherstreamoptions-factory-callback). + +### `Client.upgrade(options[, callback])` + +See [`Dispatcher.upgrade(options[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherupgradeoptions-callback). + +## Instance Properties + +### `Client.closed` + +* `boolean` + +`true` after `client.close()` has been called. + +### `Client.destroyed` + +* `boolean` + +`true` after `client.destroyed()` has been called or `client.close()` has been called and the client shutdown has completed. + +### `Client.pipelining` + +* `number` + +Property to get and set the pipelining factor. + +## Instance Events + +### Event: `'connect'` + +See [Dispatcher Event: `'connect'`](/docs/docs/api/Dispatcher.md#event-connect). + +Parameters: + +* **origin** `URL` +* **targets** `Array` + +Emitted when a socket has been created and connected. The client will connect once `client.size > 0`. + +#### Example - Client connect event + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +client.on('connect', (origin) => { + console.log(`Connected to ${origin}`) // should print before the request body statement +}) + +try { + const { body } = await client.request({ + path: '/', + method: 'GET' + }) + body.setEncoding('utf-8') + body.on('data', console.log) + client.close() + server.close() +} catch (error) { + console.error(error) + client.close() + server.close() +} +``` + +### Event: `'disconnect'` + +See [Dispatcher Event: `'disconnect'`](/docs/docs/api/Dispatcher.md#event-disconnect). + +Parameters: + +* **origin** `URL` +* **targets** `Array` +* **error** `Error` + +Emitted when socket has disconnected. The error argument of the event is the error which caused the socket to disconnect. The client will reconnect if or once `client.size > 0`. + +#### Example - Client disconnect event + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.destroy() +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +client.on('disconnect', (origin) => { + console.log(`Disconnected from ${origin}`) +}) + +try { + await client.request({ + path: '/', + method: 'GET' + }) +} catch (error) { + console.error(error.message) + client.close() + server.close() +} +``` + +### Event: `'drain'` + +Emitted when pipeline is no longer busy. + +See [Dispatcher Event: `'drain'`](/docs/docs/api/Dispatcher.md#event-drain). + +#### Example - Client drain event + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +client.on('drain', () => { + console.log('drain event') + client.close() + server.close() +}) + +const requests = [ + client.request({ path: '/', method: 'GET' }), + client.request({ path: '/', method: 'GET' }), + client.request({ path: '/', method: 'GET' }) +] + +await Promise.all(requests) + +console.log('requests completed') +``` + +### Event: `'error'` + +Invoked for users errors such as throwing in the `onError` handler. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/ClientStats.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/ClientStats.md new file mode 100644 index 0000000000000000000000000000000000000000..fa899d482c855ba584498471e3a9b3cc0c05a9f1 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/ClientStats.md @@ -0,0 +1,27 @@ +# Class: ClientStats + +Stats for a [Client](/docs/docs/api/Client.md). + +## `new ClientStats(client)` + +Arguments: + +* **client** `Client` - Client from which to return stats. + +## Instance Properties + +### `ClientStats.connected` + +Boolean if socket as open connection by this client. + +### `ClientStats.pending` + +Number of pending requests of this client. + +### `ClientStats.running` + +Number of currently active requests across this client. + +### `ClientStats.size` + +Number of active, pending, or queued requests of this clients. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/Connector.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/Connector.md new file mode 100644 index 0000000000000000000000000000000000000000..56821bd6430279cf07066e9b543749aa0748cb04 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/Connector.md @@ -0,0 +1,115 @@ +# Connector + +Undici creates the underlying socket via the connector builder. +Normally, this happens automatically and you don't need to care about this, +but if you need to perform some additional check over the currently used socket, +this is the right place. + +If you want to create a custom connector, you must import the `buildConnector` utility. + +#### Parameter: `buildConnector.BuildOptions` + +Every Tls option, see [here](https://nodejs.org/api/tls.html#tls_tls_connect_options_callback). +Furthermore, the following options can be passed: + +* **socketPath** `string | null` (optional) - Default: `null` - An IPC endpoint, either Unix domain socket or Windows named pipe. +* **maxCachedSessions** `number | null` (optional) - Default: `100` - Maximum number of TLS cached sessions. Use 0 to disable TLS session caching. Default: `100`. +* **timeout** `number | null` (optional) - In milliseconds. Default `10e3`. +* **servername** `string | null` (optional) + +Once you call `buildConnector`, it will return a connector function, which takes the following parameters. + +#### Parameter: `connector.Options` + +* **hostname** `string` (required) +* **host** `string` (optional) +* **protocol** `string` (required) +* **port** `string` (required) +* **servername** `string` (optional) +* **localAddress** `string | null` (optional) Local address the socket should connect from. +* **httpSocket** `Socket` (optional) Establish secure connection on a given socket rather than creating a new socket. It can only be sent on TLS update. + +### Basic example + +```js +'use strict' + +import { Client, buildConnector } from 'undici' + +const connector = buildConnector({ rejectUnauthorized: false }) +const client = new Client('https://localhost:3000', { + connect (opts, cb) { + connector(opts, (err, socket) => { + if (err) { + cb(err) + } else if (/* assertion */) { + socket.destroy() + cb(new Error('kaboom')) + } else { + cb(null, socket) + } + }) + } +}) +``` + +### Example: validate the CA fingerprint + +```js +'use strict' + +import { Client, buildConnector } from 'undici' + +const caFingerprint = 'FO:OB:AR' +const connector = buildConnector({ rejectUnauthorized: false }) +const client = new Client('https://localhost:3000', { + connect (opts, cb) { + connector(opts, (err, socket) => { + if (err) { + cb(err) + } else if (getIssuerCertificate(socket).fingerprint256 !== caFingerprint) { + socket.destroy() + cb(new Error('Fingerprint does not match or malformed certificate')) + } else { + cb(null, socket) + } + }) + } +}) + +client.request({ + path: '/', + method: 'GET' +}, (err, data) => { + if (err) throw err + + const bufs = [] + data.body.on('data', (buf) => { + bufs.push(buf) + }) + data.body.on('end', () => { + console.log(Buffer.concat(bufs).toString('utf8')) + client.close() + }) +}) + +function getIssuerCertificate (socket) { + let certificate = socket.getPeerCertificate(true) + while (certificate && Object.keys(certificate).length > 0) { + // invalid certificate + if (certificate.issuerCertificate == null) { + return null + } + + // We have reached the root certificate. + // In case of self-signed certificates, `issuerCertificate` may be a circular reference. + if (certificate.fingerprint256 === certificate.issuerCertificate.fingerprint256) { + break + } + + // continue the loop + certificate = certificate.issuerCertificate + } + return certificate +} +``` diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/ContentType.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/ContentType.md new file mode 100644 index 0000000000000000000000000000000000000000..2bcc9f71ca3252a189d58d338001942c93dba50f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/ContentType.md @@ -0,0 +1,57 @@ +# MIME Type Parsing + +## `MIMEType` interface + +* **type** `string` +* **subtype** `string` +* **parameters** `Map` +* **essence** `string` + +## `parseMIMEType(input)` + +Implements [parse a MIME type](https://mimesniff.spec.whatwg.org/#parse-a-mime-type). + +Parses a MIME type, returning its type, subtype, and any associated parameters. If the parser can't parse an input it returns the string literal `'failure'`. + +```js +import { parseMIMEType } from 'undici' + +parseMIMEType('text/html; charset=gbk') +// { +// type: 'text', +// subtype: 'html', +// parameters: Map(1) { 'charset' => 'gbk' }, +// essence: 'text/html' +// } +``` + +Arguments: + +* **input** `string` + +Returns: `MIMEType|'failure'` + +## `serializeAMimeType(input)` + +Implements [serialize a MIME type](https://mimesniff.spec.whatwg.org/#serialize-a-mime-type). + +Serializes a MIMEType object. + +```js +import { serializeAMimeType } from 'undici' + +serializeAMimeType({ + type: 'text', + subtype: 'html', + parameters: new Map([['charset', 'gbk']]), + essence: 'text/html' +}) +// text/html;charset=gbk + +``` + +Arguments: + +* **mimeType** `MIMEType` + +Returns: `string` diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/Cookies.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/Cookies.md new file mode 100644 index 0000000000000000000000000000000000000000..0cad37914d625889459e439768aa7d72848816aa --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/Cookies.md @@ -0,0 +1,101 @@ +# Cookie Handling + +## `Cookie` interface + +* **name** `string` +* **value** `string` +* **expires** `Date|number` (optional) +* **maxAge** `number` (optional) +* **domain** `string` (optional) +* **path** `string` (optional) +* **secure** `boolean` (optional) +* **httpOnly** `boolean` (optional) +* **sameSite** `'String'|'Lax'|'None'` (optional) +* **unparsed** `string[]` (optional) Left over attributes that weren't parsed. + +## `deleteCookie(headers, name[, attributes])` + +Sets the expiry time of the cookie to the unix epoch, causing browsers to delete it when received. + +```js +import { deleteCookie, Headers } from 'undici' + +const headers = new Headers() +deleteCookie(headers, 'name') + +console.log(headers.get('set-cookie')) // name=; Expires=Thu, 01 Jan 1970 00:00:00 GMT +``` + +Arguments: + +* **headers** `Headers` +* **name** `string` +* **attributes** `{ path?: string, domain?: string }` (optional) + +Returns: `void` + +## `getCookies(headers)` + +Parses the `Cookie` header and returns a list of attributes and values. + +```js +import { getCookies, Headers } from 'undici' + +const headers = new Headers({ + cookie: 'get=cookies; and=attributes' +}) + +console.log(getCookies(headers)) // { get: 'cookies', and: 'attributes' } +``` + +Arguments: + +* **headers** `Headers` + +Returns: `Record` + +## `getSetCookies(headers)` + +Parses all `Set-Cookie` headers. + +```js +import { getSetCookies, Headers } from 'undici' + +const headers = new Headers({ 'set-cookie': 'undici=getSetCookies; Secure' }) + +console.log(getSetCookies(headers)) +// [ +// { +// name: 'undici', +// value: 'getSetCookies', +// secure: true +// } +// ] + +``` + +Arguments: + +* **headers** `Headers` + +Returns: `Cookie[]` + +## `setCookie(headers, cookie)` + +Appends a cookie to the `Set-Cookie` header. + +```js +import { setCookie, Headers } from 'undici' + +const headers = new Headers() +setCookie(headers, { name: 'undici', value: 'setCookie' }) + +console.log(headers.get('Set-Cookie')) // undici=setCookie +``` + +Arguments: + +* **headers** `Headers` +* **cookie** `Cookie` + +Returns: `void` diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/Debug.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/Debug.md new file mode 100644 index 0000000000000000000000000000000000000000..69c7d7b4fee5c87ce0c5181f1d2346ab806263cc --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/Debug.md @@ -0,0 +1,62 @@ +# Debug + +Undici (and subsenquently `fetch` and `websocket`) exposes a debug statement that can be enabled by setting `NODE_DEBUG` within the environment. + +The flags available are: + +## `undici` + +This flag enables debug statements for the core undici library. + +```sh +NODE_DEBUG=undici node script.js + +UNDICI 16241: connecting to nodejs.org using https:h1 +UNDICI 16241: connecting to nodejs.org using https:h1 +UNDICI 16241: connected to nodejs.org using https:h1 +UNDICI 16241: sending request to GET https://nodejs.org/ +UNDICI 16241: received response to GET https://nodejs.org/ - HTTP 307 +UNDICI 16241: connecting to nodejs.org using https:h1 +UNDICI 16241: trailers received from GET https://nodejs.org/ +UNDICI 16241: connected to nodejs.org using https:h1 +UNDICI 16241: sending request to GET https://nodejs.org/en +UNDICI 16241: received response to GET https://nodejs.org/en - HTTP 200 +UNDICI 16241: trailers received from GET https://nodejs.org/en +``` + +## `fetch` + +This flag enables debug statements for the `fetch` API. + +> **Note**: statements are pretty similar to the ones in the `undici` flag, but scoped to `fetch` + +```sh +NODE_DEBUG=fetch node script.js + +FETCH 16241: connecting to nodejs.org using https:h1 +FETCH 16241: connecting to nodejs.org using https:h1 +FETCH 16241: connected to nodejs.org using https:h1 +FETCH 16241: sending request to GET https://nodejs.org/ +FETCH 16241: received response to GET https://nodejs.org/ - HTTP 307 +FETCH 16241: connecting to nodejs.org using https:h1 +FETCH 16241: trailers received from GET https://nodejs.org/ +FETCH 16241: connected to nodejs.org using https:h1 +FETCH 16241: sending request to GET https://nodejs.org/en +FETCH 16241: received response to GET https://nodejs.org/en - HTTP 200 +FETCH 16241: trailers received from GET https://nodejs.org/en +``` + +## `websocket` + +This flag enables debug statements for the `Websocket` API. + +> **Note**: statements can overlap with `UNDICI` ones if `undici` or `fetch` flag has been enabled as well. + +```sh +NODE_DEBUG=websocket node script.js + +WEBSOCKET 18309: connecting to echo.websocket.org using https:h1 +WEBSOCKET 18309: connected to echo.websocket.org using https:h1 +WEBSOCKET 18309: sending request to GET https://echo.websocket.org/ +WEBSOCKET 18309: connection opened +``` diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/DiagnosticsChannel.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/DiagnosticsChannel.md new file mode 100644 index 0000000000000000000000000000000000000000..096bd58ce298826c4a2e9398970afb515f72031b --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/DiagnosticsChannel.md @@ -0,0 +1,256 @@ +# Diagnostics Channel Support + +Stability: Experimental. + +Undici supports the [`diagnostics_channel`](https://nodejs.org/api/diagnostics_channel.html) (currently available only on Node.js v16+). +It is the preferred way to instrument Undici and retrieve internal information. + +The channels available are the following. + +## `undici:request:create` + +This message is published when a new outgoing request is created. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:request:create').subscribe(({ request }) => { + console.log('origin', request.origin) + console.log('completed', request.completed) + console.log('method', request.method) + console.log('path', request.path) + console.log('headers', request.headers) // array of strings, e.g: ['foo', 'bar'] + request.addHeader('hello', 'world') + console.log('headers', request.headers) // e.g. ['foo', 'bar', 'hello', 'world'] +}) +``` + +Note: a request is only loosely completed to a given socket. + +## `undici:request:bodyChunkSent` + +This message is published when a chunk of the request body is being sent. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:request:bodyChunkSent').subscribe(({ request, chunk }) => { + // request is the same object undici:request:create +}) +``` + +## `undici:request:bodySent` + +This message is published after the request body has been fully sent. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:request:bodySent').subscribe(({ request }) => { + // request is the same object undici:request:create +}) +``` + +## `undici:request:headers` + +This message is published after the response headers have been received. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:request:headers').subscribe(({ request, response }) => { + // request is the same object undici:request:create + console.log('statusCode', response.statusCode) + console.log(response.statusText) + // response.headers are buffers. + console.log(response.headers.map((x) => x.toString())) +}) +``` + +## `undici:request:bodyChunkReceived` + +This message is published after a chunk of the response body has been received. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:request:bodyChunkReceived').subscribe(({ request, chunk }) => { + // request is the same object undici:request:create +}) +``` + +## `undici:request:trailers` + +This message is published after the response body and trailers have been received, i.e. the response has been completed. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:request:trailers').subscribe(({ request, trailers }) => { + // request is the same object undici:request:create + console.log('completed', request.completed) + // trailers are buffers. + console.log(trailers.map((x) => x.toString())) +}) +``` + +## `undici:request:error` + +This message is published if the request is going to error, but it has not errored yet. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:request:error').subscribe(({ request, error }) => { + // request is the same object undici:request:create +}) +``` + +## `undici:client:sendHeaders` + +This message is published right before the first byte of the request is written to the socket. + +*Note*: It will publish the exact headers that will be sent to the server in raw format. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:client:sendHeaders').subscribe(({ request, headers, socket }) => { + // request is the same object undici:request:create + console.log(`Full headers list ${headers.split('\r\n')}`); +}) +``` + +## `undici:client:beforeConnect` + +This message is published before creating a new connection for **any** request. +You can not assume that this event is related to any specific request. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:client:beforeConnect').subscribe(({ connectParams, connector }) => { + // const { host, hostname, protocol, port, servername, version } = connectParams + // connector is a function that creates the socket +}) +``` + +## `undici:client:connected` + +This message is published after a connection is established. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:client:connected').subscribe(({ socket, connectParams, connector }) => { + // const { host, hostname, protocol, port, servername, version } = connectParams + // connector is a function that creates the socket +}) +``` + +## `undici:client:connectError` + +This message is published if it did not succeed to create new connection + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:client:connectError').subscribe(({ error, socket, connectParams, connector }) => { + // const { host, hostname, protocol, port, servername, version } = connectParams + // connector is a function that creates the socket + console.log(`Connect failed with ${error.message}`) +}) +``` + +## `undici:websocket:open` + +This message is published after the client has successfully connected to a server. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:websocket:open').subscribe(({ + address, // { address: string, family: string, port: number } + protocol, // string - negotiated subprotocol + extensions, // string - negotiated extensions + websocket, // WebSocket - the WebSocket instance + handshakeResponse // object - HTTP response that upgraded the connection +}) => { + console.log(address) // address, family, and port + console.log(protocol) // negotiated subprotocols + console.log(extensions) // negotiated extensions + console.log(websocket) // the WebSocket instance + + // Handshake response details + console.log(handshakeResponse.status) // 101 for successful WebSocket upgrade + console.log(handshakeResponse.statusText) // 'Switching Protocols' + console.log(handshakeResponse.headers) // Object containing response headers +}) +``` + +### Handshake Response Object + +The `handshakeResponse` object contains the HTTP response that upgraded the connection to WebSocket: + +- `status` (number): The HTTP status code (101 for successful WebSocket upgrade) +- `statusText` (string): The HTTP status message ('Switching Protocols' for successful upgrade) +- `headers` (object): The HTTP response headers from the server, including: + - `upgrade: 'websocket'` + - `connection: 'upgrade'` + - `sec-websocket-accept` and other WebSocket-related headers + +This information is particularly useful for debugging and monitoring WebSocket connections, as it provides access to the initial HTTP handshake response that established the WebSocket connection. + +## `undici:websocket:close` + +This message is published after the connection has closed. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:websocket:close').subscribe(({ websocket, code, reason }) => { + console.log(websocket) // the WebSocket instance + console.log(code) // the closing status code + console.log(reason) // the closing reason +}) +``` + +## `undici:websocket:socket_error` + +This message is published if the socket experiences an error. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:websocket:socket_error').subscribe((error) => { + console.log(error) +}) +``` + +## `undici:websocket:ping` + +This message is published after the client receives a ping frame, if the connection is not closing. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:websocket:ping').subscribe(({ payload, websocket }) => { + // a Buffer or undefined, containing the optional application data of the frame + console.log(payload) + console.log(websocket) // the WebSocket instance +}) +``` + +## `undici:websocket:pong` + +This message is published after the client receives a pong frame. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:websocket:pong').subscribe(({ payload, websocket }) => { + // a Buffer or undefined, containing the optional application data of the frame + console.log(payload) + console.log(websocket) // the WebSocket instance +}) +``` diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/Dispatcher.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/Dispatcher.md new file mode 100644 index 0000000000000000000000000000000000000000..f9eb5aee975a0ce2a232b93ab94351f0ed5cd991 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/Dispatcher.md @@ -0,0 +1,1278 @@ +# Dispatcher + +Extends: `events.EventEmitter` + +Dispatcher is the core API used to dispatch requests. + +Requests are not guaranteed to be dispatched in order of invocation. + +## Instance Methods + +### `Dispatcher.close([callback]): Promise` + +Closes the dispatcher and gracefully waits for enqueued requests to complete before resolving. + +Arguments: + +* **callback** `(error: Error | null, data: null) => void` (optional) + +Returns: `void | Promise` - Only returns a `Promise` if no `callback` argument was passed + +```js +dispatcher.close() // -> Promise +dispatcher.close(() => {}) // -> void +``` + +#### Example - Request resolves before Client closes + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('undici') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +try { + const { body } = await client.request({ + path: '/', + method: 'GET' + }) + body.setEncoding('utf8') + body.on('data', console.log) +} catch (error) {} + +await client.close() + +console.log('Client closed') +server.close() +``` + +### `Dispatcher.connect(options[, callback])` + +Starts two-way communications with the requested resource using [HTTP CONNECT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/CONNECT). + +Arguments: + +* **options** `ConnectOptions` +* **callback** `(err: Error | null, data: ConnectData | null) => void` (optional) + +Returns: `void | Promise` - Only returns a `Promise` if no `callback` argument was passed + +#### Parameter: `ConnectOptions` + +* **path** `string` +* **headers** `UndiciHeaders` (optional) - Default: `null` +* **signal** `AbortSignal | events.EventEmitter | null` (optional) - Default: `null` +* **opaque** `unknown` (optional) - This argument parameter is passed through to `ConnectData` + +#### Parameter: `ConnectData` + +* **statusCode** `number` +* **headers** `Record` +* **socket** `stream.Duplex` +* **opaque** `unknown` + +#### Example - Connect request with echo + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + throw Error('should never get here') +}).listen() + +server.on('connect', (req, socket, head) => { + socket.write('HTTP/1.1 200 Connection established\r\n\r\n') + + let data = head.toString() + socket.on('data', (buf) => { + data += buf.toString() + }) + + socket.on('end', () => { + socket.end(data) + }) +}) + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +try { + const { socket } = await client.connect({ + path: '/' + }) + const wanted = 'Body' + let data = '' + socket.on('data', d => { data += d }) + socket.on('end', () => { + console.log(`Data received: ${data.toString()} | Data wanted: ${wanted}`) + client.close() + server.close() + }) + socket.write(wanted) + socket.end() +} catch (error) { } +``` + +### `Dispatcher.destroy([error, callback]): Promise` + +Destroy the dispatcher abruptly with the given error. All the pending and running requests will be asynchronously aborted and error. Since this operation is asynchronously dispatched there might still be some progress on dispatched requests. + +Both arguments are optional; the method can be called in four different ways: + +Arguments: + +* **error** `Error | null` (optional) +* **callback** `(error: Error | null, data: null) => void` (optional) + +Returns: `void | Promise` - Only returns a `Promise` if no `callback` argument was passed + +```js +dispatcher.destroy() // -> Promise +dispatcher.destroy(new Error()) // -> Promise +dispatcher.destroy(() => {}) // -> void +dispatcher.destroy(new Error(), () => {}) // -> void +``` + +#### Example - Request is aborted when Client is destroyed + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end() +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +try { + const request = client.request({ + path: '/', + method: 'GET' + }) + client.destroy() + .then(() => { + console.log('Client destroyed') + server.close() + }) + await request +} catch (error) { + console.error(error) +} +``` + +### `Dispatcher.dispatch(options, handler)` + +This is the low level API which all the preceding APIs are implemented on top of. +This API is expected to evolve through semver-major versions and is less stable than the preceding higher level APIs. +It is primarily intended for library developers who implement higher level APIs on top of this. + +Arguments: + +* **options** `DispatchOptions` +* **handler** `DispatchHandler` + +Returns: `Boolean` - `false` if dispatcher is busy and further dispatch calls won't make any progress until the `'drain'` event has been emitted. + +#### Parameter: `DispatchOptions` + +* **origin** `string | URL` +* **path** `string` +* **method** `string` +* **reset** `boolean` (optional) - Default: `false` - If `false`, the request will attempt to create a long-living connection by sending the `connection: keep-alive` header,otherwise will attempt to close it immediately after response by sending `connection: close` within the request and closing the socket afterwards. +* **body** `string | Buffer | Uint8Array | stream.Readable | Iterable | AsyncIterable | null` (optional) - Default: `null` +* **headers** `UndiciHeaders` (optional) - Default: `null`. +* **query** `Record | null` (optional) - Default: `null` - Query string params to be embedded in the request URL. Note that both keys and values of query are encoded using `encodeURIComponent`. If for some reason you need to send them unencoded, embed query params into path directly instead. +* **idempotent** `boolean` (optional) - Default: `true` if `method` is `'HEAD'` or `'GET'` - Whether the requests can be safely retried or not. If `false` the request won't be sent until all preceding requests in the pipeline has completed. +* **blocking** `boolean` (optional) - Default: `method !== 'HEAD'` - Whether the response is expected to take a long time and would end up blocking the pipeline. When this is set to `true` further pipelining will be avoided on the same connection until headers have been received. +* **upgrade** `string | null` (optional) - Default: `null` - Upgrade the request. Should be used to specify the kind of upgrade i.e. `'Websocket'`. +* **bodyTimeout** `number | null` (optional) - The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Defaults to 300 seconds. +* **headersTimeout** `number | null` (optional) - The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers while not sending the request. Defaults to 300 seconds. +* **expectContinue** `boolean` (optional) - Default: `false` - For H2, it appends the expect: 100-continue header, and halts the request body until a 100-continue is received from the remote server + +#### Parameter: `DispatchHandler` + +* **onRequestStart** `(controller: DispatchController, context: object) => void` - Invoked before request is dispatched on socket. May be invoked multiple times when a request is retried when the request at the head of the pipeline fails. +* **onRequestUpgrade** `(controller: DispatchController, statusCode: number, headers: Record, socket: Duplex) => void` (optional) - Invoked when request is upgraded. Required if `DispatchOptions.upgrade` is defined or `DispatchOptions.method === 'CONNECT'`. +* **onResponseStart** `(controller: DispatchController, statusCode: number, headers: Record, statusMessage?: string) => void` - Invoked when statusCode and headers have been received. May be invoked multiple times due to 1xx informational headers. Not required for `upgrade` requests. +* **onResponseData** `(controller: DispatchController, chunk: Buffer) => void` - Invoked when response payload data is received. Not required for `upgrade` requests. +* **onResponseEnd** `(controller: DispatchController, trailers: Record) => void` - Invoked when response payload and trailers have been received and the request has completed. Not required for `upgrade` requests. +* **onResponseError** `(controller: DispatchController, error: Error) => void` - Invoked when an error has occurred. May not throw. + +#### Example 1 - Dispatch GET request + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +const data = [] + +client.dispatch({ + path: '/', + method: 'GET', + headers: { + 'x-foo': 'bar' + } +}, { + onConnect: () => { + console.log('Connected!') + }, + onError: (error) => { + console.error(error) + }, + onHeaders: (statusCode, headers) => { + console.log(`onHeaders | statusCode: ${statusCode} | headers: ${headers}`) + }, + onData: (chunk) => { + console.log('onData: chunk received') + data.push(chunk) + }, + onComplete: (trailers) => { + console.log(`onComplete | trailers: ${trailers}`) + const res = Buffer.concat(data).toString('utf8') + console.log(`Data: ${res}`) + client.close() + server.close() + } +}) +``` + +#### Example 2 - Dispatch Upgrade Request + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end() +}).listen() + +await once(server, 'listening') + +server.on('upgrade', (request, socket, head) => { + console.log('Node.js Server - upgrade event') + socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n') + socket.write('Upgrade: WebSocket\r\n') + socket.write('Connection: Upgrade\r\n') + socket.write('\r\n') + socket.end() +}) + +const client = new Client(`http://localhost:${server.address().port}`) + +client.dispatch({ + path: '/', + method: 'GET', + upgrade: 'websocket' +}, { + onConnect: () => { + console.log('Undici Client - onConnect') + }, + onError: (error) => { + console.log('onError') // shouldn't print + }, + onUpgrade: (statusCode, headers, socket) => { + console.log('Undici Client - onUpgrade') + console.log(`onUpgrade Headers: ${headers}`) + socket.on('data', buffer => { + console.log(buffer.toString('utf8')) + }) + socket.on('end', () => { + client.close() + server.close() + }) + socket.end() + } +}) +``` + +#### Example 3 - Dispatch POST request + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + request.on('data', (data) => { + console.log(`Request Data: ${data.toString('utf8')}`) + const body = JSON.parse(data) + body.message = 'World' + response.end(JSON.stringify(body)) + }) +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +const data = [] + +client.dispatch({ + path: '/', + method: 'POST', + headers: { + 'content-type': 'application/json' + }, + body: JSON.stringify({ message: 'Hello' }) +}, { + onConnect: () => { + console.log('Connected!') + }, + onError: (error) => { + console.error(error) + }, + onHeaders: (statusCode, headers) => { + console.log(`onHeaders | statusCode: ${statusCode} | headers: ${headers}`) + }, + onData: (chunk) => { + console.log('onData: chunk received') + data.push(chunk) + }, + onComplete: (trailers) => { + console.log(`onComplete | trailers: ${trailers}`) + const res = Buffer.concat(data).toString('utf8') + console.log(`Response Data: ${res}`) + client.close() + server.close() + } +}) +``` + +### `Dispatcher.pipeline(options, handler)` + +For easy use with [stream.pipeline](https://nodejs.org/api/stream.html#stream_stream_pipeline_source_transforms_destination_callback). The `handler` argument should return a `Readable` from which the result will be read. Usually it should just return the `body` argument unless some kind of transformation needs to be performed based on e.g. `headers` or `statusCode`. The `handler` should validate the response and save any required state. If there is an error, it should be thrown. The function returns a `Duplex` which writes to the request and reads from the response. + +Arguments: + +* **options** `PipelineOptions` +* **handler** `(data: PipelineHandlerData) => stream.Readable` + +Returns: `stream.Duplex` + +#### Parameter: PipelineOptions + +Extends: [`RequestOptions`](/docs/docs/api/Dispatcher.md#parameter-requestoptions) + +* **objectMode** `boolean` (optional) - Default: `false` - Set to `true` if the `handler` will return an object stream. + +#### Parameter: PipelineHandlerData + +* **statusCode** `number` +* **headers** `Record` +* **opaque** `unknown` +* **body** `stream.Readable` +* **context** `object` +* **onInfo** `({statusCode: number, headers: Record}) => void | null` (optional) - Default: `null` - Callback collecting all the info headers (HTTP 100-199) received. + +#### Example 1 - Pipeline Echo + +```js +import { Readable, Writable, PassThrough, pipeline } from 'stream' +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + request.pipe(response) +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +let res = '' + +pipeline( + new Readable({ + read () { + this.push(Buffer.from('undici')) + this.push(null) + } + }), + client.pipeline({ + path: '/', + method: 'GET' + }, ({ statusCode, headers, body }) => { + console.log(`response received ${statusCode}`) + console.log('headers', headers) + return pipeline(body, new PassThrough(), () => {}) + }), + new Writable({ + write (chunk, _, callback) { + res += chunk.toString() + callback() + }, + final (callback) { + console.log(`Response pipelined to writable: ${res}`) + callback() + } + }), + error => { + if (error) { + console.error(error) + } + + client.close() + server.close() + } +) +``` + +### `Dispatcher.request(options[, callback])` + +Performs a HTTP request. + +Non-idempotent requests will not be pipelined in order +to avoid indirect failures. + +Idempotent requests will be automatically retried if +they fail due to indirect failure from the request +at the head of the pipeline. This does not apply to +idempotent requests with a stream request body. + +All response bodies must always be fully consumed or destroyed. + +Arguments: + +* **options** `RequestOptions` +* **callback** `(error: Error | null, data: ResponseData) => void` (optional) + +Returns: `void | Promise` - Only returns a `Promise` if no `callback` argument was passed. + +#### Parameter: `RequestOptions` + +Extends: [`DispatchOptions`](/docs/docs/api/Dispatcher.md#parameter-dispatchoptions) + +* **opaque** `unknown` (optional) - Default: `null` - Used for passing through context to `ResponseData`. +* **signal** `AbortSignal | events.EventEmitter | null` (optional) - Default: `null`. +* **onInfo** `({statusCode: number, headers: Record}) => void | null` (optional) - Default: `null` - Callback collecting all the info headers (HTTP 100-199) received. + +The `RequestOptions.method` property should not be value `'CONNECT'`. + +#### Parameter: `ResponseData` + +* **statusCode** `number` +* **headers** `Record` - Note that all header keys are lower-cased, e.g. `content-type`. +* **body** `stream.Readable` which also implements [the body mixin from the Fetch Standard](https://fetch.spec.whatwg.org/#body-mixin). +* **trailers** `Record` - This object starts out + as empty and will be mutated to contain trailers after `body` has emitted `'end'`. +* **opaque** `unknown` +* **context** `object` + +`body` contains the following additional [body mixin](https://fetch.spec.whatwg.org/#body-mixin) methods and properties: + +* [`.arrayBuffer()`](https://fetch.spec.whatwg.org/#dom-body-arraybuffer) +* [`.blob()`](https://fetch.spec.whatwg.org/#dom-body-blob) +* [`.bytes()`](https://fetch.spec.whatwg.org/#dom-body-bytes) +* [`.json()`](https://fetch.spec.whatwg.org/#dom-body-json) +* [`.text()`](https://fetch.spec.whatwg.org/#dom-body-text) +* `body` +* `bodyUsed` + +`body` can not be consumed twice. For example, calling `text()` after `json()` throws `TypeError`. + +`body` contains the following additional extensions: + +- `dump({ limit: Integer })`, dump the response by reading up to `limit` bytes without killing the socket (optional) - Default: 262144. + +Note that body will still be a `Readable` even if it is empty, but attempting to deserialize it with `json()` will result in an exception. Recommended way to ensure there is a body to deserialize is to check if status code is not 204, and `content-type` header starts with `application/json`. + +#### Example 1 - Basic GET Request + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +try { + const { body, headers, statusCode, trailers } = await client.request({ + path: '/', + method: 'GET' + }) + console.log(`response received ${statusCode}`) + console.log('headers', headers) + body.setEncoding('utf8') + body.on('data', console.log) + body.on('error', console.error) + body.on('end', () => { + console.log('trailers', trailers) + }) + + client.close() + server.close() +} catch (error) { + console.error(error) +} +``` + +#### Example 2 - Aborting a request + +> Node.js v15+ is required to run this example + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) +const abortController = new AbortController() + +try { + client.request({ + path: '/', + method: 'GET', + signal: abortController.signal + }) +} catch (error) { + console.error(error) // should print an RequestAbortedError + client.close() + server.close() +} + +abortController.abort() +``` + +Alternatively, any `EventEmitter` that emits an `'abort'` event may be used as an abort controller: + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import EventEmitter, { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) +const ee = new EventEmitter() + +try { + client.request({ + path: '/', + method: 'GET', + signal: ee + }) +} catch (error) { + console.error(error) // should print an RequestAbortedError + client.close() + server.close() +} + +ee.emit('abort') +``` + +Destroying the request or response body will have the same effect. + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +try { + const { body } = await client.request({ + path: '/', + method: 'GET' + }) + body.destroy() +} catch (error) { + console.error(error) // should print an RequestAbortedError + client.close() + server.close() +} +``` + +#### Example 3 - Conditionally reading the body + +Remember to fully consume the body even in the case when it is not read. + +```js +const { body, statusCode } = await client.request({ + path: '/', + method: 'GET' +}) + +if (statusCode === 200) { + return await body.arrayBuffer() +} + +await body.dump() + +return null +``` + +### `Dispatcher.stream(options, factory[, callback])` + +A faster version of `Dispatcher.request`. This method expects the second argument `factory` to return a [`stream.Writable`](https://nodejs.org/api/stream.html#stream_class_stream_writable) stream which the response will be written to. This improves performance by avoiding creating an intermediate [`stream.Readable`](https://nodejs.org/api/stream.html#stream_readable_streams) stream when the user expects to directly pipe the response body to a [`stream.Writable`](https://nodejs.org/api/stream.html#stream_class_stream_writable) stream. + +As demonstrated in [Example 1 - Basic GET stream request](/docs/docs/api/Dispatcher.md#example-1-basic-get-stream-request), it is recommended to use the `option.opaque` property to avoid creating a closure for the `factory` method. This pattern works well with Node.js Web Frameworks such as [Fastify](https://fastify.io). See [Example 2 - Stream to Fastify Response](/docs/docs/api/Dispatch.md#example-2-stream-to-fastify-response) for more details. + +Arguments: + +* **options** `RequestOptions` +* **factory** `(data: StreamFactoryData) => stream.Writable` +* **callback** `(error: Error | null, data: StreamData) => void` (optional) + +Returns: `void | Promise` - Only returns a `Promise` if no `callback` argument was passed + +#### Parameter: `StreamFactoryData` + +* **statusCode** `number` +* **headers** `Record` +* **opaque** `unknown` +* **onInfo** `({statusCode: number, headers: Record}) => void | null` (optional) - Default: `null` - Callback collecting all the info headers (HTTP 100-199) received. + +#### Parameter: `StreamData` + +* **opaque** `unknown` +* **trailers** `Record` +* **context** `object` + +#### Example 1 - Basic GET stream request + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' +import { Writable } from 'stream' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +const bufs = [] + +try { + await client.stream({ + path: '/', + method: 'GET', + opaque: { bufs } + }, ({ statusCode, headers, opaque: { bufs } }) => { + console.log(`response received ${statusCode}`) + console.log('headers', headers) + return new Writable({ + write (chunk, encoding, callback) { + bufs.push(chunk) + callback() + } + }) + }) + + console.log(Buffer.concat(bufs).toString('utf-8')) + + client.close() + server.close() +} catch (error) { + console.error(error) +} +``` + +#### Example 2 - Stream to Fastify Response + +In this example, a (fake) request is made to the fastify server using `fastify.inject()`. This request then executes the fastify route handler which makes a subsequent request to the raw Node.js http server using `undici.dispatcher.stream()`. The fastify response is passed to the `opaque` option so that undici can tap into the underlying writable stream using `response.raw`. This methodology demonstrates how one could use undici and fastify together to create fast-as-possible requests from one backend server to another. + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' +import fastify from 'fastify' + +const nodeServer = createServer((request, response) => { + response.end('Hello, World! From Node.js HTTP Server') +}).listen() + +await once(nodeServer, 'listening') + +console.log('Node Server listening') + +const nodeServerUndiciClient = new Client(`http://localhost:${nodeServer.address().port}`) + +const fastifyServer = fastify() + +fastifyServer.route({ + url: '/', + method: 'GET', + handler: (request, response) => { + nodeServerUndiciClient.stream({ + path: '/', + method: 'GET', + opaque: response + }, ({ opaque }) => opaque.raw) + } +}) + +await fastifyServer.listen() + +console.log('Fastify Server listening') + +const fastifyServerUndiciClient = new Client(`http://localhost:${fastifyServer.server.address().port}`) + +try { + const { statusCode, body } = await fastifyServerUndiciClient.request({ + path: '/', + method: 'GET' + }) + + console.log(`response received ${statusCode}`) + body.setEncoding('utf8') + body.on('data', console.log) + + nodeServerUndiciClient.close() + fastifyServerUndiciClient.close() + fastifyServer.close() + nodeServer.close() +} catch (error) { } +``` + +### `Dispatcher.upgrade(options[, callback])` + +Upgrade to a different protocol. Visit [MDN - HTTP - Protocol upgrade mechanism](https://developer.mozilla.org/en-US/docs/Web/HTTP/Protocol_upgrade_mechanism) for more details. + +Arguments: + +* **options** `UpgradeOptions` + +* **callback** `(error: Error | null, data: UpgradeData) => void` (optional) + +Returns: `void | Promise` - Only returns a `Promise` if no `callback` argument was passed + +#### Parameter: `UpgradeOptions` + +* **path** `string` +* **method** `string` (optional) - Default: `'GET'` +* **headers** `UndiciHeaders` (optional) - Default: `null` +* **protocol** `string` (optional) - Default: `'Websocket'` - A string of comma separated protocols, in descending preference order. +* **signal** `AbortSignal | EventEmitter | null` (optional) - Default: `null` + +#### Parameter: `UpgradeData` + +* **headers** `http.IncomingHeaders` +* **socket** `stream.Duplex` +* **opaque** `unknown` + +#### Example 1 - Basic Upgrade Request + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.statusCode = 101 + response.setHeader('connection', 'upgrade') + response.setHeader('upgrade', request.headers.upgrade) + response.end() +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +try { + const { headers, socket } = await client.upgrade({ + path: '/', + }) + socket.on('end', () => { + console.log(`upgrade: ${headers.upgrade}`) // upgrade: Websocket + client.close() + server.close() + }) + socket.end() +} catch (error) { + console.error(error) + client.close() + server.close() +} +``` + +### `Dispatcher.compose(interceptors[, interceptor])` + +Compose a new dispatcher from the current dispatcher and the given interceptors. + +> _Notes_: +> - The order of the interceptors matters. The last interceptor will be the first to be called. +> - It is important to note that the `interceptor` function should return a function that follows the `Dispatcher.dispatch` signature. +> - Any fork of the chain of `interceptors` can lead to unexpected results. +> +> **Interceptor Stack Visualization:** +> ``` +> compose([interceptor1, interceptor2, interceptor3]) +> +> Request Flow: +> ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ +> │ Request │───▶│interceptor3 │───▶│interceptor2 │───▶│interceptor1 │───▶│ dispatcher │ +> └─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘ │ .dispatch │ +> ▲ ▲ ▲ └─────────────┘ +> │ │ │ ▲ +> (called first) (called second) (called last) │ +> │ +> ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ +> │ Response │◀───│interceptor3 │◀───│interceptor2 │◀───│interceptor1 │◀─────────┘ +> └─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘ +> +> The interceptors are composed in reverse order due to function composition. +> ``` + +Arguments: + +* **interceptors** `Interceptor[interceptor[]]`: It is an array of `Interceptor` functions passed as only argument, or several interceptors passed as separate arguments. + +Returns: `Dispatcher`. + +#### Parameter: `Interceptor` + +A function that takes a `dispatch` method and returns a `dispatch`-like function. + +#### Example 1 - Basic Compose + +```js +const { Client, RedirectHandler } = require('undici') + +const redirectInterceptor = dispatch => { + return (opts, handler) => { + const { maxRedirections } = opts + + if (!maxRedirections) { + return dispatch(opts, handler) + } + + const redirectHandler = new RedirectHandler( + dispatch, + maxRedirections, + opts, + handler + ) + opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting. + return dispatch(opts, redirectHandler) + } +} + +const client = new Client('http://localhost:3000') + .compose(redirectInterceptor) + +await client.request({ path: '/', method: 'GET' }) +``` + +#### Example 2 - Chained Compose + +```js +const { Client, RedirectHandler, RetryHandler } = require('undici') + +const redirectInterceptor = dispatch => { + return (opts, handler) => { + const { maxRedirections } = opts + + if (!maxRedirections) { + return dispatch(opts, handler) + } + + const redirectHandler = new RedirectHandler( + dispatch, + maxRedirections, + opts, + handler + ) + opts = { ...opts, maxRedirections: 0 } + return dispatch(opts, redirectHandler) + } +} + +const retryInterceptor = dispatch => { + return function retryInterceptor (opts, handler) { + return dispatch( + opts, + new RetryHandler(opts, { + handler, + dispatch + }) + ) + } +} + +const client = new Client('http://localhost:3000') + .compose(redirectInterceptor) + .compose(retryInterceptor) + +await client.request({ path: '/', method: 'GET' }) +``` + +#### Pre-built interceptors + +##### `redirect` + +The `redirect` interceptor allows you to customize the way your dispatcher handles redirects. + +It accepts the same arguments as the [`RedirectHandler` constructor](/docs/docs/api/RedirectHandler.md). + +**Example - Basic Redirect Interceptor** + +```js +const { Client, interceptors } = require("undici"); +const { redirect } = interceptors; + +const client = new Client("http://example.com").compose( + redirect({ maxRedirections: 3, throwOnMaxRedirects: true }) +); +client.request({ path: "/" }) +``` + +##### `retry` + +The `retry` interceptor allows you to customize the way your dispatcher handles retries. + +It accepts the same arguments as the [`RetryHandler` constructor](/docs/docs/api/RetryHandler.md). + +**Example - Basic Redirect Interceptor** + +```js +const { Client, interceptors } = require("undici"); +const { retry } = interceptors; + +const client = new Client("http://example.com").compose( + retry({ + maxRetries: 3, + minTimeout: 1000, + maxTimeout: 10000, + timeoutFactor: 2, + retryAfter: true, + }) +); +``` + +##### `dump` + +The `dump` interceptor enables you to dump the response body from a request upon a given limit. + +**Options** +- `maxSize` - The maximum size (in bytes) of the response body to dump. If the size of the request's body exceeds this value then the connection will be closed. Default: `1048576`. + +> The `Dispatcher#options` also gets extended with the options `dumpMaxSize`, `abortOnDumped`, and `waitForTrailers` which can be used to configure the interceptor at a request-per-request basis. + +**Example - Basic Dump Interceptor** + +```js +const { Client, interceptors } = require("undici"); +const { dump } = interceptors; + +const client = new Client("http://example.com").compose( + dump({ + maxSize: 1024, + }) +); + +// or +client.dispatch( + { + path: "/", + method: "GET", + dumpMaxSize: 1024, + }, + handler +); +``` + +##### `dns` + +The `dns` interceptor enables you to cache DNS lookups for a given duration, per origin. + +>It is well suited for scenarios where you want to cache DNS lookups to avoid the overhead of resolving the same domain multiple times + +**Options** +- `maxTTL` - The maximum time-to-live (in milliseconds) of the DNS cache. It should be a positive integer. Default: `10000`. + - Set `0` to disable TTL. +- `maxItems` - The maximum number of items to cache. It should be a positive integer. Default: `Infinity`. +- `dualStack` - Whether to resolve both IPv4 and IPv6 addresses. Default: `true`. + - It will also attempt a happy-eyeballs-like approach to connect to the available addresses in case of a connection failure. +- `affinity` - Whether to use IPv4 or IPv6 addresses. Default: `4`. + - It can be either `'4` or `6`. + - It will only take effect if `dualStack` is `false`. +- `lookup: (hostname: string, options: LookupOptions, callback: (err: NodeJS.ErrnoException | null, addresses: DNSInterceptorRecord[]) => void) => void` - Custom lookup function. Default: `dns.lookup`. + - For more info see [dns.lookup](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback). +- `pick: (origin: URL, records: DNSInterceptorRecords, affinity: 4 | 6) => DNSInterceptorRecord` - Custom pick function. Default: `RoundRobin`. + - The function should return a single record from the records array. + - By default a simplified version of Round Robin is used. + - The `records` property can be mutated to store the state of the balancing algorithm. + +> The `Dispatcher#options` also gets extended with the options `dns.affinity`, `dns.dualStack`, `dns.lookup` and `dns.pick` which can be used to configure the interceptor at a request-per-request basis. + + +**DNSInterceptorRecord** +It represents a DNS record. +- `family` - (`number`) The IP family of the address. It can be either `4` or `6`. +- `address` - (`string`) The IP address. + +**DNSInterceptorOriginRecords** +It represents a map of DNS IP addresses records for a single origin. +- `4.ips` - (`DNSInterceptorRecord[] | null`) The IPv4 addresses. +- `6.ips` - (`DNSInterceptorRecord[] | null`) The IPv6 addresses. + +**Example - Basic DNS Interceptor** + +```js +const { Client, interceptors } = require("undici"); +const { dns } = interceptors; + +const client = new Agent().compose([ + dns({ ...opts }) +]) + +const response = await client.request({ + origin: `http://localhost:3030`, + ...requestOpts +}) +``` + +##### `responseError` + +The `responseError` interceptor throws an error for responses with status code errors (>= 400). + +**Example** + +```js +const { Client, interceptors } = require("undici"); +const { responseError } = interceptors; + +const client = new Client("http://example.com").compose( + responseError() +); + +// Will throw a ResponseError for status codes >= 400 +await client.request({ + method: "GET", + path: "/" +}); +``` + +##### `decompress` + +⚠️ The decompress interceptor is experimental and subject to change. + +The `decompress` interceptor automatically decompresses response bodies that are compressed with gzip, deflate, brotli, or zstd compression. It removes the `content-encoding` and `content-length` headers from decompressed responses and supports RFC-9110 compliant multiple encodings. + +**Options** + +- `skipErrorResponses` - Whether to skip decompression for error responses (status codes >= 400). Default: `true`. +- `skipStatusCodes` - Array of status codes to skip decompression for. Default: `[204, 304]`. + +**Example - Basic Decompress Interceptor** + +```js +const { Client, interceptors } = require("undici"); +const { decompress } = interceptors; + +const client = new Client("http://example.com").compose( + decompress() +); + +// Automatically decompresses gzip/deflate/brotli/zstd responses +const response = await client.request({ + method: "GET", + path: "/" +}); +``` + +**Example - Custom Options** + +```js +const { Client, interceptors } = require("undici"); +const { decompress } = interceptors; + +const client = new Client("http://example.com").compose( + decompress({ + skipErrorResponses: false, // Decompress 5xx responses + skipStatusCodes: [204, 304, 201] // Skip these status codes + }) +); +``` + +**Supported Encodings** + +- `gzip` / `x-gzip` - GZIP compression +- `deflate` / `x-compress` - DEFLATE compression +- `br` - Brotli compression +- `zstd` - Zstandard compression +- Multiple encodings (e.g., `gzip, deflate`) are supported per RFC-9110 + +**Behavior** + +- Skips decompression for status codes < 200 or >= 400 (configurable) +- Skips decompression for 204 No Content and 304 Not Modified by default +- Removes `content-encoding` and `content-length` headers when decompressing +- Passes through unsupported encodings unchanged +- Handles case-insensitive encoding names +- Supports streaming decompression without buffering + +##### `Cache Interceptor` + +The `cache` interceptor implements client-side response caching as described in +[RFC9111](https://www.rfc-editor.org/rfc/rfc9111.html). + +**Options** + +- `store` - The [`CacheStore`](/docs/docs/api/CacheStore.md) to store and retrieve responses from. Default is [`MemoryCacheStore`](/docs/docs/api/CacheStore.md#memorycachestore). +- `methods` - The [**safe** HTTP methods](https://www.rfc-editor.org/rfc/rfc9110#section-9.2.1) to cache the response of. +- `cacheByDefault` - The default expiration time to cache responses by if they don't have an explicit expiration and cannot have an heuristic expiry computed. If this isn't present, responses neither with an explicit expiration nor heuristically cacheable will not be cached. Default `undefined`. +- `type` - The [type of cache](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Caching#types_of_caches) for Undici to act as. Can be `shared` or `private`. Default `shared`. `private` implies privately cacheable responses will be cached and potentially shared with other users of your application. + +## Instance Events + +### Event: `'connect'` + +Parameters: + +* **origin** `URL` +* **targets** `Array` + +### Event: `'disconnect'` + +Parameters: + +* **origin** `URL` +* **targets** `Array` +* **error** `Error` + +Emitted when the dispatcher has been disconnected from the origin. + +> **Note**: For HTTP/2, this event is also emitted when the dispatcher has received the [GOAWAY Frame](https://webconcepts.info/concepts/http2-frame-type/0x7) with an Error with the message `HTTP/2: "GOAWAY" frame received` and the code `UND_ERR_INFO`. +> Due to nature of the protocol of using binary frames, it is possible that requests gets hanging as a frame can be received between the `HEADER` and `DATA` frames. +> It is recommended to handle this event and close the dispatcher to create a new HTTP/2 session. + +### Event: `'connectionError'` + +Parameters: + +* **origin** `URL` +* **targets** `Array` +* **error** `Error` + +Emitted when dispatcher fails to connect to +origin. + +### Event: `'drain'` + +Parameters: + +* **origin** `URL` + +Emitted when dispatcher is no longer busy. + +## Parameter: `UndiciHeaders` + +* `Record | string[] | Iterable<[string, string | string[] | undefined]> | null` + +Header arguments such as `options.headers` in [`Client.dispatch`](/docs/docs/api/Client.md#clientdispatchoptions-handlers) can be specified in three forms: +* As an object specified by the `Record` (`IncomingHttpHeaders`) type. +* As an array of strings. An array representation of a header list must have an even length, or an `InvalidArgumentError` will be thrown. +* As an iterable that can encompass `Headers`, `Map`, or a custom iterator returning key-value pairs. +Keys are lowercase and values are not modified. + +Response headers will derive a `host` from the `url` of the [Client](/docs/docs/api/Client.md#class-client) instance if no `host` header was previously specified. + +### Example 1 - Object + +```js +{ + 'content-length': '123', + 'content-type': 'text/plain', + connection: 'keep-alive', + host: 'mysite.com', + accept: '*/*' +} +``` + +### Example 2 - Array + +```js +[ + 'content-length', '123', + 'content-type', 'text/plain', + 'connection', 'keep-alive', + 'host', 'mysite.com', + 'accept', '*/*' +] +``` + +### Example 3 - Iterable + +```js +new Headers({ + 'content-length': '123', + 'content-type': 'text/plain', + connection: 'keep-alive', + host: 'mysite.com', + accept: '*/*' +}) +``` +or +```js +new Map([ + ['content-length', '123'], + ['content-type', 'text/plain'], + ['connection', 'keep-alive'], + ['host', 'mysite.com'], + ['accept', '*/*'] +]) +``` +or +```js +{ + *[Symbol.iterator] () { + yield ['content-length', '123'] + yield ['content-type', 'text/plain'] + yield ['connection', 'keep-alive'] + yield ['host', 'mysite.com'] + yield ['accept', '*/*'] + } +} +``` diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/EnvHttpProxyAgent.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/EnvHttpProxyAgent.md new file mode 100644 index 0000000000000000000000000000000000000000..adc2a24245762dbf8ec84909f0823f38f8e2e7c4 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/EnvHttpProxyAgent.md @@ -0,0 +1,159 @@ +# Class: EnvHttpProxyAgent + +Extends: `undici.Dispatcher` + +EnvHttpProxyAgent automatically reads the proxy configuration from the environment variables `http_proxy`, `https_proxy`, and `no_proxy` and sets up the proxy agents accordingly. When `http_proxy` and `https_proxy` are set, `http_proxy` is used for HTTP requests and `https_proxy` is used for HTTPS requests. If only `http_proxy` is set, `http_proxy` is used for both HTTP and HTTPS requests. If only `https_proxy` is set, it is only used for HTTPS requests. + +`no_proxy` is a comma or space-separated list of hostnames that should not be proxied. The list may contain leading wildcard characters (`*`). If `no_proxy` is set, the EnvHttpProxyAgent will bypass the proxy for requests to hosts that match the list. If `no_proxy` is set to `"*"`, the EnvHttpProxyAgent will bypass the proxy for all requests. + +Uppercase environment variables are also supported: `HTTP_PROXY`, `HTTPS_PROXY`, and `NO_PROXY`. However, if both the lowercase and uppercase environment variables are set, the uppercase environment variables will be ignored. + +## `new EnvHttpProxyAgent([options])` + +Arguments: + +* **options** `EnvHttpProxyAgentOptions` (optional) - extends the `Agent` options. + +Returns: `EnvHttpProxyAgent` + +### Parameter: `EnvHttpProxyAgentOptions` + +Extends: [`AgentOptions`](/docs/docs/api/Agent.md#parameter-agentoptions) + +* **httpProxy** `string` (optional) - When set, it will override the `HTTP_PROXY` environment variable. +* **httpsProxy** `string` (optional) - When set, it will override the `HTTPS_PROXY` environment variable. +* **noProxy** `string` (optional) - When set, it will override the `NO_PROXY` environment variable. + +Examples: + +```js +import { EnvHttpProxyAgent } from 'undici' + +const envHttpProxyAgent = new EnvHttpProxyAgent() +// or +const envHttpProxyAgent = new EnvHttpProxyAgent({ httpProxy: 'my.proxy.server:8080', httpsProxy: 'my.proxy.server:8443', noProxy: 'localhost' }) +``` + +#### Example - EnvHttpProxyAgent instantiation + +This will instantiate the EnvHttpProxyAgent. It will not do anything until registered as the agent to use with requests. + +```js +import { EnvHttpProxyAgent } from 'undici' + +const envHttpProxyAgent = new EnvHttpProxyAgent() +``` + +#### Example - Basic Proxy Fetch with global agent dispatcher + +```js +import { setGlobalDispatcher, fetch, EnvHttpProxyAgent } from 'undici' + +const envHttpProxyAgent = new EnvHttpProxyAgent() +setGlobalDispatcher(envHttpProxyAgent) + +const { status, json } = await fetch('http://localhost:3000/foo') + +console.log('response received', status) // response received 200 + +const data = await json() // data { foo: "bar" } +``` + +#### Example - Basic Proxy Request with global agent dispatcher + +```js +import { setGlobalDispatcher, request, EnvHttpProxyAgent } from 'undici' + +const envHttpProxyAgent = new EnvHttpProxyAgent() +setGlobalDispatcher(envHttpProxyAgent) + +const { statusCode, body } = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Proxy Request with local agent dispatcher + +```js +import { EnvHttpProxyAgent, request } from 'undici' + +const envHttpProxyAgent = new EnvHttpProxyAgent() + +const { + statusCode, + body +} = await request('http://localhost:3000/foo', { dispatcher: envHttpProxyAgent }) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Proxy Fetch with local agent dispatcher + +```js +import { EnvHttpProxyAgent, fetch } from 'undici' + +const envHttpProxyAgent = new EnvHttpProxyAgent() + +const { + status, + json +} = await fetch('http://localhost:3000/foo', { dispatcher: envHttpProxyAgent }) + +console.log('response received', status) // response received 200 + +const data = await json() // data { foo: "bar" } +``` + +## Instance Methods + +### `EnvHttpProxyAgent.close([callback])` + +Implements [`Dispatcher.close([callback])`](/docs/docs/api/Dispatcher.md#dispatcherclosecallback-promise). + +### `EnvHttpProxyAgent.destroy([error, callback])` + +Implements [`Dispatcher.destroy([error, callback])`](/docs/docs/api/Dispatcher.md#dispatcherdestroyerror-callback-promise). + +### `EnvHttpProxyAgent.dispatch(options, handler: AgentDispatchOptions)` + +Implements [`Dispatcher.dispatch(options, handler)`](/docs/docs/api/Dispatcher.md#dispatcherdispatchoptions-handler). + +#### Parameter: `AgentDispatchOptions` + +Extends: [`DispatchOptions`](/docs/docs/api/Dispatcher.md#parameter-dispatchoptions) + +* **origin** `string | URL` + +Implements [`Dispatcher.destroy([error, callback])`](/docs/docs/api/Dispatcher.md#dispatcherdestroyerror-callback-promise). + +### `EnvHttpProxyAgent.connect(options[, callback])` + +See [`Dispatcher.connect(options[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherconnectoptions-callback). + +### `EnvHttpProxyAgent.dispatch(options, handler)` + +Implements [`Dispatcher.dispatch(options, handler)`](/docs/docs/api/Dispatcher.md#dispatcherdispatchoptions-handler). + +### `EnvHttpProxyAgent.pipeline(options, handler)` + +See [`Dispatcher.pipeline(options, handler)`](/docs/docs/api/Dispatcher.md#dispatcherpipelineoptions-handler). + +### `EnvHttpProxyAgent.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](/docs/docs/api/Dispatcher.md#dispatcherrequestoptions-callback). + +### `EnvHttpProxyAgent.stream(options, factory[, callback])` + +See [`Dispatcher.stream(options, factory[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherstreamoptions-factory-callback). + +### `EnvHttpProxyAgent.upgrade(options[, callback])` + +See [`Dispatcher.upgrade(options[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherupgradeoptions-callback). diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/Errors.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/Errors.md new file mode 100644 index 0000000000000000000000000000000000000000..dfba3b39ce02cdd8583b164a551ebbec9e6606b3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/Errors.md @@ -0,0 +1,49 @@ +# Errors + +Undici exposes a variety of error objects that you can use to enhance your error handling. +You can find all the error objects inside the `errors` key. + +```js +import { errors } from 'undici' +``` + +| Error | Error Codes | Description | +| ------------------------------------ | ------------------------------------- | ------------------------------------------------------------------------- | +| `UndiciError` | `UND_ERR` | all errors below are extended from `UndiciError`. | +| `ConnectTimeoutError` | `UND_ERR_CONNECT_TIMEOUT` | socket is destroyed due to connect timeout. | +| `HeadersTimeoutError` | `UND_ERR_HEADERS_TIMEOUT` | socket is destroyed due to headers timeout. | +| `HeadersOverflowError` | `UND_ERR_HEADERS_OVERFLOW` | socket is destroyed due to headers' max size being exceeded. | +| `BodyTimeoutError` | `UND_ERR_BODY_TIMEOUT` | socket is destroyed due to body timeout. | +| `ResponseStatusCodeError` | `UND_ERR_RESPONSE_STATUS_CODE` | an error is thrown when `throwOnError` is `true` for status codes >= 400. | +| `InvalidArgumentError` | `UND_ERR_INVALID_ARG` | passed an invalid argument. | +| `InvalidReturnValueError` | `UND_ERR_INVALID_RETURN_VALUE` | returned an invalid value. | +| `RequestAbortedError` | `UND_ERR_ABORTED` | the request has been aborted by the user | +| `ClientDestroyedError` | `UND_ERR_DESTROYED` | trying to use a destroyed client. | +| `ClientClosedError` | `UND_ERR_CLOSED` | trying to use a closed client. | +| `SocketError` | `UND_ERR_SOCKET` | there is an error with the socket. | +| `NotSupportedError` | `UND_ERR_NOT_SUPPORTED` | encountered unsupported functionality. | +| `RequestContentLengthMismatchError` | `UND_ERR_REQ_CONTENT_LENGTH_MISMATCH` | request body does not match content-length header | +| `ResponseContentLengthMismatchError` | `UND_ERR_RES_CONTENT_LENGTH_MISMATCH` | response body does not match content-length header | +| `InformationalError` | `UND_ERR_INFO` | expected error with reason | +| `ResponseExceededMaxSizeError` | `UND_ERR_RES_EXCEEDED_MAX_SIZE` | response body exceed the max size allowed | +| `SecureProxyConnectionError` | `UND_ERR_PRX_TLS` | tls connection to a proxy failed | + +Be aware of the possible difference between the global dispatcher version and the actual undici version you might be using. We recommend to avoid the check `instanceof errors.UndiciError` and seek for the `error.code === ''` instead to avoid inconsistencies. +### `SocketError` + +The `SocketError` has a `.socket` property which holds socket metadata: + +```ts +interface SocketInfo { + localAddress?: string + localPort?: number + remoteAddress?: string + remotePort?: number + remoteFamily?: string + timeout?: number + bytesWritten?: number + bytesRead?: number +} +``` + +Be aware that in some cases the `.socket` property can be `null`. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/EventSource.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/EventSource.md new file mode 100644 index 0000000000000000000000000000000000000000..8244aa77ed9426c3acb7d8a4fa4384fb269a0f18 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/EventSource.md @@ -0,0 +1,45 @@ +# EventSource + +> ⚠️ Warning: the EventSource API is experimental. + +Undici exposes a WHATWG spec-compliant implementation of [EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) +for [Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events). + +## Instantiating EventSource + +Undici exports a EventSource class. You can instantiate the EventSource as +follows: + +```mjs +import { EventSource } from 'undici' + +const eventSource = new EventSource('http://localhost:3000') +eventSource.onmessage = (event) => { + console.log(event.data) +} +``` + +## Using a custom Dispatcher + +undici allows you to set your own Dispatcher in the EventSource constructor. + +An example which allows you to modify the request headers is: + +```mjs +import { EventSource, Agent } from 'undici' + +class CustomHeaderAgent extends Agent { + dispatch (opts) { + opts.headers['x-custom-header'] = 'hello world' + return super.dispatch(...arguments) + } +} + +const eventSource = new EventSource('http://localhost:3000', { + dispatcher: new CustomHeaderAgent() +}) + +``` + +More information about the EventSource API can be found on +[MDN](https://developer.mozilla.org/en-US/docs/Web/API/EventSource). diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/Fetch.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/Fetch.md new file mode 100644 index 0000000000000000000000000000000000000000..00c349847dcd333ecec3712ef676b95714ee1338 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/Fetch.md @@ -0,0 +1,52 @@ +# Fetch + +Undici exposes a fetch() method starts the process of fetching a resource from the network. + +Documentation and examples can be found on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/fetch). + +## FormData + +This API is implemented as per the standard, you can find documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/FormData). + +If any parameters are passed to the FormData constructor other than `undefined`, an error will be thrown. Other parameters are ignored. + +## Response + +This API is implemented as per the standard, you can find documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Response) + +## Request + +This API is implemented as per the standard, you can find documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Request) + +## Header + +This API is implemented as per the standard, you can find documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Headers) + +# Body Mixins + +`Response` and `Request` body inherit body mixin methods. These methods include: + +- [`.arrayBuffer()`](https://fetch.spec.whatwg.org/#dom-body-arraybuffer) +- [`.blob()`](https://fetch.spec.whatwg.org/#dom-body-blob) +- [`.bytes()`](https://fetch.spec.whatwg.org/#dom-body-bytes) +- [`.formData()`](https://fetch.spec.whatwg.org/#dom-body-formdata) +- [`.json()`](https://fetch.spec.whatwg.org/#dom-body-json) +- [`.text()`](https://fetch.spec.whatwg.org/#dom-body-text) + +There is an ongoing discussion regarding `.formData()` and its usefulness and performance in server environments. It is recommended to use a dedicated library for parsing `multipart/form-data` bodies, such as [Busboy](https://www.npmjs.com/package/busboy) or [@fastify/busboy](https://www.npmjs.com/package/@fastify/busboy). + +These libraries can be interfaced with fetch with the following example code: + +```mjs +import { Busboy } from '@fastify/busboy' +import { Readable } from 'node:stream' + +const response = await fetch('...') +const busboy = new Busboy({ + headers: { + 'content-type': response.headers.get('content-type') + } +}) + +Readable.fromWeb(response.body).pipe(busboy) +``` diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/GlobalInstallation.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/GlobalInstallation.md new file mode 100644 index 0000000000000000000000000000000000000000..7e4529d8f1967b0e053dbde0b853154eb82102b0 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/GlobalInstallation.md @@ -0,0 +1,91 @@ +# Global Installation + +Undici provides an `install()` function to add all WHATWG fetch classes to `globalThis`, making them available globally without requiring imports. + +## `install()` + +Install all WHATWG fetch classes globally on `globalThis`. + +**Example:** + +```js +import { install } from 'undici' + +// Install all WHATWG fetch classes globally +install() + +// Now you can use fetch classes globally without importing +const response = await fetch('https://api.example.com/data') +const data = await response.json() + +// All classes are available globally: +const headers = new Headers([['content-type', 'application/json']]) +const request = new Request('https://example.com') +const formData = new FormData() +const ws = new WebSocket('wss://example.com') +const eventSource = new EventSource('https://example.com/events') +``` + +## Installed Classes + +The `install()` function adds the following classes to `globalThis`: + +| Class | Description | +|-------|-------------| +| `fetch` | The fetch function for making HTTP requests | +| `Headers` | HTTP headers management | +| `Response` | HTTP response representation | +| `Request` | HTTP request representation | +| `FormData` | Form data handling | +| `WebSocket` | WebSocket client | +| `CloseEvent` | WebSocket close event | +| `ErrorEvent` | WebSocket error event | +| `MessageEvent` | WebSocket message event | +| `EventSource` | Server-sent events client | + +## Use Cases + +Global installation is useful for: + +- **Polyfilling environments** that don't have native fetch support +- **Ensuring consistent behavior** across different Node.js versions +- **Library compatibility** when third-party libraries expect global fetch +- **Migration scenarios** where you want to replace built-in implementations +- **Testing environments** where you need predictable fetch behavior + +## Example: Polyfilling an Environment + +```js +import { install } from 'undici' + +// Check if fetch is available and install if needed +if (typeof globalThis.fetch === 'undefined') { + install() + console.log('Undici fetch installed globally') +} + +// Now fetch is guaranteed to be available +const response = await fetch('https://api.example.com') +``` + +## Example: Testing Environment + +```js +import { install } from 'undici' + +// In test setup, ensure consistent fetch behavior +install() + +// Now all tests use undici's implementations +test('fetch API test', async () => { + const response = await fetch('https://example.com') + expect(response).toBeInstanceOf(Response) +}) +``` + +## Notes + +- The `install()` function overwrites any existing global implementations +- Classes installed are undici's implementations, not Node.js built-ins +- This provides access to undici's latest features and performance improvements +- The global installation persists for the lifetime of the process \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/H2CClient.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/H2CClient.md new file mode 100644 index 0000000000000000000000000000000000000000..c9bbb3f17e4d6325a607f61fb64509224da9d936 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/H2CClient.md @@ -0,0 +1,262 @@ +# Class: H2CClient + +Extends: `undici.Dispatcher` + +A basic H2C client. + +**Example** + +```js +const { createServer } = require('node:http2') +const { once } = require('node:events') +const { H2CClient } = require('undici') + +const server = createServer((req, res) => { + res.writeHead(200) + res.end('Hello, world!') +}) + +server.listen() +once(server, 'listening').then(() => { + const client = new H2CClient(`http://localhost:${server.address().port}/`) + + const response = await client.request({ path: '/', method: 'GET' }) + console.log(response.statusCode) // 200 + response.body.text.then((text) => { + console.log(text) // Hello, world! + }) +}) +``` + +## `new H2CClient(url[, options])` + +Arguments: + +- **url** `URL | string` - Should only include the **protocol, hostname, and port**. It only supports `http` protocol. +- **options** `H2CClientOptions` (optional) + +Returns: `H2CClient` + +### Parameter: `H2CClientOptions` + +- **bodyTimeout** `number | null` (optional) - Default: `300e3` - The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Defaults to 300 seconds. Please note the `timeout` will be reset if you keep writing data to the socket everytime. +- **headersTimeout** `number | null` (optional) - Default: `300e3` - The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers while not sending the request. Defaults to 300 seconds. +- **keepAliveMaxTimeout** `number | null` (optional) - Default: `600e3` - The maximum allowed `keepAliveTimeout`, in milliseconds, when overridden by _keep-alive_ hints from the server. Defaults to 10 minutes. +- **keepAliveTimeout** `number | null` (optional) - Default: `4e3` - The timeout, in milliseconds, after which a socket without active requests will time out. Monitors time between activity on a connected socket. This value may be overridden by _keep-alive_ hints from the server. See [MDN: HTTP - Headers - Keep-Alive directives](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Keep-Alive#directives) for more details. Defaults to 4 seconds. +- **keepAliveTimeoutThreshold** `number | null` (optional) - Default: `2e3` - A number of milliseconds subtracted from server _keep-alive_ hints when overriding `keepAliveTimeout` to account for timing inaccuracies caused by e.g. transport latency. Defaults to 2 seconds. +- **maxHeaderSize** `number | null` (optional) - Default: `--max-http-header-size` or `16384` - The maximum length of request headers in bytes. Defaults to Node.js' --max-http-header-size or 16KiB. +- **maxResponseSize** `number | null` (optional) - Default: `-1` - The maximum length of response body in bytes. Set to `-1` to disable. +- **maxConcurrentStreams**: `number` - Default: `100`. Dictates the maximum number of concurrent streams for a single H2 session. It can be overridden by a SETTINGS remote frame. +- **pipelining** `number | null` (optional) - Default to `maxConcurrentStreams` - The amount of concurrent requests sent over a single HTTP/2 session in accordance with [RFC-7540](https://httpwg.org/specs/rfc7540.html#StreamsLayer) Stream specification. Streams can be closed up by remote server at any time. +- **connect** `ConnectOptions | null` (optional) - Default: `null`. +- **strictContentLength** `Boolean` (optional) - Default: `true` - Whether to treat request content length mismatches as errors. If true, an error is thrown when the request content-length header doesn't match the length of the request body. +- **autoSelectFamily**: `boolean` (optional) - Default: depends on local Node version, on Node 18.13.0 and above is `false`. Enables a family autodetection algorithm that loosely implements section 5 of [RFC 8305](https://tools.ietf.org/html/rfc8305#section-5). See [here](https://nodejs.org/api/net.html#socketconnectoptions-connectlistener) for more details. This option is ignored if not supported by the current Node version. +- **autoSelectFamilyAttemptTimeout**: `number` - Default: depends on local Node version, on Node 18.13.0 and above is `250`. The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option. See [here](https://nodejs.org/api/net.html#socketconnectoptions-connectlistener) for more details. + +#### Parameter: `H2CConnectOptions` + +- **socketPath** `string | null` (optional) - Default: `null` - An IPC endpoint, either Unix domain socket or Windows named pipe. +- **timeout** `number | null` (optional) - In milliseconds, Default `10e3`. +- **servername** `string | null` (optional) +- **keepAlive** `boolean | null` (optional) - Default: `true` - TCP keep-alive enabled +- **keepAliveInitialDelay** `number | null` (optional) - Default: `60000` - TCP keep-alive interval for the socket in milliseconds + +### Example - Basic Client instantiation + +This will instantiate the undici H2CClient, but it will not connect to the origin until something is queued. Consider using `client.connect` to prematurely connect to the origin, or just call `client.request`. + +```js +"use strict"; +import { H2CClient } from "undici"; + +const client = new H2CClient("http://localhost:3000"); +``` + +## Instance Methods + +### `H2CClient.close([callback])` + +Implements [`Dispatcher.close([callback])`](/docs/docs/api/Dispatcher.md#dispatcherclosecallback-promise). + +### `H2CClient.destroy([error, callback])` + +Implements [`Dispatcher.destroy([error, callback])`](/docs/docs/api/Dispatcher.md#dispatcherdestroyerror-callback-promise). + +Waits until socket is closed before invoking the callback (or returning a promise if no callback is provided). + +### `H2CClient.connect(options[, callback])` + +See [`Dispatcher.connect(options[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherconnectoptions-callback). + +### `H2CClient.dispatch(options, handlers)` + +Implements [`Dispatcher.dispatch(options, handlers)`](/docs/docs/api/Dispatcher.md#dispatcherdispatchoptions-handler). + +### `H2CClient.pipeline(options, handler)` + +See [`Dispatcher.pipeline(options, handler)`](/docs/docs/api/Dispatcher.md#dispatcherpipelineoptions-handler). + +### `H2CClient.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](/docs/docs/api/Dispatcher.md#dispatcherrequestoptions-callback). + +### `H2CClient.stream(options, factory[, callback])` + +See [`Dispatcher.stream(options, factory[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherstreamoptions-factory-callback). + +### `H2CClient.upgrade(options[, callback])` + +See [`Dispatcher.upgrade(options[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherupgradeoptions-callback). + +## Instance Properties + +### `H2CClient.closed` + +- `boolean` + +`true` after `H2CClient.close()` has been called. + +### `H2CClient.destroyed` + +- `boolean` + +`true` after `client.destroyed()` has been called or `client.close()` has been called and the client shutdown has completed. + +### `H2CClient.pipelining` + +- `number` + +Property to get and set the pipelining factor. + +## Instance Events + +### Event: `'connect'` + +See [Dispatcher Event: `'connect'`](/docs/docs/api/Dispatcher.md#event-connect). + +Parameters: + +- **origin** `URL` +- **targets** `Array` + +Emitted when a socket has been created and connected. The client will connect once `client.size > 0`. + +#### Example - Client connect event + +```js +import { createServer } from "node:http2"; +import { H2CClient } from "undici"; +import { once } from "events"; + +const server = createServer((request, response) => { + response.end("Hello, World!"); +}).listen(); + +await once(server, "listening"); + +const client = new H2CClient(`http://localhost:${server.address().port}`); + +client.on("connect", (origin) => { + console.log(`Connected to ${origin}`); // should print before the request body statement +}); + +try { + const { body } = await client.request({ + path: "/", + method: "GET", + }); + body.setEncoding("utf-8"); + body.on("data", console.log); + client.close(); + server.close(); +} catch (error) { + console.error(error); + client.close(); + server.close(); +} +``` + +### Event: `'disconnect'` + +See [Dispatcher Event: `'disconnect'`](/docs/docs/api/Dispatcher.md#event-disconnect). + +Parameters: + +- **origin** `URL` +- **targets** `Array` +- **error** `Error` + +Emitted when socket has disconnected. The error argument of the event is the error which caused the socket to disconnect. The client will reconnect if or once `client.size > 0`. + +#### Example - Client disconnect event + +```js +import { createServer } from "node:http2"; +import { H2CClient } from "undici"; +import { once } from "events"; + +const server = createServer((request, response) => { + response.destroy(); +}).listen(); + +await once(server, "listening"); + +const client = new H2CClient(`http://localhost:${server.address().port}`); + +client.on("disconnect", (origin) => { + console.log(`Disconnected from ${origin}`); +}); + +try { + await client.request({ + path: "/", + method: "GET", + }); +} catch (error) { + console.error(error.message); + client.close(); + server.close(); +} +``` + +### Event: `'drain'` + +Emitted when pipeline is no longer busy. + +See [Dispatcher Event: `'drain'`](/docs/docs/api/Dispatcher.md#event-drain). + +#### Example - Client drain event + +```js +import { createServer } from "node:http2"; +import { H2CClient } from "undici"; +import { once } from "events"; + +const server = createServer((request, response) => { + response.end("Hello, World!"); +}).listen(); + +await once(server, "listening"); + +const client = new H2CClient(`http://localhost:${server.address().port}`); + +client.on("drain", () => { + console.log("drain event"); + client.close(); + server.close(); +}); + +const requests = [ + client.request({ path: "/", method: "GET" }), + client.request({ path: "/", method: "GET" }), + client.request({ path: "/", method: "GET" }), +]; + +await Promise.all(requests); + +console.log("requests completed"); +``` + +### Event: `'error'` + +Invoked for users errors such as throwing in the `onError` handler. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/MockAgent.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/MockAgent.md new file mode 100644 index 0000000000000000000000000000000000000000..b4ce8106bb0ef4a30973e96f8f2b40b2376be1f8 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/MockAgent.md @@ -0,0 +1,603 @@ +# Class: MockAgent + +Extends: `undici.Dispatcher` + +A mocked Agent class that implements the Agent API. It allows one to intercept HTTP requests made through undici and return mocked responses instead. + +## `new MockAgent([options])` + +Arguments: + +* **options** `MockAgentOptions` (optional) - It extends the `Agent` options. + +Returns: `MockAgent` + +### Parameter: `MockAgentOptions` + +Extends: [`AgentOptions`](/docs/docs/api/Agent.md#parameter-agentoptions) + +* **agent** `Agent` (optional) - Default: `new Agent([options])` - a custom agent encapsulated by the MockAgent. + +* **ignoreTrailingSlash** `boolean` (optional) - Default: `false` - set the default value for `ignoreTrailingSlash` for interceptors. + +* **acceptNonStandardSearchParameters** `boolean` (optional) - Default: `false` - set to `true` if the matcher should also accept non standard search parameters such as multi-value items specified with `[]` (e.g. `param[]=1¶m[]=2¶m[]=3`) and multi-value items which values are comma separated (e.g. `param=1,2,3`). + +### Example - Basic MockAgent instantiation + +This will instantiate the MockAgent. It will not do anything until registered as the agent to use with requests and mock interceptions are added. + +```js +import { MockAgent } from 'undici' + +const mockAgent = new MockAgent() +``` + +### Example - Basic MockAgent instantiation with custom agent + +```js +import { Agent, MockAgent } from 'undici' + +const agent = new Agent() + +const mockAgent = new MockAgent({ agent }) +``` + +## Instance Methods + +### `MockAgent.get(origin)` + +This method creates and retrieves MockPool or MockClient instances which can then be used to intercept HTTP requests. If the number of connections on the mock agent is set to 1, a MockClient instance is returned. Otherwise a MockPool instance is returned. + +For subsequent `MockAgent.get` calls on the same origin, the same mock instance will be returned. + +Arguments: + +* **origin** `string | RegExp | (value) => boolean` - a matcher for the pool origin to be retrieved from the MockAgent. + +| Matcher type | Condition to pass | +|:------------:| -------------------------- | +| `string` | Exact match against string | +| `RegExp` | Regex must pass | +| `Function` | Function must return true | + +Returns: `MockClient | MockPool`. + +| `MockAgentOptions` | Mock instance returned | +| -------------------- | ---------------------- | +| `connections === 1` | `MockClient` | +| `connections` > `1` | `MockPool` | + +#### Example - Basic Mocked Request + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { statusCode, body } = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Mocked Request with local mock agent dispatcher + +```js +import { MockAgent, request } from 'undici' + +const mockAgent = new MockAgent() + +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo', { dispatcher: mockAgent }) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Mocked Request with local mock pool dispatcher + +```js +import { MockAgent, request } from 'undici' + +const mockAgent = new MockAgent() + +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo', { dispatcher: mockPool }) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Mocked Request with local mock client dispatcher + +```js +import { MockAgent, request } from 'undici' + +const mockAgent = new MockAgent({ connections: 1 }) + +const mockClient = mockAgent.get('http://localhost:3000') +mockClient.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo', { dispatcher: mockClient }) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Mocked requests with multiple intercepts + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') +mockPool.intercept({ path: '/hello'}).reply(200, 'hello') + +const result1 = await request('http://localhost:3000/foo') + +console.log('response received', result1.statusCode) // response received 200 + +for await (const data of result1.body) { + console.log('data', data.toString('utf8')) // data foo +} + +const result2 = await request('http://localhost:3000/hello') + +console.log('response received', result2.statusCode) // response received 200 + +for await (const data of result2.body) { + console.log('data', data.toString('utf8')) // data hello +} +``` + +#### Example - Mock different requests within the same file + +```js +const { MockAgent, setGlobalDispatcher } = require('undici'); +const agent = new MockAgent(); +agent.disableNetConnect(); +setGlobalDispatcher(agent); +describe('Test', () => { + it('200', async () => { + const mockAgent = agent.get('http://test.com'); + // your test + }); + it('200', async () => { + const mockAgent = agent.get('http://testing.com'); + // your test + }); +}); +``` + +#### Example - Mocked request with query body, headers and trailers + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo?hello=there&see=ya', + method: 'POST', + body: 'form1=data1&form2=data2' +}).reply(200, { foo: 'bar' }, { + headers: { 'content-type': 'application/json' }, + trailers: { 'Content-MD5': 'test' } +}) + +const { + statusCode, + headers, + trailers, + body +} = await request('http://localhost:3000/foo?hello=there&see=ya', { + method: 'POST', + body: 'form1=data1&form2=data2' +}) + +console.log('response received', statusCode) // response received 200 +console.log('headers', headers) // { 'content-type': 'application/json' } + +for await (const data of body) { + console.log('data', data.toString('utf8')) // '{"foo":"bar"}' +} + +console.log('trailers', trailers) // { 'content-md5': 'test' } +``` + +#### Example - Mocked request with origin regex + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get(new RegExp('http://localhost:3000')) +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Mocked request with origin function + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get((origin) => origin === 'http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +### `MockAgent.close()` + +Closes the mock agent and waits for registered mock pools and clients to also close before resolving. + +Returns: `Promise` + +#### Example - clean up after tests are complete + +```js +import { MockAgent, setGlobalDispatcher } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +await mockAgent.close() +``` + +### `MockAgent.dispatch(options, handlers)` + +Implements [`Agent.dispatch(options, handlers)`](/docs/docs/api/Agent.md#parameter-agentdispatchoptions). + +### `MockAgent.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](/docs/docs/api/Dispatcher.md#dispatcherrequestoptions-callback). + +#### Example - MockAgent request + +```js +import { MockAgent } from 'undici' + +const mockAgent = new MockAgent() + +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await mockAgent.request({ + origin: 'http://localhost:3000', + path: '/foo', + method: 'GET' +}) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +### `MockAgent.deactivate()` + +This method disables mocking in MockAgent. + +Returns: `void` + +#### Example - Deactivate Mocking + +```js +import { MockAgent, setGlobalDispatcher } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +mockAgent.deactivate() +``` + +### `MockAgent.activate()` + +This method enables mocking in a MockAgent instance. When instantiated, a MockAgent is automatically activated. Therefore, this method is only effective after `MockAgent.deactivate` has been called. + +Returns: `void` + +#### Example - Activate Mocking + +```js +import { MockAgent, setGlobalDispatcher } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +mockAgent.deactivate() +// No mocking will occur + +// Later +mockAgent.activate() +``` + +### `MockAgent.enableNetConnect([host])` + +When requests are not matched in a MockAgent intercept, a real HTTP request is attempted. We can control this further through the use of `enableNetConnect`. This is achieved by defining host matchers so only matching requests will be attempted. + +When using a string, it should only include the **hostname and optionally, the port**. In addition, calling this method multiple times with a string will allow all HTTP requests that match these values. + +Arguments: + +* **host** `string | RegExp | (value) => boolean` - (optional) + +Returns: `void` + +#### Example - Allow all non-matching urls to be dispatched in a real HTTP request + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +mockAgent.enableNetConnect() + +await request('http://example.com') +// A real request is made +``` + +#### Example - Allow requests matching a host string to make real requests + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +mockAgent.enableNetConnect('example-1.com') +mockAgent.enableNetConnect('example-2.com:8080') + +await request('http://example-1.com') +// A real request is made + +await request('http://example-2.com:8080') +// A real request is made + +await request('http://example-3.com') +// Will throw +``` + +#### Example - Allow requests matching a host regex to make real requests + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +mockAgent.enableNetConnect(new RegExp('example.com')) + +await request('http://example.com') +// A real request is made +``` + +#### Example - Allow requests matching a host function to make real requests + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +mockAgent.enableNetConnect((value) => value === 'example.com') + +await request('http://example.com') +// A real request is made +``` + +### `MockAgent.disableNetConnect()` + +This method causes all requests to throw when requests are not matched in a MockAgent intercept. + +Returns: `void` + +#### Example - Disable all non-matching requests by throwing an error for each + +```js +import { MockAgent, request } from 'undici' + +const mockAgent = new MockAgent() + +mockAgent.disableNetConnect() + +await request('http://example.com') +// Will throw +``` + +### `MockAgent.pendingInterceptors()` + +This method returns any pending interceptors registered on a mock agent. A pending interceptor meets one of the following criteria: + +- Is registered with neither `.times()` nor `.persist()`, and has not been invoked; +- Is persistent (i.e., registered with `.persist()`) and has not been invoked; +- Is registered with `.times()` and has not been invoked `` of times. + +Returns: `PendingInterceptor[]` (where `PendingInterceptor` is a `MockDispatch` with an additional `origin: string`) + +#### Example - List all pending interceptors + +```js +const agent = new MockAgent() +agent.disableNetConnect() + +agent + .get('https://example.com') + .intercept({ method: 'GET', path: '/' }) + .reply(200) + +const pendingInterceptors = agent.pendingInterceptors() +// Returns [ +// { +// timesInvoked: 0, +// times: 1, +// persist: false, +// consumed: false, +// pending: true, +// path: '/', +// method: 'GET', +// body: undefined, +// headers: undefined, +// data: { +// error: null, +// statusCode: 200, +// data: '', +// headers: {}, +// trailers: {} +// }, +// origin: 'https://example.com' +// } +// ] +``` + +### `MockAgent.assertNoPendingInterceptors([options])` + +This method throws if the mock agent has any pending interceptors. A pending interceptor meets one of the following criteria: + +- Is registered with neither `.times()` nor `.persist()`, and has not been invoked; +- Is persistent (i.e., registered with `.persist()`) and has not been invoked; +- Is registered with `.times()` and has not been invoked `` of times. + +#### Example - Check that there are no pending interceptors + +```js +const agent = new MockAgent() +agent.disableNetConnect() + +agent + .get('https://example.com') + .intercept({ method: 'GET', path: '/' }) + .reply(200) + +agent.assertNoPendingInterceptors() +// Throws an UndiciError with the following message: +// +// 1 interceptor is pending: +// +// ┌─────────┬────────┬───────────────────────┬──────┬─────────────┬────────────┬─────────────┬───────────┐ +// │ (index) │ Method │ Origin │ Path │ Status code │ Persistent │ Invocations │ Remaining │ +// ├─────────┼────────┼───────────────────────┼──────┼─────────────┼────────────┼─────────────┼───────────┤ +// │ 0 │ 'GET' │ 'https://example.com' │ '/' │ 200 │ '❌' │ 0 │ 1 │ +// └─────────┴────────┴───────────────────────┴──────┴─────────────┴────────────┴─────────────┴───────────┘ +``` + +#### Example - access call history on MockAgent + +You can register every call made within a MockAgent to be able to retrieve the body, headers and so on. + +This is not enabled by default. + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent({ enableCallHistory: true }) +setGlobalDispatcher(mockAgent) + +await request('http://example.com', { query: { item: 1 }}) + +mockAgent.getCallHistory()?.firstCall() +// Returns +// MockCallHistoryLog { +// body: undefined, +// headers: undefined, +// method: 'GET', +// origin: 'http://example.com', +// fullUrl: 'http://example.com/?item=1', +// path: '/', +// searchParams: { item: '1' }, +// protocol: 'http:', +// host: 'example.com', +// port: '' +// } +``` + +#### Example - clear call history + +```js +const mockAgent = new MockAgent() + +mockAgent.clearAllCallHistory() +``` + +#### Example - call history instance class method + +```js +const mockAgent = new MockAgent() + +const mockAgentHistory = mockAgent.getCallHistory() + +mockAgentHistory?.calls() // returns an array of MockCallHistoryLogs +mockAgentHistory?.firstCall() // returns the first MockCallHistoryLogs or undefined +mockAgentHistory?.lastCall() // returns the last MockCallHistoryLogs or undefined +mockAgentHistory?.nthCall(3) // returns the third MockCallHistoryLogs or undefined +mockAgentHistory?.filterCalls({ path: '/endpoint', hash: '#hash-value' }) // returns an Array of MockCallHistoryLogs WHERE path === /endpoint OR hash === #hash-value +mockAgentHistory?.filterCalls({ path: '/endpoint', hash: '#hash-value' }, { operator: 'AND' }) // returns an Array of MockCallHistoryLogs WHERE path === /endpoint AND hash === #hash-value +mockAgentHistory?.filterCalls(/"data": "{}"/) // returns an Array of MockCallHistoryLogs where any value match regexp +mockAgentHistory?.filterCalls('application/json') // returns an Array of MockCallHistoryLogs where any value === 'application/json' +mockAgentHistory?.filterCalls((log) => log.path === '/endpoint') // returns an Array of MockCallHistoryLogs when given function returns true +mockAgentHistory?.clear() // clear the history +``` diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/MockCallHistory.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/MockCallHistory.md new file mode 100644 index 0000000000000000000000000000000000000000..7473453b128f34732e8cda90628dd934a425974e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/MockCallHistory.md @@ -0,0 +1,197 @@ +# Class: MockCallHistory + +Access to an instance with : + +```js +const mockAgent = new MockAgent({ enableCallHistory: true }) +mockAgent.getCallHistory() + +// or +const mockAgent = new MockAgent() +mockAgent.enableMockHistory() +mockAgent.getCallHistory() + +``` + +a MockCallHistory instance implements a **Symbol.iterator** letting you iterate on registered logs : + +```ts +for (const log of mockAgent.getCallHistory()) { + //... +} + +const array: Array = [...mockAgent.getCallHistory()] +const set: Set = new Set(mockAgent.getCallHistory()) +``` + +## class methods + +### clear + +Clear all MockCallHistoryLog registered. This is automatically done when calling `mockAgent.close()` + +```js +mockAgent.clearCallHistory() +// same as +mockAgent.getCallHistory()?.clear() +``` + +### calls + +Get all MockCallHistoryLog registered as an array + +```js +mockAgent.getCallHistory()?.calls() +``` + +### firstCall + +Get the first MockCallHistoryLog registered or undefined + +```js +mockAgent.getCallHistory()?.firstCall() +``` + +### lastCall + +Get the last MockCallHistoryLog registered or undefined + +```js +mockAgent.getCallHistory()?.lastCall() +``` + +### nthCall + +Get the nth MockCallHistoryLog registered or undefined + +```js +mockAgent.getCallHistory()?.nthCall(3) // the third MockCallHistoryLog registered +``` + +### filterCallsByProtocol + +Filter MockCallHistoryLog by protocol. + +> more details for the first parameter can be found [here](/docs/docs/api/MockCallHistory.md#filter-parameter) + +```js +mockAgent.getCallHistory()?.filterCallsByProtocol(/https/) +mockAgent.getCallHistory()?.filterCallsByProtocol('https:') +``` + +### filterCallsByHost + +Filter MockCallHistoryLog by host. + +> more details for the first parameter can be found [here](/docs/docs/api/MockCallHistory.md#filter-parameter) + +```js +mockAgent.getCallHistory()?.filterCallsByHost(/localhost/) +mockAgent.getCallHistory()?.filterCallsByHost('localhost:3000') +``` + +### filterCallsByPort + +Filter MockCallHistoryLog by port. + +> more details for the first parameter can be found [here](/docs/docs/api/MockCallHistory.md#filter-parameter) + +```js +mockAgent.getCallHistory()?.filterCallsByPort(/3000/) +mockAgent.getCallHistory()?.filterCallsByPort('3000') +mockAgent.getCallHistory()?.filterCallsByPort('') +``` + +### filterCallsByOrigin + +Filter MockCallHistoryLog by origin. + +> more details for the first parameter can be found [here](/docs/docs/api/MockCallHistory.md#filter-parameter) + +```js +mockAgent.getCallHistory()?.filterCallsByOrigin(/http:\/\/localhost:3000/) +mockAgent.getCallHistory()?.filterCallsByOrigin('http://localhost:3000') +``` + +### filterCallsByPath + +Filter MockCallHistoryLog by path. + +> more details for the first parameter can be found [here](/docs/docs/api/MockCallHistory.md#filter-parameter) + +```js +mockAgent.getCallHistory()?.filterCallsByPath(/api\/v1\/graphql/) +mockAgent.getCallHistory()?.filterCallsByPath('/api/v1/graphql') +``` + +### filterCallsByHash + +Filter MockCallHistoryLog by hash. + +> more details for the first parameter can be found [here](/docs/docs/api/MockCallHistory.md#filter-parameter) + +```js +mockAgent.getCallHistory()?.filterCallsByPath(/hash/) +mockAgent.getCallHistory()?.filterCallsByPath('#hash') +``` + +### filterCallsByFullUrl + +Filter MockCallHistoryLog by fullUrl. fullUrl contains protocol, host, port, path, hash, and query params + +> more details for the first parameter can be found [here](/docs/docs/api/MockCallHistory.md#filter-parameter) + +```js +mockAgent.getCallHistory()?.filterCallsByFullUrl(/https:\/\/localhost:3000\/\?query=value#hash/) +mockAgent.getCallHistory()?.filterCallsByFullUrl('https://localhost:3000/?query=value#hash') +``` + +### filterCallsByMethod + +Filter MockCallHistoryLog by method. + +> more details for the first parameter can be found [here](/docs/docs/api/MockCallHistory.md#filter-parameter) + +```js +mockAgent.getCallHistory()?.filterCallsByMethod(/POST/) +mockAgent.getCallHistory()?.filterCallsByMethod('POST') +``` + +### filterCalls + +This class method is a meta function / alias to apply complex filtering in a single way. + +Parameters : + +- criteria : the first parameter. a function, regexp or object. + - function : filter MockCallHistoryLog when the function returns false + - regexp : filter MockCallHistoryLog when the regexp does not match on MockCallHistoryLog.toString() ([see](./MockCallHistoryLog.md#to-string)) + - object : an object with MockCallHistoryLog properties as keys to apply multiple filters. each values are a [filter parameter](/docs/docs/api/MockCallHistory.md#filter-parameter) +- options : the second parameter. an object. + - options.operator : `'AND'` or `'OR'` (default `'OR'`). Used only if criteria is an object. see below + +```js +mockAgent.getCallHistory()?.filterCalls((log) => log.hash === value && log.headers?.['authorization'] !== undefined) +mockAgent.getCallHistory()?.filterCalls(/"data": "{ "errors": "wrong body" }"/) + +// returns an Array of MockCallHistoryLog which all have +// - a hash containing my-hash +// - OR +// - a path equal to /endpoint +mockAgent.getCallHistory()?.filterCalls({ hash: /my-hash/, path: '/endpoint' }) + +// returns an Array of MockCallHistoryLog which all have +// - a hash containing my-hash +// - AND +// - a path equal to /endpoint +mockAgent.getCallHistory()?.filterCalls({ hash: /my-hash/, path: '/endpoint' }, { operator: 'AND' }) +``` + +## filter parameter + +Can be : + +- string. MockCallHistoryLog filtered if `value !== parameterValue` +- null. MockCallHistoryLog filtered if `value !== parameterValue` +- undefined. MockCallHistoryLog filtered if `value !== parameterValue` +- regexp. MockCallHistoryLog filtered if `!parameterValue.test(value)` diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/MockCallHistoryLog.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/MockCallHistoryLog.md new file mode 100644 index 0000000000000000000000000000000000000000..3d38bdd29d556e9834029f3637c9ef22f1605266 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/MockCallHistoryLog.md @@ -0,0 +1,43 @@ +# Class: MockCallHistoryLog + +Access to an instance with : + +```js +const mockAgent = new MockAgent({ enableCallHistory: true }) +mockAgent.getCallHistory()?.firstCall() +``` + +## class properties + +- body `mockAgent.getCallHistory()?.firstCall()?.body` +- headers `mockAgent.getCallHistory()?.firstCall()?.headers` an object +- method `mockAgent.getCallHistory()?.firstCall()?.method` a string +- fullUrl `mockAgent.getCallHistory()?.firstCall()?.fullUrl` a string containing the protocol, origin, path, query and hash +- origin `mockAgent.getCallHistory()?.firstCall()?.origin` a string containing the protocol and the host +- headers `mockAgent.getCallHistory()?.firstCall()?.headers` an object +- path `mockAgent.getCallHistory()?.firstCall()?.path` a string always starting with `/` +- searchParams `mockAgent.getCallHistory()?.firstCall()?.searchParams` an object +- protocol `mockAgent.getCallHistory()?.firstCall()?.protocol` a string (`https:`) +- host `mockAgent.getCallHistory()?.firstCall()?.host` a string +- port `mockAgent.getCallHistory()?.firstCall()?.port` an empty string or a string containing numbers +- hash `mockAgent.getCallHistory()?.firstCall()?.hash` an empty string or a string starting with `#` + +## class methods + +### toMap + +Returns a Map instance + +```js +mockAgent.getCallHistory()?.firstCall()?.toMap()?.get('hash') +// #hash +``` + +### toString + +Returns a string computed with any class property name and value pair + +```js +mockAgent.getCallHistory()?.firstCall()?.toString() +// protocol->https:|host->localhost:4000|port->4000|origin->https://localhost:4000|path->/endpoint|hash->#here|searchParams->{"query":"value"}|fullUrl->https://localhost:4000/endpoint?query=value#here|method->PUT|body->"{ "data": "hello" }"|headers->{"content-type":"application/json"} +``` diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/MockClient.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/MockClient.md new file mode 100644 index 0000000000000000000000000000000000000000..0e6c57a1a84c439ef40fbd889dac4375ffe0208d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/MockClient.md @@ -0,0 +1,81 @@ +# Class: MockClient + +Extends: `undici.Client` + +A mock client class that implements the same api as [MockPool](/docs/docs/api/MockPool.md). + +## `new MockClient(origin, [options])` + +Arguments: + +* **origin** `string` - It should only include the **protocol, hostname, and port**. +* **options** `MockClientOptions` - It extends the `Client` options. + +Returns: `MockClient` + +### Parameter: `MockClientOptions` + +Extends: `ClientOptions` + +* **agent** `Agent` - the agent to associate this MockClient with. + +### Example - Basic MockClient instantiation + +We can use MockAgent to instantiate a MockClient ready to be used to intercept specified requests. It will not do anything until registered as the agent to use and any mock request are registered. + +```js +import { MockAgent } from 'undici' + +// Connections must be set to 1 to return a MockClient instance +const mockAgent = new MockAgent({ connections: 1 }) + +const mockClient = mockAgent.get('http://localhost:3000') +``` + +## Instance Methods + +### `MockClient.intercept(options)` + +Implements: [`MockPool.intercept(options)`](/docs/docs/api/MockPool.md#mockpoolinterceptoptions) + +### `MockClient.cleanMocks()` + +Implements: [`MockPool.cleanMocks()`](/docs/docs/api/MockPool.md#mockpoolcleanmocks) + +### `MockClient.close()` + +Implements: [`MockPool.close()`](/docs/docs/api/MockPool.md#mockpoolclose) + +### `MockClient.dispatch(options, handlers)` + +Implements [`Dispatcher.dispatch(options, handlers)`](/docs/docs/api/Dispatcher.md#dispatcherdispatchoptions-handler). + +### `MockClient.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](/docs/docs/api/Dispatcher.md#dispatcherrequestoptions-callback). + +#### Example - MockClient request + +```js +import { MockAgent } from 'undici' + +const mockAgent = new MockAgent({ connections: 1 }) + +const mockClient = mockAgent.get('http://localhost:3000') +mockClient.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await mockClient.request({ + origin: 'http://localhost:3000', + path: '/foo', + method: 'GET' +}) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/MockErrors.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/MockErrors.md new file mode 100644 index 0000000000000000000000000000000000000000..c1aa3dbee8ec5e7a311c07f4be431a59a5fc389e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/MockErrors.md @@ -0,0 +1,12 @@ +# MockErrors + +Undici exposes a variety of mock error objects that you can use to enhance your mock error handling. +You can find all the mock error objects inside the `mockErrors` key. + +```js +import { mockErrors } from 'undici' +``` + +| Mock Error | Mock Error Codes | Description | +| --------------------- | ------------------------------- | ---------------------------------------------------------- | +| `MockNotMatchedError` | `UND_MOCK_ERR_MOCK_NOT_MATCHED` | The request does not match any registered mock dispatches. | diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/MockPool.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/MockPool.md new file mode 100644 index 0000000000000000000000000000000000000000..6656b95d834c05c30402c2de94d62931cc49fc80 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/MockPool.md @@ -0,0 +1,554 @@ +# Class: MockPool + +Extends: `undici.Pool` + +A mock Pool class that implements the Pool API and is used by MockAgent to intercept real requests and return mocked responses. + +## `new MockPool(origin, [options])` + +Arguments: + +* **origin** `string` - It should only include the **protocol, hostname, and port**. +* **options** `MockPoolOptions` - It extends the `Pool` options. + +Returns: `MockPool` + +### Parameter: `MockPoolOptions` + +Extends: `PoolOptions` + +* **agent** `Agent` - the agent to associate this MockPool with. + +### Example - Basic MockPool instantiation + +We can use MockAgent to instantiate a MockPool ready to be used to intercept specified requests. It will not do anything until registered as the agent to use and any mock request are registered. + +```js +import { MockAgent } from 'undici' + +const mockAgent = new MockAgent() + +const mockPool = mockAgent.get('http://localhost:3000') +``` + +## Instance Methods + +### `MockPool.intercept(options)` + +This method defines the interception rules for matching against requests for a MockPool or MockPool. We can intercept multiple times on a single instance, but each intercept is only used once. For example if you expect to make 2 requests inside a test, you need to call `intercept()` twice. Assuming you use `disableNetConnect()` you will get `MockNotMatchedError` on the second request when you only call `intercept()` once. + +When defining interception rules, all the rules must pass for a request to be intercepted. If a request is not intercepted, a real request will be attempted. + +| Matcher type | Condition to pass | +|:------------:| -------------------------- | +| `string` | Exact match against string | +| `RegExp` | Regex must pass | +| `Function` | Function must return true | + +Arguments: + +* **options** `MockPoolInterceptOptions` - Interception options. + +Returns: `MockInterceptor` corresponding to the input options. + +### Parameter: `MockPoolInterceptOptions` + +* **path** `string | RegExp | (path: string) => boolean` - a matcher for the HTTP request path. When a `RegExp` or callback is used, it will match against the request path including all query parameters in alphabetical order. When a `string` is provided, the query parameters can be conveniently specified through the `MockPoolInterceptOptions.query` setting. +* **method** `string | RegExp | (method: string) => boolean` - (optional) - a matcher for the HTTP request method. Defaults to `GET`. +* **body** `string | RegExp | (body: string) => boolean` - (optional) - a matcher for the HTTP request body. +* **headers** `Record boolean`> - (optional) - a matcher for the HTTP request headers. To be intercepted, a request must match all defined headers. Extra headers not defined here may (or may not) be included in the request and do not affect the interception in any way. +* **query** `Record | null` - (optional) - a matcher for the HTTP request query string params. Only applies when a `string` was provided for `MockPoolInterceptOptions.path`. +* **ignoreTrailingSlash** `boolean` - (optional) - set to `true` if the matcher should also match by ignoring potential trailing slashes in `MockPoolInterceptOptions.path`. + +### Return: `MockInterceptor` + +We can define the behaviour of an intercepted request with the following options. + +* **reply** `(statusCode: number, replyData: string | Buffer | object | MockInterceptor.MockResponseDataHandler, responseOptions?: MockResponseOptions) => MockScope` - define a reply for a matching request. You can define the replyData as a callback to read incoming request data. Default for `responseOptions` is `{}`. +* **reply** `(callback: MockInterceptor.MockReplyOptionsCallback) => MockScope` - define a reply for a matching request, allowing dynamic mocking of all reply options rather than just the data. +* **replyWithError** `(error: Error) => MockScope` - define an error for a matching request to throw. +* **defaultReplyHeaders** `(headers: Record) => MockInterceptor` - define default headers to be included in subsequent replies. These are in addition to headers on a specific reply. +* **defaultReplyTrailers** `(trailers: Record) => MockInterceptor` - define default trailers to be included in subsequent replies. These are in addition to trailers on a specific reply. +* **replyContentLength** `() => MockInterceptor` - define automatically calculated `content-length` headers to be included in subsequent replies. + +The reply data of an intercepted request may either be a string, buffer, or JavaScript object. Objects are converted to JSON while strings and buffers are sent as-is. + +By default, `reply` and `replyWithError` define the behaviour for the first matching request only. Subsequent requests will not be affected (this can be changed using the returned `MockScope`). + +### Parameter: `MockResponseOptions` + +* **headers** `Record` - headers to be included on the mocked reply. +* **trailers** `Record` - trailers to be included on the mocked reply. + +### Return: `MockScope` + +A `MockScope` is associated with a single `MockInterceptor`. With this, we can configure the default behaviour of an intercepted reply. + +* **delay** `(waitInMs: number) => MockScope` - delay the associated reply by a set amount in ms. +* **persist** `() => MockScope` - any matching request will always reply with the defined response indefinitely. +* **times** `(repeatTimes: number) => MockScope` - any matching request will reply with the defined response a fixed amount of times. This is overridden by **persist**. + +#### Example - Basic Mocked Request + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +// MockPool +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Mocked request using reply data callbacks + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/echo', + method: 'GET', + headers: { + 'User-Agent': 'undici', + Host: 'example.com' + } +}).reply(200, ({ headers }) => ({ message: headers.get('message') })) + +const { statusCode, body, headers } = await request('http://localhost:3000', { + headers: { + message: 'hello world!' + } +}) + +console.log('response received', statusCode) // response received 200 +console.log('headers', headers) // { 'content-type': 'application/json' } + +for await (const data of body) { + console.log('data', data.toString('utf8')) // { "message":"hello world!" } +} +``` + +#### Example - Mocked request using reply options callback + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/echo', + method: 'GET', + headers: { + 'User-Agent': 'undici', + Host: 'example.com' + } +}).reply(({ headers }) => ({ statusCode: 200, data: { message: headers.get('message') }}))) + +const { statusCode, body, headers } = await request('http://localhost:3000', { + headers: { + message: 'hello world!' + } +}) + +console.log('response received', statusCode) // response received 200 +console.log('headers', headers) // { 'content-type': 'application/json' } + +for await (const data of body) { + console.log('data', data.toString('utf8')) // { "message":"hello world!" } +} +``` + +#### Example - Basic Mocked requests with multiple intercepts + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).reply(200, 'foo') + +mockPool.intercept({ + path: '/hello', + method: 'GET', +}).reply(200, 'hello') + +const result1 = await request('http://localhost:3000/foo') + +console.log('response received', result1.statusCode) // response received 200 + +for await (const data of result1.body) { + console.log('data', data.toString('utf8')) // data foo +} + +const result2 = await request('http://localhost:3000/hello') + +console.log('response received', result2.statusCode) // response received 200 + +for await (const data of result2.body) { + console.log('data', data.toString('utf8')) // data hello +} +``` + +#### Example - Mocked request with query body, request headers and response headers and trailers + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo?hello=there&see=ya', + method: 'POST', + body: 'form1=data1&form2=data2', + headers: { + 'User-Agent': 'undici', + Host: 'example.com' + } +}).reply(200, { foo: 'bar' }, { + headers: { 'content-type': 'application/json' }, + trailers: { 'Content-MD5': 'test' } +}) + +const { + statusCode, + headers, + trailers, + body +} = await request('http://localhost:3000/foo?hello=there&see=ya', { + method: 'POST', + body: 'form1=data1&form2=data2', + headers: { + foo: 'bar', + 'User-Agent': 'undici', + Host: 'example.com' + } + }) + +console.log('response received', statusCode) // response received 200 +console.log('headers', headers) // { 'content-type': 'application/json' } + +for await (const data of body) { + console.log('data', data.toString('utf8')) // '{"foo":"bar"}' +} + +console.log('trailers', trailers) // { 'content-md5': 'test' } +``` + +#### Example - Mocked request using different matchers + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: /^GET$/, + body: (value) => value === 'form=data', + headers: { + 'User-Agent': 'undici', + Host: /^example.com$/ + } +}).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo', { + method: 'GET', + body: 'form=data', + headers: { + foo: 'bar', + 'User-Agent': 'undici', + Host: 'example.com' + } +}) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Mocked request with reply with a defined error + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).replyWithError(new Error('kaboom')) + +try { + await request('http://localhost:3000/foo', { + method: 'GET' + }) +} catch (error) { + console.error(error) // Error: kaboom +} +``` + +#### Example - Mocked request with defaultReplyHeaders + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).defaultReplyHeaders({ foo: 'bar' }) + .reply(200, 'foo') + +const { headers } = await request('http://localhost:3000/foo') + +console.log('headers', headers) // headers { foo: 'bar' } +``` + +#### Example - Mocked request with defaultReplyTrailers + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).defaultReplyTrailers({ foo: 'bar' }) + .reply(200, 'foo') + +const { trailers } = await request('http://localhost:3000/foo') + +console.log('trailers', trailers) // trailers { foo: 'bar' } +``` + +#### Example - Mocked request with automatic content-length calculation + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).replyContentLength().reply(200, 'foo') + +const { headers } = await request('http://localhost:3000/foo') + +console.log('headers', headers) // headers { 'content-length': '3' } +``` + +#### Example - Mocked request with automatic content-length calculation on an object + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).replyContentLength().reply(200, { foo: 'bar' }) + +const { headers } = await request('http://localhost:3000/foo') + +console.log('headers', headers) // headers { 'content-length': '13' } +``` + +#### Example - Mocked request with persist enabled + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).reply(200, 'foo').persist() + +const result1 = await request('http://localhost:3000/foo') +// Will match and return mocked data + +const result2 = await request('http://localhost:3000/foo') +// Will match and return mocked data + +// Etc +``` + +#### Example - Mocked request with times enabled + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).reply(200, 'foo').times(2) + +const result1 = await request('http://localhost:3000/foo') +// Will match and return mocked data + +const result2 = await request('http://localhost:3000/foo') +// Will match and return mocked data + +const result3 = await request('http://localhost:3000/foo') +// Will not match and make attempt a real request +``` + +#### Example - Mocked request with path callback + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' +import querystring from 'querystring' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +const matchPath = requestPath => { + const [pathname, search] = requestPath.split('?') + const requestQuery = querystring.parse(search) + + if (!pathname.startsWith('/foo')) { + return false + } + + if (!Object.keys(requestQuery).includes('foo') || requestQuery.foo !== 'bar') { + return false + } + + return true +} + +mockPool.intercept({ + path: matchPath, + method: 'GET' +}).reply(200, 'foo') + +const result = await request('http://localhost:3000/foo?foo=bar') +// Will match and return mocked data +``` + +### `MockPool.close()` + +Closes the mock pool and de-registers from associated MockAgent. + +Returns: `Promise` + +#### Example - clean up after tests are complete + +```js +import { MockAgent } from 'undici' + +const mockAgent = new MockAgent() +const mockPool = mockAgent.get('http://localhost:3000') + +await mockPool.close() +``` + +### `MockPool.dispatch(options, handlers)` + +Implements [`Dispatcher.dispatch(options, handlers)`](/docs/docs/api/Dispatcher.md#dispatcherdispatchoptions-handler). + +### `MockPool.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](/docs/docs/api/Dispatcher.md#dispatcherrequestoptions-callback). + +#### Example - MockPool request + +```js +import { MockAgent } from 'undici' + +const mockAgent = new MockAgent() + +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ + path: '/foo', + method: 'GET', +}).reply(200, 'foo') + +const { + statusCode, + body +} = await mockPool.request({ + origin: 'http://localhost:3000', + path: '/foo', + method: 'GET' +}) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +### `MockPool.cleanMocks()` + +This method cleans up all the prepared mocks. + +Returns: `void` diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/Pool.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/Pool.md new file mode 100644 index 0000000000000000000000000000000000000000..ee0a0d3fe81acaeadd6ce5cc93f068113dcab120 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/Pool.md @@ -0,0 +1,84 @@ +# Class: Pool + +Extends: `undici.Dispatcher` + +A pool of [Client](/docs/docs/api/Client.md) instances connected to the same upstream target. + +Requests are not guaranteed to be dispatched in order of invocation. + +## `new Pool(url[, options])` + +Arguments: + +* **url** `URL | string` - It should only include the **protocol, hostname, and port**. +* **options** `PoolOptions` (optional) + +### Parameter: `PoolOptions` + +Extends: [`ClientOptions`](/docs/docs/api/Client.md#parameter-clientoptions) + +* **factory** `(origin: URL, opts: Object) => Dispatcher` - Default: `(origin, opts) => new Client(origin, opts)` +* **connections** `number | null` (optional) - Default: `null` - The number of `Client` instances to create. When set to `null`, the `Pool` instance will create an unlimited amount of `Client` instances. +* **clientTtl** `number | null` (optional) - Default: `null` - The amount of time before a `Client` instance is removed from the `Pool` and closed. When set to `null`, `Client` instances will not be removed or closed based on age. + +## Instance Properties + +### `Pool.closed` + +Implements [Client.closed](/docs/docs/api/Client.md#clientclosed) + +### `Pool.destroyed` + +Implements [Client.destroyed](/docs/docs/api/Client.md#clientdestroyed) + +### `Pool.stats` + +Returns [`PoolStats`](PoolStats.md) instance for this pool. + +## Instance Methods + +### `Pool.close([callback])` + +Implements [`Dispatcher.close([callback])`](/docs/docs/api/Dispatcher.md#dispatcherclosecallback-promise). + +### `Pool.destroy([error, callback])` + +Implements [`Dispatcher.destroy([error, callback])`](/docs/docs/api/Dispatcher.md#dispatcherdestroyerror-callback-promise). + +### `Pool.connect(options[, callback])` + +See [`Dispatcher.connect(options[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherconnectoptions-callback). + +### `Pool.dispatch(options, handler)` + +Implements [`Dispatcher.dispatch(options, handler)`](/docs/docs/api/Dispatcher.md#dispatcherdispatchoptions-handler). + +### `Pool.pipeline(options, handler)` + +See [`Dispatcher.pipeline(options, handler)`](/docs/docs/api/Dispatcher.md#dispatcherpipelineoptions-handler). + +### `Pool.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](/docs/docs/api/Dispatcher.md#dispatcherrequestoptions-callback). + +### `Pool.stream(options, factory[, callback])` + +See [`Dispatcher.stream(options, factory[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherstreamoptions-factory-callback). + +### `Pool.upgrade(options[, callback])` + +See [`Dispatcher.upgrade(options[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherupgradeoptions-callback). + +## Instance Events + +### Event: `'connect'` + +See [Dispatcher Event: `'connect'`](/docs/docs/api/Dispatcher.md#event-connect). + +### Event: `'disconnect'` + +See [Dispatcher Event: `'disconnect'`](/docs/docs/api/Dispatcher.md#event-disconnect). + +### Event: `'drain'` + +See [Dispatcher Event: `'drain'`](/docs/docs/api/Dispatcher.md#event-drain). diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/PoolStats.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/PoolStats.md new file mode 100644 index 0000000000000000000000000000000000000000..3cbe0d82e17a9a14e2d1feb8f91b760624a1f98b --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/PoolStats.md @@ -0,0 +1,35 @@ +# Class: PoolStats + +Aggregate stats for a [Pool](/docs/docs/api/Pool.md) or [BalancedPool](/docs/docs/api/BalancedPool.md). + +## `new PoolStats(pool)` + +Arguments: + +* **pool** `Pool` - Pool or BalancedPool from which to return stats. + +## Instance Properties + +### `PoolStats.connected` + +Number of open socket connections in this pool. + +### `PoolStats.free` + +Number of open socket connections in this pool that do not have an active request. + +### `PoolStats.pending` + +Number of pending requests across all clients in this pool. + +### `PoolStats.queued` + +Number of queued requests across all clients in this pool. + +### `PoolStats.running` + +Number of currently active requests across all clients in this pool. + +### `PoolStats.size` + +Number of active, pending, or queued requests across all clients in this pool. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/ProxyAgent.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/ProxyAgent.md new file mode 100644 index 0000000000000000000000000000000000000000..8db7221a3626af1c63c7e363bc96f5fa1b0d1870 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/ProxyAgent.md @@ -0,0 +1,229 @@ +# Class: ProxyAgent + +Extends: `undici.Dispatcher` + +A Proxy Agent class that implements the Agent API. It allows the connection through proxy in a simple way. + +## `new ProxyAgent([options])` + +Arguments: + +* **options** `ProxyAgentOptions` (required) - It extends the `Agent` options. + +Returns: `ProxyAgent` + +### Parameter: `ProxyAgentOptions` + +Extends: [`AgentOptions`](/docs/docs/api/Agent.md#parameter-agentoptions) +> It ommits `AgentOptions#connect`. + +> **Note:** When `AgentOptions#connections` is set, and different from `0`, the non-standard [`proxy-connection` header](https://udger.com/resources/http-request-headers-detail?header=Proxy-Connection) will be set to `keep-alive` in the request. + +* **uri** `string | URL` (required) - The URI of the proxy server. This can be provided as a string, as an instance of the URL class, or as an object with a `uri` property of type string. +If the `uri` is provided as a string or `uri` is an object with an `uri` property of type string, then it will be parsed into a `URL` object according to the [WHATWG URL Specification](https://url.spec.whatwg.org). +For detailed information on the parsing process and potential validation errors, please refer to the ["Writing" section](https://url.spec.whatwg.org/#writing) of the WHATWG URL Specification. +* **token** `string` (optional) - It can be passed by a string of token for authentication. +* **auth** `string` (**deprecated**) - Use token. +* **clientFactory** `(origin: URL, opts: Object) => Dispatcher` (optional) - Default: `(origin, opts) => new Pool(origin, opts)` +* **requestTls** `BuildOptions` (optional) - Options object passed when creating the underlying socket via the connector builder for the request. It extends from [`Client#ConnectOptions`](/docs/docs/api/Client.md#parameter-connectoptions). +* **proxyTls** `BuildOptions` (optional) - Options object passed when creating the underlying socket via the connector builder for the proxy server. It extends from [`Client#ConnectOptions`](/docs/docs/api/Client.md#parameter-connectoptions). +* **proxyTunnel** `boolean` (optional) - For connections involving secure protocols, Undici will always establish a tunnel via the HTTP2 CONNECT extension. If proxyTunnel is set to true, this will occur for unsecured proxy/endpoint connections as well. Currently, there is no way to facilitate HTTP1 IP tunneling as described in https://www.rfc-editor.org/rfc/rfc9484.html#name-http-11-request. If proxyTunnel is set to false (the default), ProxyAgent connections where both the Proxy and Endpoint are unsecured will issue all requests to the Proxy, and prefix the endpoint request path with the endpoint origin address. + +Examples: + +```js +import { ProxyAgent } from 'undici' + +const proxyAgent = new ProxyAgent('my.proxy.server') +// or +const proxyAgent = new ProxyAgent(new URL('my.proxy.server')) +// or +const proxyAgent = new ProxyAgent({ uri: 'my.proxy.server' }) +// or +const proxyAgent = new ProxyAgent({ + uri: new URL('my.proxy.server'), + proxyTls: { + signal: AbortSignal.timeout(1000) + } +}) +``` + +#### Example - Basic ProxyAgent instantiation + +This will instantiate the ProxyAgent. It will not do anything until registered as the agent to use with requests. + +```js +import { ProxyAgent } from 'undici' + +const proxyAgent = new ProxyAgent('my.proxy.server') +``` + +#### Example - Basic Proxy Request with global agent dispatcher + +```js +import { setGlobalDispatcher, request, ProxyAgent } from 'undici' + +const proxyAgent = new ProxyAgent('my.proxy.server') +setGlobalDispatcher(proxyAgent) + +const { statusCode, body } = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Proxy Request with local agent dispatcher + +```js +import { ProxyAgent, request } from 'undici' + +const proxyAgent = new ProxyAgent('my.proxy.server') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo', { dispatcher: proxyAgent }) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Proxy Request with authentication + +```js +import { setGlobalDispatcher, request, ProxyAgent } from 'undici'; + +const proxyAgent = new ProxyAgent({ + uri: 'my.proxy.server', + // token: 'Bearer xxxx' + token: `Basic ${Buffer.from('username:password').toString('base64')}` +}); +setGlobalDispatcher(proxyAgent); + +const { statusCode, body } = await request('http://localhost:3000/foo'); + +console.log('response received', statusCode); // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')); // data foo +} +``` + +### `ProxyAgent.close()` + +Closes the proxy agent and waits for registered pools and clients to also close before resolving. + +Returns: `Promise` + +#### Example - clean up after tests are complete + +```js +import { ProxyAgent, setGlobalDispatcher } from 'undici' + +const proxyAgent = new ProxyAgent('my.proxy.server') +setGlobalDispatcher(proxyAgent) + +await proxyAgent.close() +``` + +### `ProxyAgent.dispatch(options, handlers)` + +Implements [`Agent.dispatch(options, handlers)`](/docs/docs/api/Agent.md#parameter-agentdispatchoptions). + +### `ProxyAgent.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](/docs/docs/api/Dispatcher.md#dispatcherrequestoptions-callback). + + +#### Example - ProxyAgent with Fetch + +This example demonstrates how to use `fetch` with a proxy via `ProxyAgent`. It is particularly useful for scenarios requiring proxy tunneling. + +```javascript +import { ProxyAgent, fetch } from 'undici'; + +// Define the ProxyAgent +const proxyAgent = new ProxyAgent('http://localhost:8000'); + +// Make a GET request through the proxy +const response = await fetch('http://localhost:3000/foo', { + dispatcher: proxyAgent, + method: 'GET', +}); + +console.log('Response status:', response.status); +console.log('Response data:', await response.text()); +``` + +--- + +#### Example - ProxyAgent with a Custom Proxy Server + +This example shows how to create a custom proxy server and use it with `ProxyAgent`. + +```javascript +import * as http from 'node:http'; +import { createProxy } from 'proxy'; +import { ProxyAgent, fetch } from 'undici'; + +// Create a proxy server +const proxyServer = createProxy(http.createServer()); +proxyServer.listen(8000, () => { + console.log('Proxy server running on port 8000'); +}); + +// Define and use the ProxyAgent +const proxyAgent = new ProxyAgent('http://localhost:8000'); + +const response = await fetch('http://example.com', { + dispatcher: proxyAgent, + method: 'GET', +}); + +console.log('Response status:', response.status); +console.log('Response data:', await response.text()); +``` + +--- + +#### Example - ProxyAgent with HTTPS Tunneling + +This example demonstrates how to perform HTTPS tunneling using a proxy. + +```javascript +import { ProxyAgent, fetch } from 'undici'; + +// Define a ProxyAgent for HTTPS proxy +const proxyAgent = new ProxyAgent('https://secure.proxy.server'); + +// Make a request to an HTTPS endpoint via the proxy +const response = await fetch('https://secure.endpoint.com/api/data', { + dispatcher: proxyAgent, + method: 'GET', +}); + +console.log('Response status:', response.status); +console.log('Response data:', await response.json()); +``` + +#### Example - ProxyAgent as a Global Dispatcher + +`ProxyAgent` can be configured as a global dispatcher, making it available for all requests without explicitly passing it. This simplifies code and is useful when a single proxy configuration applies to all requests. + +```javascript +import { ProxyAgent, setGlobalDispatcher, fetch } from 'undici'; + +// Define and configure the ProxyAgent +const proxyAgent = new ProxyAgent('http://localhost:8000'); +setGlobalDispatcher(proxyAgent); + +// Make requests without specifying the dispatcher +const response = await fetch('http://example.com'); +console.log('Response status:', response.status); +console.log('Response data:', await response.text()); diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/RedirectHandler.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/RedirectHandler.md new file mode 100644 index 0000000000000000000000000000000000000000..bb16284fff4c8d8641546f9a735b4d76aa37fbe2 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/RedirectHandler.md @@ -0,0 +1,96 @@ +# Class: RedirectHandler + +A class that handles redirection logic for HTTP requests. + +## `new RedirectHandler(dispatch, maxRedirections, opts, handler, redirectionLimitReached)` + +Arguments: + +- **dispatch** `function` - The dispatch function to be called after every retry. +- **maxRedirections** `number` - Maximum number of redirections allowed. +- **opts** `object` - Options for handling redirection. +- **handler** `object` - An object containing handlers for different stages of the request lifecycle. +- **redirectionLimitReached** `boolean` (default: `false`) - A flag that the implementer can provide to enable or disable the feature. If set to `false`, it indicates that the caller doesn't want to use the feature and prefers the old behavior. + +Returns: `RedirectHandler` + +### Parameters + +- **dispatch** `(options: Dispatch.DispatchOptions, handlers: Dispatch.DispatchHandler) => Promise` (required) - Dispatch function to be called after every redirection. +- **maxRedirections** `number` (required) - Maximum number of redirections allowed. +- **opts** `object` (required) - Options for handling redirection. +- **handler** `object` (required) - Handlers for different stages of the request lifecycle. +- **redirectionLimitReached** `boolean` (default: `false`) - A flag that the implementer can provide to enable or disable the feature. If set to `false`, it indicates that the caller doesn't want to use the feature and prefers the old behavior. + +### Properties + +- **location** `string` - The current redirection location. +- **abort** `function` - The abort function. +- **opts** `object` - The options for handling redirection. +- **maxRedirections** `number` - Maximum number of redirections allowed. +- **handler** `object` - Handlers for different stages of the request lifecycle. +- **history** `Array` - An array representing the history of URLs during redirection. +- **redirectionLimitReached** `boolean` - Indicates whether the redirection limit has been reached. + +### Methods + +#### `onConnect(abort)` + +Called when the connection is established. + +Parameters: + +- **abort** `function` - The abort function. + +#### `onUpgrade(statusCode, headers, socket)` + +Called when an upgrade is requested. + +Parameters: + +- **statusCode** `number` - The HTTP status code. +- **headers** `object` - The headers received in the response. +- **socket** `object` - The socket object. + +#### `onError(error)` + +Called when an error occurs. + +Parameters: + +- **error** `Error` - The error that occurred. + +#### `onHeaders(statusCode, headers, resume, statusText)` + +Called when headers are received. + +Parameters: + +- **statusCode** `number` - The HTTP status code. +- **headers** `object` - The headers received in the response. +- **resume** `function` - The resume function. +- **statusText** `string` - The status text. + +#### `onData(chunk)` + +Called when data is received. + +Parameters: + +- **chunk** `Buffer` - The data chunk received. + +#### `onComplete(trailers)` + +Called when the request is complete. + +Parameters: + +- **trailers** `object` - The trailers received. + +#### `onBodySent(chunk)` + +Called when the request body is sent. + +Parameters: + +- **chunk** `Buffer` - The chunk of the request body sent. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/RetryAgent.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/RetryAgent.md new file mode 100644 index 0000000000000000000000000000000000000000..9b423d9f0fff56367a3ff569e39d0556904c5d0f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/RetryAgent.md @@ -0,0 +1,50 @@ +# Class: RetryAgent + +Extends: `undici.Dispatcher` + +A `undici.Dispatcher` that allows to automatically retry a request. +Wraps a `undici.RetryHandler`. + +## `new RetryAgent(dispatcher, [options])` + +Arguments: + +* **dispatcher** `undici.Dispatcher` (required) - the dispatcher to wrap +* **options** `RetryHandlerOptions` (optional) - the options + +Returns: `ProxyAgent` + +### Parameter: `RetryHandlerOptions` + +- **throwOnError** `boolean` (optional) - Disable to prevent throwing error on last retry attept, useful if you need the body on errors from server or if you have custom error handler. Default: `true` +- **retry** `(err: Error, context: RetryContext, callback: (err?: Error | null) => void) => void` (optional) - Function to be called after every retry. It should pass error if no more retries should be performed. +- **maxRetries** `number` (optional) - Maximum number of retries. Default: `5` +- **maxTimeout** `number` (optional) - Maximum number of milliseconds to wait before retrying. Default: `30000` (30 seconds) +- **minTimeout** `number` (optional) - Minimum number of milliseconds to wait before retrying. Default: `500` (half a second) +- **timeoutFactor** `number` (optional) - Factor to multiply the timeout by for each retry attempt. Default: `2` +- **retryAfter** `boolean` (optional) - It enables automatic retry after the `Retry-After` header is received. Default: `true` +- +- **methods** `string[]` (optional) - Array of HTTP methods to retry. Default: `['GET', 'PUT', 'HEAD', 'OPTIONS', 'DELETE']` +- **statusCodes** `number[]` (optional) - Array of HTTP status codes to retry. Default: `[429, 500, 502, 503, 504]` +- **errorCodes** `string[]` (optional) - Array of Error codes to retry. Default: `['ECONNRESET', 'ECONNREFUSED', 'ENOTFOUND', 'ENETDOWN','ENETUNREACH', 'EHOSTDOWN', 'UND_ERR_SOCKET']` + +**`RetryContext`** + +- `state`: `RetryState` - Current retry state. It can be mutated. +- `opts`: `Dispatch.DispatchOptions & RetryOptions` - Options passed to the retry handler. + +Example: + +```js +import { Agent, RetryAgent } from 'undici' + +const agent = new RetryAgent(new Agent()) + +const res = await agent.request({ + method: 'GET', + origin: 'http://example.com', + path: '/', +}) +console.log(res.statusCode) +console.log(await res.body.text()) +``` diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/RetryHandler.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/RetryHandler.md new file mode 100644 index 0000000000000000000000000000000000000000..d7b3e88d0f717e156e0f1c979e137e5db95e75ab --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/RetryHandler.md @@ -0,0 +1,118 @@ +# Class: RetryHandler + +Extends: `undici.DispatcherHandlers` + +A handler class that implements the retry logic for a request. + +## `new RetryHandler(dispatchOptions, retryHandlers, [retryOptions])` + +Arguments: + +- **options** `Dispatch.DispatchOptions & RetryOptions` (required) - It is an intersection of `Dispatcher.DispatchOptions` and `RetryOptions`. +- **retryHandlers** `RetryHandlers` (required) - Object containing the `dispatch` to be used on every retry, and `handler` for handling the `dispatch` lifecycle. + +Returns: `retryHandler` + +### Parameter: `Dispatch.DispatchOptions & RetryOptions` + +Extends: [`Dispatch.DispatchOptions`](/docs/docs/api/Dispatcher.md#parameter-dispatchoptions). + +#### `RetryOptions` + +- **throwOnError** `boolean` (optional) - Disable to prevent throwing error on last retry attept, useful if you need the body on errors from server or if you have custom error handler. +- **retry** `(err: Error, context: RetryContext, callback: (err?: Error | null) => void) => number | null` (optional) - Function to be called after every retry. It should pass error if no more retries should be performed. +- **maxRetries** `number` (optional) - Maximum number of retries. Default: `5` +- **maxTimeout** `number` (optional) - Maximum number of milliseconds to wait before retrying. Default: `30000` (30 seconds) +- **minTimeout** `number` (optional) - Minimum number of milliseconds to wait before retrying. Default: `500` (half a second) +- **timeoutFactor** `number` (optional) - Factor to multiply the timeout by for each retry attempt. Default: `2` +- **retryAfter** `boolean` (optional) - It enables automatic retry after the `Retry-After` header is received. Default: `true` +- +- **methods** `string[]` (optional) - Array of HTTP methods to retry. Default: `['GET', 'PUT', 'HEAD', 'OPTIONS', 'DELETE']` +- **statusCodes** `number[]` (optional) - Array of HTTP status codes to retry. Default: `[429, 500, 502, 503, 504]` +- **errorCodes** `string[]` (optional) - Array of Error codes to retry. Default: `['ECONNRESET', 'ECONNREFUSED', 'ENOTFOUND', 'ENETDOWN','ENETUNREACH', 'EHOSTDOWN', 'UND_ERR_SOCKET']` + +**`RetryContext`** + +- `state`: `RetryState` - Current retry state. It can be mutated. +- `opts`: `Dispatch.DispatchOptions & RetryOptions` - Options passed to the retry handler. + +**`RetryState`** + +It represents the retry state for a given request. + +- `counter`: `number` - Current retry attempt. + +### Parameter `RetryHandlers` + +- **dispatch** `(options: Dispatch.DispatchOptions, handlers: Dispatch.DispatchHandler) => Promise` (required) - Dispatch function to be called after every retry. +- **handler** Extends [`Dispatch.DispatchHandler`](/docs/docs/api/Dispatcher.md#dispatcherdispatchoptions-handler) (required) - Handler function to be called after the request is successful or the retries are exhausted. + +>__Note__: The `RetryHandler` does not retry over stateful bodies (e.g. streams, AsyncIterable) as those, once consumed, are left in a state that cannot be reutilized. For these situations the `RetryHandler` will identify +>the body as stateful and will not retry the request rejecting with the error `UND_ERR_REQ_RETRY`. + +Examples: + +```js +const client = new Client(`http://localhost:${server.address().port}`); +const chunks = []; +const handler = new RetryHandler( + { + ...dispatchOptions, + retryOptions: { + // custom retry function + retry: function (err, state, callback) { + counter++; + + if (err.code && err.code === "UND_ERR_DESTROYED") { + callback(err); + return; + } + + if (err.statusCode === 206) { + callback(err); + return; + } + + setTimeout(() => callback(null), 1000); + }, + }, + }, + { + dispatch: (...args) => { + return client.dispatch(...args); + }, + handler: { + onConnect() {}, + onBodySent() {}, + onHeaders(status, _rawHeaders, resume, _statusMessage) { + // do something with headers + }, + onData(chunk) { + chunks.push(chunk); + return true; + }, + onComplete() {}, + onError() { + // handle error properly + }, + }, + } +); +``` + +#### Example - Basic RetryHandler with defaults + +```js +const client = new Client(`http://localhost:${server.address().port}`); +const handler = new RetryHandler(dispatchOptions, { + dispatch: client.dispatch.bind(client), + handler: { + onConnect() {}, + onBodySent() {}, + onHeaders(status, _rawHeaders, resume, _statusMessage) {}, + onData(chunk) {}, + onComplete() {}, + onError(err) {}, + }, +}); +``` diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/SnapshotAgent.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/SnapshotAgent.md new file mode 100644 index 0000000000000000000000000000000000000000..e4c8f2484a5408ad908c96d473e3cb8f89b2875e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/SnapshotAgent.md @@ -0,0 +1,616 @@ +# SnapshotAgent + +The `SnapshotAgent` provides a powerful way to record and replay HTTP requests for testing purposes. It extends `MockAgent` to enable automatic snapshot testing, eliminating the need to manually define mock responses. + +## Use Cases + +- **Integration Testing**: Record real API interactions and replay them in tests +- **Offline Development**: Work with APIs without network connectivity +- **Consistent Test Data**: Ensure tests use the same responses across runs +- **API Contract Testing**: Capture and validate API behavior over time + +## Constructor + +```javascript +new SnapshotAgent([options]) +``` + +### Parameters + +- **options** `Object` (optional) + - **mode** `String` - The snapshot mode: `'record'`, `'playback'`, or `'update'`. Default: `'record'` + - **snapshotPath** `String` - Path to the snapshot file for loading/saving + - **maxSnapshots** `Number` - Maximum number of snapshots to keep in memory. Default: `Infinity` + - **autoFlush** `Boolean` - Whether to automatically save snapshots to disk. Default: `false` + - **flushInterval** `Number` - Interval in milliseconds for auto-flush. Default: `30000` + - **matchHeaders** `Array` - Specific headers to include in request matching. Default: all headers + - **ignoreHeaders** `Array` - Headers to ignore during request matching + - **excludeHeaders** `Array` - Headers to exclude from snapshots (for security) + - **matchBody** `Boolean` - Whether to include request body in matching. Default: `true` + - **matchQuery** `Boolean` - Whether to include query parameters in matching. Default: `true` + - **caseSensitive** `Boolean` - Whether header matching is case-sensitive. Default: `false` + - **shouldRecord** `Function` - Callback to determine if a request should be recorded + - **shouldPlayback** `Function` - Callback to determine if a request should be played back + - **excludeUrls** `Array` - URL patterns (strings or RegExp) to exclude from recording/playback + - All other options from `MockAgent` are supported + +### Modes + +#### Record Mode (`'record'`) +Makes real HTTP requests and saves the responses to snapshots. + +```javascript +import { SnapshotAgent, setGlobalDispatcher } from 'undici' + +const agent = new SnapshotAgent({ + mode: 'record', + snapshotPath: './test/snapshots/api-calls.json' +}) +setGlobalDispatcher(agent) + +// Makes real requests and records them +const response = await fetch('https://api.example.com/users') +const users = await response.json() + +// Save recorded snapshots +await agent.saveSnapshots() +``` + +#### Playback Mode (`'playback'`) +Replays recorded responses without making real HTTP requests. + +```javascript +import { SnapshotAgent, setGlobalDispatcher } from 'undici' + +const agent = new SnapshotAgent({ + mode: 'playback', + snapshotPath: './test/snapshots/api-calls.json' +}) +setGlobalDispatcher(agent) + +// Uses recorded response instead of real request +const response = await fetch('https://api.example.com/users') +``` + +#### Update Mode (`'update'`) +Uses existing snapshots when available, but records new ones for missing requests. + +```javascript +import { SnapshotAgent, setGlobalDispatcher } from 'undici' + +const agent = new SnapshotAgent({ + mode: 'update', + snapshotPath: './test/snapshots/api-calls.json' +}) +setGlobalDispatcher(agent) + +// Uses snapshot if exists, otherwise makes real request and records it +const response = await fetch('https://api.example.com/new-endpoint') +``` + +## Instance Methods + +### `agent.saveSnapshots([filePath])` + +Saves all recorded snapshots to a file. + +#### Parameters + +- **filePath** `String` (optional) - Path to save snapshots. Uses constructor `snapshotPath` if not provided. + +#### Returns + +`Promise` + +```javascript +await agent.saveSnapshots('./custom-snapshots.json') +``` + +## Advanced Configuration + +### Header Filtering + +Control which headers are used for request matching and what gets stored in snapshots: + +```javascript +const agent = new SnapshotAgent({ + mode: 'record', + snapshotPath: './snapshots.json', + + // Only match these specific headers + matchHeaders: ['content-type', 'accept'], + + // Ignore these headers during matching (but still store them) + ignoreHeaders: ['user-agent', 'date'], + + // Exclude sensitive headers from snapshots entirely + excludeHeaders: ['authorization', 'x-api-key', 'cookie'] +}) +``` + +### Custom Request/Response Filtering + +Use callback functions to determine what gets recorded or played back: + +```javascript +const agent = new SnapshotAgent({ + mode: 'record', + snapshotPath: './snapshots.json', + + // Only record GET requests to specific endpoints + shouldRecord: (requestOpts) => { + const url = new URL(requestOpts.path, requestOpts.origin) + return requestOpts.method === 'GET' && url.pathname.startsWith('/api/v1/') + }, + + // Skip authentication endpoints during playback + shouldPlayback: (requestOpts) => { + const url = new URL(requestOpts.path, requestOpts.origin) + return !url.pathname.includes('/auth/') + } +}) +``` + +### URL Pattern Exclusion + +Exclude specific URLs from recording/playback using patterns: + +```javascript +const agent = new SnapshotAgent({ + mode: 'record', + snapshotPath: './snapshots.json', + + excludeUrls: [ + 'https://analytics.example.com', // String match + /\/api\/v\d+\/health/, // Regex pattern + 'telemetry' // Substring match + ] +}) +``` + +### Memory Management + +Configure automatic memory and disk management: + +```javascript +const agent = new SnapshotAgent({ + mode: 'record', + snapshotPath: './snapshots.json', + + // Keep only 1000 snapshots in memory + maxSnapshots: 1000, + + // Automatically save to disk every 30 seconds + autoFlush: true, + flushInterval: 30000 +}) +``` + +### Sequential Response Handling + +Handle multiple responses for the same request (similar to nock): + +```javascript +// In record mode, multiple identical requests get recorded as separate responses +const agent = new SnapshotAgent({ mode: 'record', snapshotPath: './sequential.json' }) + +// First call returns response A +await fetch('https://api.example.com/random') + +// Second call returns response B +await fetch('https://api.example.com/random') + +await agent.saveSnapshots() + +// In playback mode, calls return responses in sequence +const playbackAgent = new SnapshotAgent({ mode: 'playback', snapshotPath: './sequential.json' }) + +// Returns response A +const first = await fetch('https://api.example.com/random') + +// Returns response B +const second = await fetch('https://api.example.com/random') + +// Third call repeats the last response (B) +const third = await fetch('https://api.example.com/random') +``` + +## Managing Snapshots + +### Replacing Existing Snapshots + +```javascript +// Load existing snapshots +await agent.loadSnapshots('./old-snapshots.json') + +// Get snapshot data +const recorder = agent.getRecorder() +const snapshots = recorder.getSnapshots() + +// Modify or filter snapshots +const filteredSnapshots = snapshots.filter(s => + !s.request.url.includes('deprecated') +) + +// Replace all snapshots +agent.replaceSnapshots(filteredSnapshots.map((snapshot, index) => ({ + hash: `new-hash-${index}`, + snapshot +}))) + +// Save updated snapshots +await agent.saveSnapshots('./updated-snapshots.json') +``` + +### `agent.loadSnapshots([filePath])` + +Loads snapshots from a file. + +#### Parameters + +- **filePath** `String` (optional) - Path to load snapshots from. Uses constructor `snapshotPath` if not provided. + +#### Returns + +`Promise` + +```javascript +await agent.loadSnapshots('./existing-snapshots.json') +``` + +### `agent.getRecorder()` + +Gets the underlying `SnapshotRecorder` instance. + +#### Returns + +`SnapshotRecorder` + +```javascript +const recorder = agent.getRecorder() +console.log(`Recorded ${recorder.size()} interactions`) +``` + +### `agent.getMode()` + +Gets the current snapshot mode. + +#### Returns + +`String` - The current mode (`'record'`, `'playback'`, or `'update'`) + +### `agent.clearSnapshots()` + +Clears all recorded snapshots from memory. + +```javascript +agent.clearSnapshots() +``` + +## Working with Different Request Types + +### GET Requests + +```javascript +// Record mode +const agent = new SnapshotAgent({ mode: 'record', snapshotPath: './get-snapshots.json' }) +setGlobalDispatcher(agent) + +const response = await fetch('https://jsonplaceholder.typicode.com/posts/1') +const post = await response.json() + +await agent.saveSnapshots() +``` + +### POST Requests with Body + +```javascript +// Record mode +const agent = new SnapshotAgent({ mode: 'record', snapshotPath: './post-snapshots.json' }) +setGlobalDispatcher(agent) + +const response = await fetch('https://jsonplaceholder.typicode.com/posts', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ title: 'Test Post', body: 'Content' }) +}) + +await agent.saveSnapshots() +``` + +### Using with `undici.request` + +SnapshotAgent works with all undici APIs, not just fetch: + +```javascript +import { SnapshotAgent, request, setGlobalDispatcher } from 'undici' + +const agent = new SnapshotAgent({ mode: 'record', snapshotPath: './request-snapshots.json' }) +setGlobalDispatcher(agent) + +const { statusCode, headers, body } = await request('https://api.example.com/data') +const data = await body.json() + +await agent.saveSnapshots() +``` + +## Test Integration + +### Basic Test Setup + +```javascript +import { test } from 'node:test' +import { SnapshotAgent, setGlobalDispatcher, getGlobalDispatcher } from 'undici' + +test('API integration test', async (t) => { + const originalDispatcher = getGlobalDispatcher() + + const agent = new SnapshotAgent({ + mode: 'playback', + snapshotPath: './test/snapshots/api-test.json' + }) + setGlobalDispatcher(agent) + + t.after(() => setGlobalDispatcher(originalDispatcher)) + + // This will use recorded data + const response = await fetch('https://api.example.com/users') + const users = await response.json() + + assert(Array.isArray(users)) + assert(users.length > 0) +}) +``` + +### Environment-Based Mode Selection + +```javascript +const mode = process.env.SNAPSHOT_MODE || 'playback' + +const agent = new SnapshotAgent({ + mode, + snapshotPath: './test/snapshots/integration.json' +}) + +// Run with: SNAPSHOT_MODE=record npm test (to record) +// Run with: npm test (to playback) +``` + +### Test Helper Function + +```javascript +function createSnapshotAgent(testName, mode = 'playback') { + return new SnapshotAgent({ + mode, + snapshotPath: `./test/snapshots/${testName}.json` + }) +} + +test('user API test', async (t) => { + const agent = createSnapshotAgent('user-api') + setGlobalDispatcher(agent) + + // Test implementation... +}) +``` + +## Snapshot File Format + +Snapshots are stored as JSON with the following structure: + +```json +[ + { + "hash": "dGVzdC1oYXNo...", + "snapshot": { + "request": { + "method": "GET", + "url": "https://api.example.com/users", + "headers": { + "authorization": "Bearer token" + }, + "body": undefined + }, + "response": { + "statusCode": 200, + "headers": { + "content-type": "application/json" + }, + "body": "eyJkYXRhIjoidGVzdCJ9", // base64 encoded + "trailers": {} + }, + "timestamp": "2024-01-01T00:00:00.000Z" + } + } +] +``` + +## Security Considerations + +### Sensitive Data in Snapshots + +By default, SnapshotAgent records all headers and request/response data. For production use, always exclude sensitive information: + +```javascript +const agent = new SnapshotAgent({ + mode: 'record', + snapshotPath: './snapshots.json', + + // Exclude sensitive headers from snapshots + excludeHeaders: [ + 'authorization', + 'x-api-key', + 'cookie', + 'set-cookie', + 'x-auth-token', + 'x-csrf-token' + ], + + // Filter out requests with sensitive data + shouldRecord: (requestOpts) => { + const url = new URL(requestOpts.path, requestOpts.origin) + + // Don't record authentication endpoints + if (url.pathname.includes('/auth/') || url.pathname.includes('/login')) { + return false + } + + // Don't record if request contains sensitive body data + if (requestOpts.body && typeof requestOpts.body === 'string') { + const body = requestOpts.body.toLowerCase() + if (body.includes('password') || body.includes('secret')) { + return false + } + } + + return true + } +}) +``` + +### Snapshot File Security + +**Important**: Snapshot files may contain sensitive data. Handle them securely: + +- ✅ Add snapshot files to `.gitignore` if they contain real API data +- ✅ Use environment-specific snapshots (dev/staging/prod) +- ✅ Regularly review snapshot contents for sensitive information +- ✅ Use the `excludeHeaders` option for production snapshots +- ❌ Never commit snapshots with real authentication tokens +- ❌ Don't share snapshot files containing personal data + +```gitignore +# Exclude snapshots with real data +/test/snapshots/production-*.json +/test/snapshots/*-real-data.json + +# Include sanitized test snapshots +!/test/snapshots/mock-*.json +``` + +## Error Handling + +### Missing Snapshots in Playback Mode + +```javascript +try { + const response = await fetch('https://api.example.com/nonexistent') +} catch (error) { + if (error.message.includes('No snapshot found')) { + // Handle missing snapshot + console.log('Snapshot not found for this request') + } +} +``` + +### Handling Network Errors in Record Mode + +```javascript +const agent = new SnapshotAgent({ mode: 'record', snapshotPath: './snapshots.json' }) + +try { + const response = await fetch('https://nonexistent-api.example.com/data') +} catch (error) { + // Network errors are not recorded as snapshots + console.log('Network error:', error.message) +} +``` + +## Best Practices + +### 1. Organize Snapshots by Test Suite + +```javascript +// Use descriptive snapshot file names +const agent = new SnapshotAgent({ + mode: 'playback', + snapshotPath: `./test/snapshots/${testSuiteName}-${testName}.json` +}) +``` + +### 2. Version Control Snapshots + +Add snapshot files to version control to ensure consistent test behavior across environments: + +```gitignore +# Include snapshots in version control +!/test/snapshots/*.json +``` + +### 3. Clean Up Test Data + +```javascript +test('API test', async (t) => { + const agent = new SnapshotAgent({ + mode: 'playback', + snapshotPath: './test/snapshots/temp-test.json' + }) + + // Clean up after test + t.after(() => { + agent.clearSnapshots() + }) +}) +``` + +### 4. Snapshot Validation + +```javascript +test('validate snapshot contents', async (t) => { + const agent = new SnapshotAgent({ + mode: 'playback', + snapshotPath: './test/snapshots/validation.json' + }) + + const recorder = agent.getRecorder() + const snapshots = recorder.getSnapshots() + + // Validate snapshot structure + assert(snapshots.length > 0, 'Should have recorded snapshots') + assert(snapshots[0].request.url.startsWith('https://'), 'Should use HTTPS') +}) +``` + +## Comparison with Other Tools + +### vs Manual MockAgent Setup + +**Manual MockAgent:** +```javascript +const mockAgent = new MockAgent() +const mockPool = mockAgent.get('https://api.example.com') + +mockPool.intercept({ + path: '/users', + method: 'GET' +}).reply(200, [ + { id: 1, name: 'User 1' }, + { id: 2, name: 'User 2' } +]) +``` + +**SnapshotAgent:** +```javascript +// Record once +const agent = new SnapshotAgent({ mode: 'record', snapshotPath: './snapshots.json' }) +// Real API call gets recorded automatically + +// Use in tests +const agent = new SnapshotAgent({ mode: 'playback', snapshotPath: './snapshots.json' }) +// Automatically replays recorded response +``` + +### vs nock + +SnapshotAgent provides similar functionality to nock but is specifically designed for undici: + +- ✅ Works with all undici APIs (`request`, `stream`, `pipeline`, etc.) +- ✅ Supports undici-specific features (RetryAgent, connection pooling) +- ✅ Better TypeScript integration +- ✅ More efficient for high-performance scenarios + +## See Also + +- [MockAgent](./MockAgent.md) - Manual mocking for more control +- [MockCallHistory](./MockCallHistory.md) - Inspecting request history +- [Testing Best Practices](../best-practices/writing-tests.md) - General testing guidance \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/Util.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/Util.md new file mode 100644 index 0000000000000000000000000000000000000000..53b96e3ed3f50300c5d2089b9823c91987a39e1b --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/Util.md @@ -0,0 +1,25 @@ +# Util + +Utility API for third-party implementations of the dispatcher API. + +## `parseHeaders(headers, [obj])` + +Receives a header object and returns the parsed value. + +Arguments: + +- **headers** `(Buffer | string | (Buffer | string)[])[]` (required) - Header object. + +- **obj** `Record` (optional) - Object to specify a proxy object. The parsed value is assigned to this object. But, if **headers** is an object, it is not used. + +Returns: `Record` If **obj** is specified, it is equivalent to **obj**. + +## `headerNameToString(value)` + +Retrieves a header name and returns its lowercase value. + +Arguments: + +- **value** `string | Buffer` (required) - Header name. + +Returns: `string` diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/WebSocket.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/WebSocket.md new file mode 100644 index 0000000000000000000000000000000000000000..9cc2937ce4c08515af94de1b159639efbdace410 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/WebSocket.md @@ -0,0 +1,112 @@ +# Class: WebSocket + +Extends: [`EventTarget`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget) + +The WebSocket object provides a way to manage a WebSocket connection to a server, allowing bidirectional communication. The API follows the [WebSocket spec](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) and [RFC 6455](https://datatracker.ietf.org/doc/html/rfc6455). + +## `new WebSocket(url[, protocol])` + +Arguments: + +* **url** `URL | string` +* **protocol** `string | string[] | WebSocketInit` (optional) - Subprotocol(s) to request the server use, or a [`Dispatcher`](/docs/docs/api/Dispatcher.md). + +### Example: + +This example will not work in browsers or other platforms that don't allow passing an object. + +```mjs +import { WebSocket, ProxyAgent } from 'undici' + +const proxyAgent = new ProxyAgent('my.proxy.server') + +const ws = new WebSocket('wss://echo.websocket.events', { + dispatcher: proxyAgent, + protocols: ['echo', 'chat'] +}) +``` + +If you do not need a custom Dispatcher, it's recommended to use the following pattern: + +```mjs +import { WebSocket } from 'undici' + +const ws = new WebSocket('wss://echo.websocket.events', ['echo', 'chat']) +``` + +# Class: WebSocketStream + +> ⚠️ Warning: the WebSocketStream API has not been finalized and is likely to change. + +See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/WebSocketStream) for more information. + +## `new WebSocketStream(url[, protocol])` + +Arguments: + +* **url** `URL | string` +* **options** `WebSocketStreamOptions` (optional) + +### WebSocketStream Example + +```js +const stream = new WebSocketStream('https://echo.websocket.org/') +const { readable, writable } = await stream.opened + +async function read () { + /** @type {ReadableStreamReader} */ + const reader = readable.getReader() + + while (true) { + const { done, value } = await reader.read() + if (done) break + + // do something with value + } +} + +async function write () { + /** @type {WritableStreamDefaultWriter} */ + const writer = writable.getWriter() + writer.write('Hello, world!') + writer.releaseLock() +} + +read() + +setInterval(() => write(), 5000) + +``` + +## ping(websocket, payload) +Arguments: + +* **websocket** `WebSocket` - The WebSocket instance to send the ping frame on +* **payload** `Buffer|undefined` (optional) - Optional payload data to include with the ping frame. Must not exceed 125 bytes. + +Sends a ping frame to the WebSocket server. The server must respond with a pong frame containing the same payload data. This can be used for keepalive purposes or to verify that the connection is still active. + +### Example: + +```js +import { WebSocket, ping } from 'undici' + +const ws = new WebSocket('wss://echo.websocket.events') + +ws.addEventListener('open', () => { + // Send ping with no payload + ping(ws) + + // Send ping with payload + const payload = Buffer.from('hello') + ping(ws, payload) +}) +``` + +**Note**: A ping frame cannot have a payload larger than 125 bytes. The ping will only be sent if the WebSocket connection is in the OPEN state. + +## Read More + +- [MDN - WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) +- [The WebSocket Specification](https://www.rfc-editor.org/rfc/rfc6455) +- [The WHATWG WebSocket Specification](https://websockets.spec.whatwg.org/) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/api-lifecycle.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/api-lifecycle.md new file mode 100644 index 0000000000000000000000000000000000000000..ee08292cc7d37a7b8bfef90c4fae76fe96c99548 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/api/api-lifecycle.md @@ -0,0 +1,91 @@ +# Client Lifecycle + +An Undici [Client](/docs/docs/api/Client.md) can be best described as a state machine. The following list is a summary of the various state transitions the `Client` will go through in its lifecycle. This document also contains detailed breakdowns of each state. + +> This diagram is not a perfect representation of the undici Client. Since the Client class is not actually implemented as a state-machine, actual execution may deviate slightly from what is described below. Consider this as a general resource for understanding the inner workings of the Undici client rather than some kind of formal specification. + +## State Transition Overview + +* A `Client` begins in the **idle** state with no socket connection and no requests in queue. + * The *connect* event transitions the `Client` to the **pending** state where requests can be queued prior to processing. + * The *close* and *destroy* events transition the `Client` to the **destroyed** state. Since there are no requests in the queue, the *close* event immediately transitions to the **destroyed** state. +* The **pending** state indicates the underlying socket connection has been successfully established and requests are queueing. + * The *process* event transitions the `Client` to the **processing** state where requests are processed. + * If requests are queued, the *close* event transitions to the **processing** state; otherwise, it transitions to the **destroyed** state. + * The *destroy* event transitions to the **destroyed** state. +* The **processing** state initializes to the **processing.running** state. + * If the current request requires draining, the *needDrain* event transitions the `Client` into the **processing.busy** state which will return to the **processing.running** state with the *drainComplete* event. + * After all queued requests are completed, the *keepalive* event transitions the `Client` back to the **pending** state. If no requests are queued during the timeout, the **close** event transitions the `Client` to the **destroyed** state. + * If the *close* event is fired while the `Client` still has queued requests, the `Client` transitions to the **process.closing** state where it will complete all existing requests before firing the *done* event. + * The *done* event gracefully transitions the `Client` to the **destroyed** state. + * At any point in time, the *destroy* event will transition the `Client` from the **processing** state to the **destroyed** state, destroying any queued requests. +* The **destroyed** state is a final state and the `Client` is no longer functional. + +A state diagram representing an Undici Client instance: + +```mermaid +stateDiagram-v2 + [*] --> idle + idle --> pending : connect + idle --> destroyed : destroy/close + + pending --> idle : timeout + pending --> destroyed : destroy + + state close_fork <> + pending --> close_fork : close + close_fork --> processing + close_fork --> destroyed + + pending --> processing : process + + processing --> pending : keepalive + processing --> destroyed : done + processing --> destroyed : destroy + + destroyed --> [*] + + state processing { + [*] --> running + running --> closing : close + running --> busy : needDrain + busy --> running : drainComplete + running --> [*] : keepalive + closing --> [*] : done + } +``` +## State details + +### idle + +The **idle** state is the initial state of a `Client` instance. While an `origin` is required for instantiating a `Client` instance, the underlying socket connection will not be established until a request is queued using [`Client.dispatch()`](/docs/docs/api/Client.md#clientdispatchoptions-handlers). By calling `Client.dispatch()` directly or using one of the multiple implementations ([`Client.connect()`](Client.md#clientconnectoptions-callback), [`Client.pipeline()`](Client.md#clientpipelineoptions-handler), [`Client.request()`](Client.md#clientrequestoptions-callback), [`Client.stream()`](Client.md#clientstreamoptions-factory-callback), and [`Client.upgrade()`](/docs/docs/api/Client.md#clientupgradeoptions-callback)), the `Client` instance will transition from **idle** to [**pending**](/docs/docs/api/Client.md#pending) and then most likely directly to [**processing**](/docs/docs/api/Client.md#processing). + +Calling [`Client.close()`](/docs/docs/api/Client.md#clientclosecallback) or [`Client.destroy()`](Client.md#clientdestroyerror-callback) transitions directly to the [**destroyed**](/docs/docs/api/Client.md#destroyed) state since the `Client` instance will have no queued requests in this state. + +### pending + +The **pending** state signifies a non-processing `Client`. Upon entering this state, the `Client` establishes a socket connection and emits the [`'connect'`](/docs/docs/api/Client.md#event-connect) event signalling a connection was successfully established with the `origin` provided during `Client` instantiation. The internal queue is initially empty, and requests can start queueing. + +Calling [`Client.close()`](/docs/docs/api/Client.md#clientclosecallback) with queued requests, transitions the `Client` to the [**processing**](/docs/docs/api/Client.md#processing) state. Without queued requests, it transitions to the [**destroyed**](/docs/docs/api/Client.md#destroyed) state. + +Calling [`Client.destroy()`](/docs/docs/api/Client.md#clientdestroyerror-callback) transitions directly to the [**destroyed**](/docs/docs/api/Client.md#destroyed) state regardless of existing requests. + +### processing + +The **processing** state is a state machine within itself. It initializes to the [**processing.running**](/docs/docs/api/Client.md#running) state. The [`Client.dispatch()`](/docs/docs/api/Client.md#clientdispatchoptions-handlers), [`Client.close()`](Client.md#clientclosecallback), and [`Client.destroy()`](Client.md#clientdestroyerror-callback) can be called at any time while the `Client` is in this state. `Client.dispatch()` will add more requests to the queue while existing requests continue to be processed. `Client.close()` will transition to the [**processing.closing**](/docs/docs/api/Client.md#closing) state. And `Client.destroy()` will transition to [**destroyed**](/docs/docs/api/Client.md#destroyed). + +#### running + +In the **processing.running** sub-state, queued requests are being processed in a FIFO order. If a request body requires draining, the *needDrain* event transitions to the [**processing.busy**](/docs/docs/api/Client.md#busy) sub-state. The *close* event transitions the Client to the [**process.closing**](/docs/docs/api/Client.md#closing) sub-state. If all queued requests are processed and neither [`Client.close()`](/docs/docs/api/Client.md#clientclosecallback) nor [`Client.destroy()`](Client.md#clientdestroyerror-callback) are called, then the [**processing**](/docs/docs/api/Client.md#processing) machine will trigger a *keepalive* event transitioning the `Client` back to the [**pending**](/docs/docs/api/Client.md#pending) state. During this time, the `Client` is waiting for the socket connection to timeout, and once it does, it triggers the *timeout* event and transitions to the [**idle**](/docs/docs/api/Client.md#idle) state. + +#### busy + +This sub-state is only entered when a request body is an instance of [Stream](https://nodejs.org/api/stream.html) and requires draining. The `Client` cannot process additional requests while in this state and must wait until the currently processing request body is completely drained before transitioning back to [**processing.running**](/docs/docs/api/Client.md#running). + +#### closing + +This sub-state is only entered when a `Client` instance has queued requests and the [`Client.close()`](/docs/docs/api/Client.md#clientclosecallback) method is called. In this state, the `Client` instance continues to process requests as usual, with the one exception that no additional requests can be queued. Once all of the queued requests are processed, the `Client` will trigger the *done* event gracefully entering the [**destroyed**](/docs/docs/api/Client.md#destroyed) state without an error. + +### destroyed + +The **destroyed** state is a final state for the `Client` instance. Once in this state, a `Client` is nonfunctional. Calling any other `Client` methods will result in an `ClientDestroyedError`. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/best-practices/client-certificate.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/best-practices/client-certificate.md new file mode 100644 index 0000000000000000000000000000000000000000..9ead733af9e87e0833cff2fdecff840950ffda14 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/best-practices/client-certificate.md @@ -0,0 +1,64 @@ +# Client certificate + +Client certificate authentication can be configured with the `Client`, the required options are passed along through the `connect` option. + +The client certificates must be signed by a trusted CA. The Node.js default is to trust the well-known CAs curated by Mozilla. + +Setting the server option `requestCert: true` tells the server to request the client certificate. + +The server option `rejectUnauthorized: false` allows us to handle any invalid certificate errors in client code. The `authorized` property on the socket of the incoming request will show if the client certificate was valid. The `authorizationError` property will give the reason if the certificate was not valid. + +### Client Certificate Authentication + +```js +const { readFileSync } = require('node:fs') +const { join } = require('node:path') +const { createServer } = require('node:https') +const { Client } = require('undici') + +const serverOptions = { + ca: [ + readFileSync(join(__dirname, 'client-ca-crt.pem'), 'utf8') + ], + key: readFileSync(join(__dirname, 'server-key.pem'), 'utf8'), + cert: readFileSync(join(__dirname, 'server-crt.pem'), 'utf8'), + requestCert: true, + rejectUnauthorized: false +} + +const server = createServer(serverOptions, (req, res) => { + // true if client cert is valid + if(req.client.authorized === true) { + console.log('valid') + } else { + console.error(req.client.authorizationError) + } + res.end() +}) + +server.listen(0, function () { + const tls = { + ca: [ + readFileSync(join(__dirname, 'server-ca-crt.pem'), 'utf8') + ], + key: readFileSync(join(__dirname, 'client-key.pem'), 'utf8'), + cert: readFileSync(join(__dirname, 'client-crt.pem'), 'utf8'), + rejectUnauthorized: false, + servername: 'agent1' + } + const client = new Client(`https://localhost:${server.address().port}`, { + connect: tls + }) + + client.request({ + path: '/', + method: 'GET' + }, (err, { body }) => { + body.on('data', (buf) => {}) + body.on('end', () => { + client.close() + server.close() + }) + }) +}) +``` diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/best-practices/mocking-request.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/best-practices/mocking-request.md new file mode 100644 index 0000000000000000000000000000000000000000..ce56a09f5ddc457c0eb55113c369a0c169cbb8a6 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/best-practices/mocking-request.md @@ -0,0 +1,190 @@ +# Mocking Request + +Undici has its own mocking [utility](/docs/docs/api/MockAgent.md). It allow us to intercept undici HTTP requests and return mocked values instead. It can be useful for testing purposes. + +Example: + +```js +// bank.mjs +import { request } from 'undici' + +export async function bankTransfer(recipient, amount) { + const { body } = await request('http://localhost:3000/bank-transfer', + { + method: 'POST', + headers: { + 'X-TOKEN-SECRET': 'SuperSecretToken', + }, + body: JSON.stringify({ + recipient, + amount + }) + } + ) + return await body.json() +} +``` + +And this is what the test file looks like: + +```js +// index.test.mjs +import { strict as assert } from 'node:assert' +import { MockAgent, setGlobalDispatcher, } from 'undici' +import { bankTransfer } from './bank.mjs' + +const mockAgent = new MockAgent(); + +setGlobalDispatcher(mockAgent); + +// Provide the base url to the request +const mockPool = mockAgent.get('http://localhost:3000'); + +// intercept the request +mockPool.intercept({ + path: '/bank-transfer', + method: 'POST', + headers: { + 'X-TOKEN-SECRET': 'SuperSecretToken', + }, + body: JSON.stringify({ + recipient: '1234567890', + amount: '100' + }) +}).reply(200, { + message: 'transaction processed' +}) + +const success = await bankTransfer('1234567890', '100') + +assert.deepEqual(success, { message: 'transaction processed' }) + +// if you dont want to check whether the body or the headers contain the same value +// just remove it from interceptor +mockPool.intercept({ + path: '/bank-transfer', + method: 'POST', +}).reply(400, { + message: 'bank account not found' +}) + +const badRequest = await bankTransfer('1234567890', '100') + +assert.deepEqual(badRequest, { message: 'bank account not found' }) +``` + +Explore other MockAgent functionality [here](/docs/docs/api/MockAgent.md) + +## Access agent call history + +Using a MockAgent also allows you to make assertions on the configuration used to make your request in your application. + +Here is an example : + +```js +// index.test.mjs +import { strict as assert } from 'node:assert' +import { MockAgent, setGlobalDispatcher, fetch } from 'undici' +import { app } from './app.mjs' + +// given an application server running on http://localhost:3000 +await app.start() + +// enable call history at instantiation +const mockAgent = new MockAgent({ enableCallHistory: true }) +// or after instantiation +mockAgent.enableCallHistory() + +setGlobalDispatcher(mockAgent) + +// this call is made (not intercepted) +await fetch(`http://localhost:3000/endpoint?query='hello'`, { + method: 'POST', + headers: { 'content-type': 'application/json' } + body: JSON.stringify({ data: '' }) +}) + +// access to the call history of the MockAgent (which register every call made intercepted or not) +assert.ok(mockAgent.getCallHistory()?.calls().length === 1) +assert.strictEqual(mockAgent.getCallHistory()?.firstCall()?.fullUrl, `http://localhost:3000/endpoint?query='hello'`) +assert.strictEqual(mockAgent.getCallHistory()?.firstCall()?.body, JSON.stringify({ data: '' })) +assert.deepStrictEqual(mockAgent.getCallHistory()?.firstCall()?.searchParams, { query: 'hello' }) +assert.strictEqual(mockAgent.getCallHistory()?.firstCall()?.port, '3000') +assert.strictEqual(mockAgent.getCallHistory()?.firstCall()?.host, 'localhost:3000') +assert.strictEqual(mockAgent.getCallHistory()?.firstCall()?.method, 'POST') +assert.strictEqual(mockAgent.getCallHistory()?.firstCall()?.path, '/endpoint') +assert.deepStrictEqual(mockAgent.getCallHistory()?.firstCall()?.headers, { 'content-type': 'application/json' }) + +// clear all call history logs +mockAgent.clearCallHistory() + +assert.ok(mockAgent.getCallHistory()?.calls().length === 0) +``` + +Calling `mockAgent.close()` will automatically clear and delete every call history for you. + +Explore other MockAgent functionality [here](/docs/docs/api/MockAgent.md) + +Explore other MockCallHistory functionality [here](/docs/docs/api/MockCallHistory.md) + +Explore other MockCallHistoryLog functionality [here](/docs/docs/api/MockCallHistoryLog.md) + +## Debug Mock Value + +When the interceptor and the request options are not the same, undici will automatically make a real HTTP request. To prevent real requests from being made, use `mockAgent.disableNetConnect()`: + +```js +const mockAgent = new MockAgent(); + +setGlobalDispatcher(mockAgent); +mockAgent.disableNetConnect() + +// Provide the base url to the request +const mockPool = mockAgent.get('http://localhost:3000'); + +mockPool.intercept({ + path: '/bank-transfer', + method: 'POST', +}).reply(200, { + message: 'transaction processed' +}) + +const badRequest = await bankTransfer('1234567890', '100') +// Will throw an error +// MockNotMatchedError: Mock dispatch not matched for path '/bank-transfer': +// subsequent request to origin http://localhost:3000 was not allowed (net.connect disabled) +``` + +## Reply with data based on request + +If the mocked response needs to be dynamically derived from the request parameters, you can provide a function instead of an object to `reply`: + +```js +mockPool.intercept({ + path: '/bank-transfer', + method: 'POST', + headers: { + 'X-TOKEN-SECRET': 'SuperSecretToken', + }, + body: JSON.stringify({ + recipient: '1234567890', + amount: '100' + }) +}).reply(200, (opts) => { + // do something with opts + + return { message: 'transaction processed' } +}) +``` + +in this case opts will be + +``` +{ + method: 'POST', + headers: { 'X-TOKEN-SECRET': 'SuperSecretToken' }, + body: '{"recipient":"1234567890","amount":"100"}', + origin: 'http://localhost:3000', + path: '/bank-transfer' +} +``` diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/best-practices/proxy.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/best-practices/proxy.md new file mode 100644 index 0000000000000000000000000000000000000000..8b1a7210e8c8b6ca3461c08db2cb383ecff5255f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/best-practices/proxy.md @@ -0,0 +1,127 @@ +# Connecting through a proxy + +Connecting through a proxy is possible by: + +- Using [ProxyAgent](/docs/docs/api/ProxyAgent.md). +- Configuring `Client` or `Pool` constructor. + +The proxy url should be passed to the `Client` or `Pool` constructor, while the upstream server url +should be added to every request call in the `path`. +For instance, if you need to send a request to the `/hello` route of your upstream server, +the `path` should be `path: 'http://upstream.server:port/hello?foo=bar'`. + +If you proxy requires basic authentication, you can send it via the `proxy-authorization` header. + +### Connect without authentication + +```js +import { Client } from 'undici' +import { createServer } from 'http' +import { createProxy } from 'proxy' + +const server = await buildServer() +const proxyServer = await buildProxy() + +const serverUrl = `http://localhost:${server.address().port}` +const proxyUrl = `http://localhost:${proxyServer.address().port}` + +server.on('request', (req, res) => { + console.log(req.url) // '/hello?foo=bar' + res.setHeader('content-type', 'application/json') + res.end(JSON.stringify({ hello: 'world' })) +}) + +const client = new Client(proxyUrl) + +const response = await client.request({ + method: 'GET', + path: serverUrl + '/hello?foo=bar' +}) + +response.body.setEncoding('utf8') +let data = '' +for await (const chunk of response.body) { + data += chunk +} +console.log(response.statusCode) // 200 +console.log(JSON.parse(data)) // { hello: 'world' } + +server.close() +proxyServer.close() +client.close() + +function buildServer () { + return new Promise((resolve, reject) => { + const server = createServer() + server.listen(0, () => resolve(server)) + }) +} + +function buildProxy () { + return new Promise((resolve, reject) => { + const server = createProxy(createServer()) + server.listen(0, () => resolve(server)) + }) +} +``` + +### Connect with authentication + +```js +import { Client } from 'undici' +import { createServer } from 'http' +import { createProxy } from 'proxy' + +const server = await buildServer() +const proxyServer = await buildProxy() + +const serverUrl = `http://localhost:${server.address().port}` +const proxyUrl = `http://localhost:${proxyServer.address().port}` + +proxyServer.authenticate = function (req) { + return req.headers['proxy-authorization'] === `Basic ${Buffer.from('user:pass').toString('base64')}` +} + +server.on('request', (req, res) => { + console.log(req.url) // '/hello?foo=bar' + res.setHeader('content-type', 'application/json') + res.end(JSON.stringify({ hello: 'world' })) +}) + +const client = new Client(proxyUrl) + +const response = await client.request({ + method: 'GET', + path: serverUrl + '/hello?foo=bar', + headers: { + 'proxy-authorization': `Basic ${Buffer.from('user:pass').toString('base64')}` + } +}) + +response.body.setEncoding('utf8') +let data = '' +for await (const chunk of response.body) { + data += chunk +} +console.log(response.statusCode) // 200 +console.log(JSON.parse(data)) // { hello: 'world' } + +server.close() +proxyServer.close() +client.close() + +function buildServer () { + return new Promise((resolve, reject) => { + const server = createServer() + server.listen(0, () => resolve(server)) + }) +} + +function buildProxy () { + return new Promise((resolve, reject) => { + const server = createProxy(createServer()) + server.listen(0, () => resolve(server)) + }) +} +``` + diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/best-practices/writing-tests.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/best-practices/writing-tests.md new file mode 100644 index 0000000000000000000000000000000000000000..57549de63572a7eccf5f63f52129886e8aa07777 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/docs/docs/best-practices/writing-tests.md @@ -0,0 +1,20 @@ +# Writing tests + +Undici is tuned for a production use case and its default will keep +a socket open for a few seconds after an HTTP request is completed to +remove the overhead of opening up a new socket. These settings that makes +Undici shine in production are not a good fit for using Undici in automated +tests, as it will result in longer execution times. + +The following are good defaults that will keep the socket open for only 10ms: + +```js +import { request, setGlobalDispatcher, Agent } from 'undici' + +const agent = new Agent({ + keepAliveTimeout: 10, // milliseconds + keepAliveMaxTimeout: 10 // milliseconds +}) + +setGlobalDispatcher(agent) +``` diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/api/abort-signal.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/api/abort-signal.js new file mode 100644 index 0000000000000000000000000000000000000000..608170b4316560798784ea60d754985eeb84d060 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/api/abort-signal.js @@ -0,0 +1,59 @@ +'use strict' + +const { addAbortListener } = require('../core/util') +const { RequestAbortedError } = require('../core/errors') + +const kListener = Symbol('kListener') +const kSignal = Symbol('kSignal') + +function abort (self) { + if (self.abort) { + self.abort(self[kSignal]?.reason) + } else { + self.reason = self[kSignal]?.reason ?? new RequestAbortedError() + } + removeSignal(self) +} + +function addSignal (self, signal) { + self.reason = null + + self[kSignal] = null + self[kListener] = null + + if (!signal) { + return + } + + if (signal.aborted) { + abort(self) + return + } + + self[kSignal] = signal + self[kListener] = () => { + abort(self) + } + + addAbortListener(self[kSignal], self[kListener]) +} + +function removeSignal (self) { + if (!self[kSignal]) { + return + } + + if ('removeEventListener' in self[kSignal]) { + self[kSignal].removeEventListener('abort', self[kListener]) + } else { + self[kSignal].removeListener('abort', self[kListener]) + } + + self[kSignal] = null + self[kListener] = null +} + +module.exports = { + addSignal, + removeSignal +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/api/api-connect.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/api/api-connect.js new file mode 100644 index 0000000000000000000000000000000000000000..c8b86dd7d534166ca6e81c7557117f57cce59477 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/api/api-connect.js @@ -0,0 +1,110 @@ +'use strict' + +const assert = require('node:assert') +const { AsyncResource } = require('node:async_hooks') +const { InvalidArgumentError, SocketError } = require('../core/errors') +const util = require('../core/util') +const { addSignal, removeSignal } = require('./abort-signal') + +class ConnectHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + const { signal, opaque, responseHeaders } = opts + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + super('UNDICI_CONNECT') + + this.opaque = opaque || null + this.responseHeaders = responseHeaders || null + this.callback = callback + this.abort = null + + addSignal(this, signal) + } + + onConnect (abort, context) { + if (this.reason) { + abort(this.reason) + return + } + + assert(this.callback) + + this.abort = abort + this.context = context + } + + onHeaders () { + throw new SocketError('bad connect', null) + } + + onUpgrade (statusCode, rawHeaders, socket) { + const { callback, opaque, context } = this + + removeSignal(this) + + this.callback = null + + let headers = rawHeaders + // Indicates is an HTTP2Session + if (headers != null) { + headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + } + + this.runInAsyncScope(callback, null, null, { + statusCode, + headers, + socket, + opaque, + context + }) + } + + onError (err) { + const { callback, opaque } = this + + removeSignal(this) + + if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } + } +} + +function connect (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + connect.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + try { + const connectHandler = new ConnectHandler(opts, callback) + const connectOptions = { ...opts, method: 'CONNECT' } + + this.dispatch(connectOptions, connectHandler) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts?.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} + +module.exports = connect diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/api/api-pipeline.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/api/api-pipeline.js new file mode 100644 index 0000000000000000000000000000000000000000..77f3520a83f04c56ce87658620b136e9e64b54f3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/api/api-pipeline.js @@ -0,0 +1,252 @@ +'use strict' + +const { + Readable, + Duplex, + PassThrough +} = require('node:stream') +const assert = require('node:assert') +const { AsyncResource } = require('node:async_hooks') +const { + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError +} = require('../core/errors') +const util = require('../core/util') +const { addSignal, removeSignal } = require('./abort-signal') + +function noop () {} + +const kResume = Symbol('resume') + +class PipelineRequest extends Readable { + constructor () { + super({ autoDestroy: true }) + + this[kResume] = null + } + + _read () { + const { [kResume]: resume } = this + + if (resume) { + this[kResume] = null + resume() + } + } + + _destroy (err, callback) { + this._read() + + callback(err) + } +} + +class PipelineResponse extends Readable { + constructor (resume) { + super({ autoDestroy: true }) + this[kResume] = resume + } + + _read () { + this[kResume]() + } + + _destroy (err, callback) { + if (!err && !this._readableState.endEmitted) { + err = new RequestAbortedError() + } + + callback(err) + } +} + +class PipelineHandler extends AsyncResource { + constructor (opts, handler) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + if (typeof handler !== 'function') { + throw new InvalidArgumentError('invalid handler') + } + + const { signal, method, opaque, onInfo, responseHeaders } = opts + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } + + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } + + super('UNDICI_PIPELINE') + + this.opaque = opaque || null + this.responseHeaders = responseHeaders || null + this.handler = handler + this.abort = null + this.context = null + this.onInfo = onInfo || null + + this.req = new PipelineRequest().on('error', noop) + + this.ret = new Duplex({ + readableObjectMode: opts.objectMode, + autoDestroy: true, + read: () => { + const { body } = this + + if (body?.resume) { + body.resume() + } + }, + write: (chunk, encoding, callback) => { + const { req } = this + + if (req.push(chunk, encoding) || req._readableState.destroyed) { + callback() + } else { + req[kResume] = callback + } + }, + destroy: (err, callback) => { + const { body, req, res, ret, abort } = this + + if (!err && !ret._readableState.endEmitted) { + err = new RequestAbortedError() + } + + if (abort && err) { + abort() + } + + util.destroy(body, err) + util.destroy(req, err) + util.destroy(res, err) + + removeSignal(this) + + callback(err) + } + }).on('prefinish', () => { + const { req } = this + + // Node < 15 does not call _final in same tick. + req.push(null) + }) + + this.res = null + + addSignal(this, signal) + } + + onConnect (abort, context) { + const { res } = this + + if (this.reason) { + abort(this.reason) + return + } + + assert(!res, 'pipeline cannot be retried') + + this.abort = abort + this.context = context + } + + onHeaders (statusCode, rawHeaders, resume) { + const { opaque, handler, context } = this + + if (statusCode < 200) { + if (this.onInfo) { + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + this.onInfo({ statusCode, headers }) + } + return + } + + this.res = new PipelineResponse(resume) + + let body + try { + this.handler = null + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + body = this.runInAsyncScope(handler, null, { + statusCode, + headers, + opaque, + body: this.res, + context + }) + } catch (err) { + this.res.on('error', noop) + throw err + } + + if (!body || typeof body.on !== 'function') { + throw new InvalidReturnValueError('expected Readable') + } + + body + .on('data', (chunk) => { + const { ret, body } = this + + if (!ret.push(chunk) && body.pause) { + body.pause() + } + }) + .on('error', (err) => { + const { ret } = this + + util.destroy(ret, err) + }) + .on('end', () => { + const { ret } = this + + ret.push(null) + }) + .on('close', () => { + const { ret } = this + + if (!ret._readableState.ended) { + util.destroy(ret, new RequestAbortedError()) + } + }) + + this.body = body + } + + onData (chunk) { + const { res } = this + return res.push(chunk) + } + + onComplete (trailers) { + const { res } = this + res.push(null) + } + + onError (err) { + const { ret } = this + this.handler = null + util.destroy(ret, err) + } +} + +function pipeline (opts, handler) { + try { + const pipelineHandler = new PipelineHandler(opts, handler) + this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler) + return pipelineHandler.ret + } catch (err) { + return new PassThrough().destroy(err) + } +} + +module.exports = pipeline diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/api/api-request.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/api/api-request.js new file mode 100644 index 0000000000000000000000000000000000000000..9ae7ed6c7409495699afb6e3d172c00d8c7bd436 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/api/api-request.js @@ -0,0 +1,199 @@ +'use strict' + +const assert = require('node:assert') +const { AsyncResource } = require('node:async_hooks') +const { Readable } = require('./readable') +const { InvalidArgumentError, RequestAbortedError } = require('../core/errors') +const util = require('../core/util') + +function noop () {} + +class RequestHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + const { signal, method, opaque, body, onInfo, responseHeaders, highWaterMark } = opts + + try { + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) { + throw new InvalidArgumentError('invalid highWaterMark') + } + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } + + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } + + super('UNDICI_REQUEST') + } catch (err) { + if (util.isStream(body)) { + util.destroy(body.on('error', noop), err) + } + throw err + } + + this.method = method + this.responseHeaders = responseHeaders || null + this.opaque = opaque || null + this.callback = callback + this.res = null + this.abort = null + this.body = body + this.trailers = {} + this.context = null + this.onInfo = onInfo || null + this.highWaterMark = highWaterMark + this.reason = null + this.removeAbortListener = null + + if (signal?.aborted) { + this.reason = signal.reason ?? new RequestAbortedError() + } else if (signal) { + this.removeAbortListener = util.addAbortListener(signal, () => { + this.reason = signal.reason ?? new RequestAbortedError() + if (this.res) { + util.destroy(this.res.on('error', noop), this.reason) + } else if (this.abort) { + this.abort(this.reason) + } + }) + } + } + + onConnect (abort, context) { + if (this.reason) { + abort(this.reason) + return + } + + assert(this.callback) + + this.abort = abort + this.context = context + } + + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this + + const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + + if (statusCode < 200) { + if (this.onInfo) { + this.onInfo({ statusCode, headers }) + } + return + } + + const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers + const contentType = parsedHeaders['content-type'] + const contentLength = parsedHeaders['content-length'] + const res = new Readable({ + resume, + abort, + contentType, + contentLength: this.method !== 'HEAD' && contentLength + ? Number(contentLength) + : null, + highWaterMark + }) + + if (this.removeAbortListener) { + res.on('close', this.removeAbortListener) + this.removeAbortListener = null + } + + this.callback = null + this.res = res + if (callback !== null) { + this.runInAsyncScope(callback, null, null, { + statusCode, + headers, + trailers: this.trailers, + opaque, + body: res, + context + }) + } + } + + onData (chunk) { + return this.res.push(chunk) + } + + onComplete (trailers) { + util.parseHeaders(trailers, this.trailers) + this.res.push(null) + } + + onError (err) { + const { res, callback, body, opaque } = this + + if (callback) { + // TODO: Does this need queueMicrotask? + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } + + if (res) { + this.res = null + // Ensure all queued handlers are invoked before destroying res. + queueMicrotask(() => { + util.destroy(res.on('error', noop), err) + }) + } + + if (body) { + this.body = null + + if (util.isStream(body)) { + body.on('error', noop) + util.destroy(body, err) + } + } + + if (this.removeAbortListener) { + this.removeAbortListener() + this.removeAbortListener = null + } + } +} + +function request (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + request.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + try { + const handler = new RequestHandler(opts, callback) + + this.dispatch(opts, handler) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts?.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} + +module.exports = request +module.exports.RequestHandler = RequestHandler diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/api/api-stream.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/api/api-stream.js new file mode 100644 index 0000000000000000000000000000000000000000..5d0b3fbe633271ff79edb54680bdea8140ed14c2 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/api/api-stream.js @@ -0,0 +1,209 @@ +'use strict' + +const assert = require('node:assert') +const { finished } = require('node:stream') +const { AsyncResource } = require('node:async_hooks') +const { InvalidArgumentError, InvalidReturnValueError } = require('../core/errors') +const util = require('../core/util') +const { addSignal, removeSignal } = require('./abort-signal') + +function noop () {} + +class StreamHandler extends AsyncResource { + constructor (opts, factory, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + const { signal, method, opaque, body, onInfo, responseHeaders } = opts + + try { + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + if (typeof factory !== 'function') { + throw new InvalidArgumentError('invalid factory') + } + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } + + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } + + super('UNDICI_STREAM') + } catch (err) { + if (util.isStream(body)) { + util.destroy(body.on('error', noop), err) + } + throw err + } + + this.responseHeaders = responseHeaders || null + this.opaque = opaque || null + this.factory = factory + this.callback = callback + this.res = null + this.abort = null + this.context = null + this.trailers = null + this.body = body + this.onInfo = onInfo || null + + if (util.isStream(body)) { + body.on('error', (err) => { + this.onError(err) + }) + } + + addSignal(this, signal) + } + + onConnect (abort, context) { + if (this.reason) { + abort(this.reason) + return + } + + assert(this.callback) + + this.abort = abort + this.context = context + } + + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const { factory, opaque, context, responseHeaders } = this + + const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + + if (statusCode < 200) { + if (this.onInfo) { + this.onInfo({ statusCode, headers }) + } + return + } + + this.factory = null + + if (factory === null) { + return + } + + const res = this.runInAsyncScope(factory, null, { + statusCode, + headers, + opaque, + context + }) + + if ( + !res || + typeof res.write !== 'function' || + typeof res.end !== 'function' || + typeof res.on !== 'function' + ) { + throw new InvalidReturnValueError('expected Writable') + } + + // TODO: Avoid finished. It registers an unnecessary amount of listeners. + finished(res, { readable: false }, (err) => { + const { callback, res, opaque, trailers, abort } = this + + this.res = null + if (err || !res?.readable) { + util.destroy(res, err) + } + + this.callback = null + this.runInAsyncScope(callback, null, err || null, { opaque, trailers }) + + if (err) { + abort() + } + }) + + res.on('drain', resume) + + this.res = res + + const needDrain = res.writableNeedDrain !== undefined + ? res.writableNeedDrain + : res._writableState?.needDrain + + return needDrain !== true + } + + onData (chunk) { + const { res } = this + + return res ? res.write(chunk) : true + } + + onComplete (trailers) { + const { res } = this + + removeSignal(this) + + if (!res) { + return + } + + this.trailers = util.parseHeaders(trailers) + + res.end() + } + + onError (err) { + const { res, callback, opaque, body } = this + + removeSignal(this) + + this.factory = null + + if (res) { + this.res = null + util.destroy(res, err) + } else if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } + + if (body) { + this.body = null + util.destroy(body, err) + } + } +} + +function stream (opts, factory, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + stream.call(this, opts, factory, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + try { + const handler = new StreamHandler(opts, factory, callback) + + this.dispatch(opts, handler) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts?.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} + +module.exports = stream diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/api/api-upgrade.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/api/api-upgrade.js new file mode 100644 index 0000000000000000000000000000000000000000..f6efdc98626515a0dca594ce12329286f0792cb6 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/api/api-upgrade.js @@ -0,0 +1,110 @@ +'use strict' + +const { InvalidArgumentError, SocketError } = require('../core/errors') +const { AsyncResource } = require('node:async_hooks') +const assert = require('node:assert') +const util = require('../core/util') +const { addSignal, removeSignal } = require('./abort-signal') + +class UpgradeHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + const { signal, opaque, responseHeaders } = opts + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + super('UNDICI_UPGRADE') + + this.responseHeaders = responseHeaders || null + this.opaque = opaque || null + this.callback = callback + this.abort = null + this.context = null + + addSignal(this, signal) + } + + onConnect (abort, context) { + if (this.reason) { + abort(this.reason) + return + } + + assert(this.callback) + + this.abort = abort + this.context = null + } + + onHeaders () { + throw new SocketError('bad upgrade', null) + } + + onUpgrade (statusCode, rawHeaders, socket) { + assert(statusCode === 101) + + const { callback, opaque, context } = this + + removeSignal(this) + + this.callback = null + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + this.runInAsyncScope(callback, null, null, { + headers, + socket, + opaque, + context + }) + } + + onError (err) { + const { callback, opaque } = this + + removeSignal(this) + + if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } + } +} + +function upgrade (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + upgrade.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + try { + const upgradeHandler = new UpgradeHandler(opts, callback) + const upgradeOpts = { + ...opts, + method: opts.method || 'GET', + upgrade: opts.protocol || 'Websocket' + } + + this.dispatch(upgradeOpts, upgradeHandler) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts?.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} + +module.exports = upgrade diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/api/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/api/index.js new file mode 100644 index 0000000000000000000000000000000000000000..8983a5e746f5dbd57acac8330e65299b57a9f3ad --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/api/index.js @@ -0,0 +1,7 @@ +'use strict' + +module.exports.request = require('./api-request') +module.exports.stream = require('./api-stream') +module.exports.pipeline = require('./api-pipeline') +module.exports.upgrade = require('./api-upgrade') +module.exports.connect = require('./api-connect') diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/api/readable.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/api/readable.js new file mode 100644 index 0000000000000000000000000000000000000000..b5fd12dd30382bfdb4da06d5c179d34211213b2a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/api/readable.js @@ -0,0 +1,578 @@ +'use strict' + +const assert = require('node:assert') +const { Readable } = require('node:stream') +const { RequestAbortedError, NotSupportedError, InvalidArgumentError, AbortError } = require('../core/errors') +const util = require('../core/util') +const { ReadableStreamFrom } = require('../core/util') + +const kConsume = Symbol('kConsume') +const kReading = Symbol('kReading') +const kBody = Symbol('kBody') +const kAbort = Symbol('kAbort') +const kContentType = Symbol('kContentType') +const kContentLength = Symbol('kContentLength') +const kUsed = Symbol('kUsed') +const kBytesRead = Symbol('kBytesRead') + +const noop = () => {} + +/** + * @class + * @extends {Readable} + * @see https://fetch.spec.whatwg.org/#body + */ +class BodyReadable extends Readable { + /** + * @param {object} opts + * @param {(this: Readable, size: number) => void} opts.resume + * @param {() => (void | null)} opts.abort + * @param {string} [opts.contentType = ''] + * @param {number} [opts.contentLength] + * @param {number} [opts.highWaterMark = 64 * 1024] + */ + constructor ({ + resume, + abort, + contentType = '', + contentLength, + highWaterMark = 64 * 1024 // Same as nodejs fs streams. + }) { + super({ + autoDestroy: true, + read: resume, + highWaterMark + }) + + this._readableState.dataEmitted = false + + this[kAbort] = abort + + /** @type {Consume | null} */ + this[kConsume] = null + + /** @type {number} */ + this[kBytesRead] = 0 + + /** @type {ReadableStream|null} */ + this[kBody] = null + + /** @type {boolean} */ + this[kUsed] = false + + /** @type {string} */ + this[kContentType] = contentType + + /** @type {number|null} */ + this[kContentLength] = Number.isFinite(contentLength) ? contentLength : null + + /** + * Is stream being consumed through Readable API? + * This is an optimization so that we avoid checking + * for 'data' and 'readable' listeners in the hot path + * inside push(). + * + * @type {boolean} + */ + this[kReading] = false + } + + /** + * @param {Error|null} err + * @param {(error:(Error|null)) => void} callback + * @returns {void} + */ + _destroy (err, callback) { + if (!err && !this._readableState.endEmitted) { + err = new RequestAbortedError() + } + + if (err) { + this[kAbort]() + } + + // Workaround for Node "bug". If the stream is destroyed in same + // tick as it is created, then a user who is waiting for a + // promise (i.e micro tick) for installing an 'error' listener will + // never get a chance and will always encounter an unhandled exception. + if (!this[kUsed]) { + setImmediate(callback, err) + } else { + callback(err) + } + } + + /** + * @param {string|symbol} event + * @param {(...args: any[]) => void} listener + * @returns {this} + */ + on (event, listener) { + if (event === 'data' || event === 'readable') { + this[kReading] = true + this[kUsed] = true + } + return super.on(event, listener) + } + + /** + * @param {string|symbol} event + * @param {(...args: any[]) => void} listener + * @returns {this} + */ + addListener (event, listener) { + return this.on(event, listener) + } + + /** + * @param {string|symbol} event + * @param {(...args: any[]) => void} listener + * @returns {this} + */ + off (event, listener) { + const ret = super.off(event, listener) + if (event === 'data' || event === 'readable') { + this[kReading] = ( + this.listenerCount('data') > 0 || + this.listenerCount('readable') > 0 + ) + } + return ret + } + + /** + * @param {string|symbol} event + * @param {(...args: any[]) => void} listener + * @returns {this} + */ + removeListener (event, listener) { + return this.off(event, listener) + } + + /** + * @param {Buffer|null} chunk + * @returns {boolean} + */ + push (chunk) { + if (chunk) { + this[kBytesRead] += chunk.length + if (this[kConsume]) { + consumePush(this[kConsume], chunk) + return this[kReading] ? super.push(chunk) : true + } + } + + return super.push(chunk) + } + + /** + * Consumes and returns the body as a string. + * + * @see https://fetch.spec.whatwg.org/#dom-body-text + * @returns {Promise} + */ + text () { + return consume(this, 'text') + } + + /** + * Consumes and returns the body as a JavaScript Object. + * + * @see https://fetch.spec.whatwg.org/#dom-body-json + * @returns {Promise} + */ + json () { + return consume(this, 'json') + } + + /** + * Consumes and returns the body as a Blob + * + * @see https://fetch.spec.whatwg.org/#dom-body-blob + * @returns {Promise} + */ + blob () { + return consume(this, 'blob') + } + + /** + * Consumes and returns the body as an Uint8Array. + * + * @see https://fetch.spec.whatwg.org/#dom-body-bytes + * @returns {Promise} + */ + bytes () { + return consume(this, 'bytes') + } + + /** + * Consumes and returns the body as an ArrayBuffer. + * + * @see https://fetch.spec.whatwg.org/#dom-body-arraybuffer + * @returns {Promise} + */ + arrayBuffer () { + return consume(this, 'arrayBuffer') + } + + /** + * Not implemented + * + * @see https://fetch.spec.whatwg.org/#dom-body-formdata + * @throws {NotSupportedError} + */ + async formData () { + // TODO: Implement. + throw new NotSupportedError() + } + + /** + * Returns true if the body is not null and the body has been consumed. + * Otherwise, returns false. + * + * @see https://fetch.spec.whatwg.org/#dom-body-bodyused + * @readonly + * @returns {boolean} + */ + get bodyUsed () { + return util.isDisturbed(this) + } + + /** + * @see https://fetch.spec.whatwg.org/#dom-body-body + * @readonly + * @returns {ReadableStream} + */ + get body () { + if (!this[kBody]) { + this[kBody] = ReadableStreamFrom(this) + if (this[kConsume]) { + // TODO: Is this the best way to force a lock? + this[kBody].getReader() // Ensure stream is locked. + assert(this[kBody].locked) + } + } + return this[kBody] + } + + /** + * Dumps the response body by reading `limit` number of bytes. + * @param {object} opts + * @param {number} [opts.limit = 131072] Number of bytes to read. + * @param {AbortSignal} [opts.signal] An AbortSignal to cancel the dump. + * @returns {Promise} + */ + async dump (opts) { + const signal = opts?.signal + + if (signal != null && (typeof signal !== 'object' || !('aborted' in signal))) { + throw new InvalidArgumentError('signal must be an AbortSignal') + } + + const limit = opts?.limit && Number.isFinite(opts.limit) + ? opts.limit + : 128 * 1024 + + signal?.throwIfAborted() + + if (this._readableState.closeEmitted) { + return null + } + + return await new Promise((resolve, reject) => { + if ( + (this[kContentLength] && (this[kContentLength] > limit)) || + this[kBytesRead] > limit + ) { + this.destroy(new AbortError()) + } + + if (signal) { + const onAbort = () => { + this.destroy(signal.reason ?? new AbortError()) + } + signal.addEventListener('abort', onAbort) + this + .on('close', function () { + signal.removeEventListener('abort', onAbort) + if (signal.aborted) { + reject(signal.reason ?? new AbortError()) + } else { + resolve(null) + } + }) + } else { + this.on('close', resolve) + } + + this + .on('error', noop) + .on('data', () => { + if (this[kBytesRead] > limit) { + this.destroy() + } + }) + .resume() + }) + } + + /** + * @param {BufferEncoding} encoding + * @returns {this} + */ + setEncoding (encoding) { + if (Buffer.isEncoding(encoding)) { + this._readableState.encoding = encoding + } + return this + } +} + +/** + * @see https://streams.spec.whatwg.org/#readablestream-locked + * @param {BodyReadable} bodyReadable + * @returns {boolean} + */ +function isLocked (bodyReadable) { + // Consume is an implicit lock. + return bodyReadable[kBody]?.locked === true || bodyReadable[kConsume] !== null +} + +/** + * @see https://fetch.spec.whatwg.org/#body-unusable + * @param {BodyReadable} bodyReadable + * @returns {boolean} + */ +function isUnusable (bodyReadable) { + return util.isDisturbed(bodyReadable) || isLocked(bodyReadable) +} + +/** + * @typedef {'text' | 'json' | 'blob' | 'bytes' | 'arrayBuffer'} ConsumeType + */ + +/** + * @template {ConsumeType} T + * @typedef {T extends 'text' ? string : + * T extends 'json' ? unknown : + * T extends 'blob' ? Blob : + * T extends 'arrayBuffer' ? ArrayBuffer : + * T extends 'bytes' ? Uint8Array : + * never + * } ConsumeReturnType + */ +/** + * @typedef {object} Consume + * @property {ConsumeType} type + * @property {BodyReadable} stream + * @property {((value?: any) => void)} resolve + * @property {((err: Error) => void)} reject + * @property {number} length + * @property {Buffer[]} body + */ + +/** + * @template {ConsumeType} T + * @param {BodyReadable} stream + * @param {T} type + * @returns {Promise>} + */ +function consume (stream, type) { + assert(!stream[kConsume]) + + return new Promise((resolve, reject) => { + if (isUnusable(stream)) { + const rState = stream._readableState + if (rState.destroyed && rState.closeEmitted === false) { + stream + .on('error', reject) + .on('close', () => { + reject(new TypeError('unusable')) + }) + } else { + reject(rState.errored ?? new TypeError('unusable')) + } + } else { + queueMicrotask(() => { + stream[kConsume] = { + type, + stream, + resolve, + reject, + length: 0, + body: [] + } + + stream + .on('error', function (err) { + consumeFinish(this[kConsume], err) + }) + .on('close', function () { + if (this[kConsume].body !== null) { + consumeFinish(this[kConsume], new RequestAbortedError()) + } + }) + + consumeStart(stream[kConsume]) + }) + } + }) +} + +/** + * @param {Consume} consume + * @returns {void} + */ +function consumeStart (consume) { + if (consume.body === null) { + return + } + + const { _readableState: state } = consume.stream + + if (state.bufferIndex) { + const start = state.bufferIndex + const end = state.buffer.length + for (let n = start; n < end; n++) { + consumePush(consume, state.buffer[n]) + } + } else { + for (const chunk of state.buffer) { + consumePush(consume, chunk) + } + } + + if (state.endEmitted) { + consumeEnd(this[kConsume], this._readableState.encoding) + } else { + consume.stream.on('end', function () { + consumeEnd(this[kConsume], this._readableState.encoding) + }) + } + + consume.stream.resume() + + while (consume.stream.read() != null) { + // Loop + } +} + +/** + * @param {Buffer[]} chunks + * @param {number} length + * @param {BufferEncoding} [encoding='utf8'] + * @returns {string} + */ +function chunksDecode (chunks, length, encoding) { + if (chunks.length === 0 || length === 0) { + return '' + } + const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks, length) + const bufferLength = buffer.length + + // Skip BOM. + const start = + bufferLength > 2 && + buffer[0] === 0xef && + buffer[1] === 0xbb && + buffer[2] === 0xbf + ? 3 + : 0 + if (!encoding || encoding === 'utf8' || encoding === 'utf-8') { + return buffer.utf8Slice(start, bufferLength) + } else { + return buffer.subarray(start, bufferLength).toString(encoding) + } +} + +/** + * @param {Buffer[]} chunks + * @param {number} length + * @returns {Uint8Array} + */ +function chunksConcat (chunks, length) { + if (chunks.length === 0 || length === 0) { + return new Uint8Array(0) + } + if (chunks.length === 1) { + // fast-path + return new Uint8Array(chunks[0]) + } + const buffer = new Uint8Array(Buffer.allocUnsafeSlow(length).buffer) + + let offset = 0 + for (let i = 0; i < chunks.length; ++i) { + const chunk = chunks[i] + buffer.set(chunk, offset) + offset += chunk.length + } + + return buffer +} + +/** + * @param {Consume} consume + * @param {BufferEncoding} encoding + * @returns {void} + */ +function consumeEnd (consume, encoding) { + const { type, body, resolve, stream, length } = consume + + try { + if (type === 'text') { + resolve(chunksDecode(body, length, encoding)) + } else if (type === 'json') { + resolve(JSON.parse(chunksDecode(body, length, encoding))) + } else if (type === 'arrayBuffer') { + resolve(chunksConcat(body, length).buffer) + } else if (type === 'blob') { + resolve(new Blob(body, { type: stream[kContentType] })) + } else if (type === 'bytes') { + resolve(chunksConcat(body, length)) + } + + consumeFinish(consume) + } catch (err) { + stream.destroy(err) + } +} + +/** + * @param {Consume} consume + * @param {Buffer} chunk + * @returns {void} + */ +function consumePush (consume, chunk) { + consume.length += chunk.length + consume.body.push(chunk) +} + +/** + * @param {Consume} consume + * @param {Error} [err] + * @returns {void} + */ +function consumeFinish (consume, err) { + if (consume.body === null) { + return + } + + if (err) { + consume.reject(err) + } else { + consume.resolve() + } + + // Reset the consume object to allow for garbage collection. + consume.type = null + consume.stream = null + consume.resolve = null + consume.reject = null + consume.length = 0 + consume.body = null +} + +module.exports = { + Readable: BodyReadable, + chunksDecode +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/cache/memory-cache-store.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/cache/memory-cache-store.js new file mode 100644 index 0000000000000000000000000000000000000000..dba29ae4de9d82e59542daaab942f0b45b50db74 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/cache/memory-cache-store.js @@ -0,0 +1,234 @@ +'use strict' + +const { Writable } = require('node:stream') +const { EventEmitter } = require('node:events') +const { assertCacheKey, assertCacheValue } = require('../util/cache.js') + +/** + * @typedef {import('../../types/cache-interceptor.d.ts').default.CacheKey} CacheKey + * @typedef {import('../../types/cache-interceptor.d.ts').default.CacheValue} CacheValue + * @typedef {import('../../types/cache-interceptor.d.ts').default.CacheStore} CacheStore + * @typedef {import('../../types/cache-interceptor.d.ts').default.GetResult} GetResult + */ + +/** + * @implements {CacheStore} + * @extends {EventEmitter} + */ +class MemoryCacheStore extends EventEmitter { + #maxCount = 1024 + #maxSize = 104857600 // 100MB + #maxEntrySize = 5242880 // 5MB + + #size = 0 + #count = 0 + #entries = new Map() + #hasEmittedMaxSizeEvent = false + + /** + * @param {import('../../types/cache-interceptor.d.ts').default.MemoryCacheStoreOpts | undefined} [opts] + */ + constructor (opts) { + super() + if (opts) { + if (typeof opts !== 'object') { + throw new TypeError('MemoryCacheStore options must be an object') + } + + if (opts.maxCount !== undefined) { + if ( + typeof opts.maxCount !== 'number' || + !Number.isInteger(opts.maxCount) || + opts.maxCount < 0 + ) { + throw new TypeError('MemoryCacheStore options.maxCount must be a non-negative integer') + } + this.#maxCount = opts.maxCount + } + + if (opts.maxSize !== undefined) { + if ( + typeof opts.maxSize !== 'number' || + !Number.isInteger(opts.maxSize) || + opts.maxSize < 0 + ) { + throw new TypeError('MemoryCacheStore options.maxSize must be a non-negative integer') + } + this.#maxSize = opts.maxSize + } + + if (opts.maxEntrySize !== undefined) { + if ( + typeof opts.maxEntrySize !== 'number' || + !Number.isInteger(opts.maxEntrySize) || + opts.maxEntrySize < 0 + ) { + throw new TypeError('MemoryCacheStore options.maxEntrySize must be a non-negative integer') + } + this.#maxEntrySize = opts.maxEntrySize + } + } + } + + /** + * Get the current size of the cache in bytes + * @returns {number} The current size of the cache in bytes + */ + get size () { + return this.#size + } + + /** + * Check if the cache is full (either max size or max count reached) + * @returns {boolean} True if the cache is full, false otherwise + */ + isFull () { + return this.#size >= this.#maxSize || this.#count >= this.#maxCount + } + + /** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} req + * @returns {import('../../types/cache-interceptor.d.ts').default.GetResult | undefined} + */ + get (key) { + assertCacheKey(key) + + const topLevelKey = `${key.origin}:${key.path}` + + const now = Date.now() + const entries = this.#entries.get(topLevelKey) + + const entry = entries ? findEntry(key, entries, now) : null + + return entry == null + ? undefined + : { + statusMessage: entry.statusMessage, + statusCode: entry.statusCode, + headers: entry.headers, + body: entry.body, + vary: entry.vary ? entry.vary : undefined, + etag: entry.etag, + cacheControlDirectives: entry.cacheControlDirectives, + cachedAt: entry.cachedAt, + staleAt: entry.staleAt, + deleteAt: entry.deleteAt + } + } + + /** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key + * @param {import('../../types/cache-interceptor.d.ts').default.CacheValue} val + * @returns {Writable | undefined} + */ + createWriteStream (key, val) { + assertCacheKey(key) + assertCacheValue(val) + + const topLevelKey = `${key.origin}:${key.path}` + + const store = this + const entry = { ...key, ...val, body: [], size: 0 } + + return new Writable({ + write (chunk, encoding, callback) { + if (typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding) + } + + entry.size += chunk.byteLength + + if (entry.size >= store.#maxEntrySize) { + this.destroy() + } else { + entry.body.push(chunk) + } + + callback(null) + }, + final (callback) { + let entries = store.#entries.get(topLevelKey) + if (!entries) { + entries = [] + store.#entries.set(topLevelKey, entries) + } + const previousEntry = findEntry(key, entries, Date.now()) + if (previousEntry) { + const index = entries.indexOf(previousEntry) + entries.splice(index, 1, entry) + store.#size -= previousEntry.size + } else { + entries.push(entry) + store.#count += 1 + } + + store.#size += entry.size + + // Check if cache is full and emit event if needed + if (store.#size > store.#maxSize || store.#count > store.#maxCount) { + // Emit maxSizeExceeded event if we haven't already + if (!store.#hasEmittedMaxSizeEvent) { + store.emit('maxSizeExceeded', { + size: store.#size, + maxSize: store.#maxSize, + count: store.#count, + maxCount: store.#maxCount + }) + store.#hasEmittedMaxSizeEvent = true + } + + // Perform eviction + for (const [key, entries] of store.#entries) { + for (const entry of entries.splice(0, entries.length / 2)) { + store.#size -= entry.size + store.#count -= 1 + } + if (entries.length === 0) { + store.#entries.delete(key) + } + } + + // Reset the event flag after eviction + if (store.#size < store.#maxSize && store.#count < store.#maxCount) { + store.#hasEmittedMaxSizeEvent = false + } + } + + callback(null) + } + }) + } + + /** + * @param {CacheKey} key + */ + delete (key) { + if (typeof key !== 'object') { + throw new TypeError(`expected key to be object, got ${typeof key}`) + } + + const topLevelKey = `${key.origin}:${key.path}` + + for (const entry of this.#entries.get(topLevelKey) ?? []) { + this.#size -= entry.size + this.#count -= 1 + } + this.#entries.delete(topLevelKey) + } +} + +function findEntry (key, entries, now) { + return entries.find((entry) => ( + entry.deleteAt > now && + entry.method === key.method && + (entry.vary == null || Object.keys(entry.vary).every(headerName => { + if (entry.vary[headerName] === null) { + return key.headers[headerName] === undefined + } + + return entry.vary[headerName] === key.headers[headerName] + })) + )) +} + +module.exports = MemoryCacheStore diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/cache/sqlite-cache-store.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/cache/sqlite-cache-store.js new file mode 100644 index 0000000000000000000000000000000000000000..7cb4aa7e2466e3f2a1fef784bea45163f0f22fb9 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/cache/sqlite-cache-store.js @@ -0,0 +1,461 @@ +'use strict' + +const { Writable } = require('node:stream') +const { assertCacheKey, assertCacheValue } = require('../util/cache.js') + +let DatabaseSync + +const VERSION = 3 + +// 2gb +const MAX_ENTRY_SIZE = 2 * 1000 * 1000 * 1000 + +/** + * @typedef {import('../../types/cache-interceptor.d.ts').default.CacheStore} CacheStore + * @implements {CacheStore} + * + * @typedef {{ + * id: Readonly, + * body?: Uint8Array + * statusCode: number + * statusMessage: string + * headers?: string + * vary?: string + * etag?: string + * cacheControlDirectives?: string + * cachedAt: number + * staleAt: number + * deleteAt: number + * }} SqliteStoreValue + */ +module.exports = class SqliteCacheStore { + #maxEntrySize = MAX_ENTRY_SIZE + #maxCount = Infinity + + /** + * @type {import('node:sqlite').DatabaseSync} + */ + #db + + /** + * @type {import('node:sqlite').StatementSync} + */ + #getValuesQuery + + /** + * @type {import('node:sqlite').StatementSync} + */ + #updateValueQuery + + /** + * @type {import('node:sqlite').StatementSync} + */ + #insertValueQuery + + /** + * @type {import('node:sqlite').StatementSync} + */ + #deleteExpiredValuesQuery + + /** + * @type {import('node:sqlite').StatementSync} + */ + #deleteByUrlQuery + + /** + * @type {import('node:sqlite').StatementSync} + */ + #countEntriesQuery + + /** + * @type {import('node:sqlite').StatementSync | null} + */ + #deleteOldValuesQuery + + /** + * @param {import('../../types/cache-interceptor.d.ts').default.SqliteCacheStoreOpts | undefined} opts + */ + constructor (opts) { + if (opts) { + if (typeof opts !== 'object') { + throw new TypeError('SqliteCacheStore options must be an object') + } + + if (opts.maxEntrySize !== undefined) { + if ( + typeof opts.maxEntrySize !== 'number' || + !Number.isInteger(opts.maxEntrySize) || + opts.maxEntrySize < 0 + ) { + throw new TypeError('SqliteCacheStore options.maxEntrySize must be a non-negative integer') + } + + if (opts.maxEntrySize > MAX_ENTRY_SIZE) { + throw new TypeError('SqliteCacheStore options.maxEntrySize must be less than 2gb') + } + + this.#maxEntrySize = opts.maxEntrySize + } + + if (opts.maxCount !== undefined) { + if ( + typeof opts.maxCount !== 'number' || + !Number.isInteger(opts.maxCount) || + opts.maxCount < 0 + ) { + throw new TypeError('SqliteCacheStore options.maxCount must be a non-negative integer') + } + this.#maxCount = opts.maxCount + } + } + + if (!DatabaseSync) { + DatabaseSync = require('node:sqlite').DatabaseSync + } + this.#db = new DatabaseSync(opts?.location ?? ':memory:') + + this.#db.exec(` + PRAGMA journal_mode = WAL; + PRAGMA synchronous = NORMAL; + PRAGMA temp_store = memory; + PRAGMA optimize; + + CREATE TABLE IF NOT EXISTS cacheInterceptorV${VERSION} ( + -- Data specific to us + id INTEGER PRIMARY KEY AUTOINCREMENT, + url TEXT NOT NULL, + method TEXT NOT NULL, + + -- Data returned to the interceptor + body BUF NULL, + deleteAt INTEGER NOT NULL, + statusCode INTEGER NOT NULL, + statusMessage TEXT NOT NULL, + headers TEXT NULL, + cacheControlDirectives TEXT NULL, + etag TEXT NULL, + vary TEXT NULL, + cachedAt INTEGER NOT NULL, + staleAt INTEGER NOT NULL + ); + + CREATE INDEX IF NOT EXISTS idx_cacheInterceptorV${VERSION}_getValuesQuery ON cacheInterceptorV${VERSION}(url, method, deleteAt); + CREATE INDEX IF NOT EXISTS idx_cacheInterceptorV${VERSION}_deleteByUrlQuery ON cacheInterceptorV${VERSION}(deleteAt); + `) + + this.#getValuesQuery = this.#db.prepare(` + SELECT + id, + body, + deleteAt, + statusCode, + statusMessage, + headers, + etag, + cacheControlDirectives, + vary, + cachedAt, + staleAt + FROM cacheInterceptorV${VERSION} + WHERE + url = ? + AND method = ? + ORDER BY + deleteAt ASC + `) + + this.#updateValueQuery = this.#db.prepare(` + UPDATE cacheInterceptorV${VERSION} SET + body = ?, + deleteAt = ?, + statusCode = ?, + statusMessage = ?, + headers = ?, + etag = ?, + cacheControlDirectives = ?, + cachedAt = ?, + staleAt = ? + WHERE + id = ? + `) + + this.#insertValueQuery = this.#db.prepare(` + INSERT INTO cacheInterceptorV${VERSION} ( + url, + method, + body, + deleteAt, + statusCode, + statusMessage, + headers, + etag, + cacheControlDirectives, + vary, + cachedAt, + staleAt + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `) + + this.#deleteByUrlQuery = this.#db.prepare( + `DELETE FROM cacheInterceptorV${VERSION} WHERE url = ?` + ) + + this.#countEntriesQuery = this.#db.prepare( + `SELECT COUNT(*) AS total FROM cacheInterceptorV${VERSION}` + ) + + this.#deleteExpiredValuesQuery = this.#db.prepare( + `DELETE FROM cacheInterceptorV${VERSION} WHERE deleteAt <= ?` + ) + + this.#deleteOldValuesQuery = this.#maxCount === Infinity + ? null + : this.#db.prepare(` + DELETE FROM cacheInterceptorV${VERSION} + WHERE id IN ( + SELECT + id + FROM cacheInterceptorV${VERSION} + ORDER BY cachedAt DESC + LIMIT ? + ) + `) + } + + close () { + this.#db.close() + } + + /** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key + * @returns {(import('../../types/cache-interceptor.d.ts').default.GetResult & { body?: Buffer }) | undefined} + */ + get (key) { + assertCacheKey(key) + + const value = this.#findValue(key) + return value + ? { + body: value.body ? Buffer.from(value.body.buffer, value.body.byteOffset, value.body.byteLength) : undefined, + statusCode: value.statusCode, + statusMessage: value.statusMessage, + headers: value.headers ? JSON.parse(value.headers) : undefined, + etag: value.etag ? value.etag : undefined, + vary: value.vary ? JSON.parse(value.vary) : undefined, + cacheControlDirectives: value.cacheControlDirectives + ? JSON.parse(value.cacheControlDirectives) + : undefined, + cachedAt: value.cachedAt, + staleAt: value.staleAt, + deleteAt: value.deleteAt + } + : undefined + } + + /** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key + * @param {import('../../types/cache-interceptor.d.ts').default.CacheValue & { body: null | Buffer | Array}} value + */ + set (key, value) { + assertCacheKey(key) + + const url = this.#makeValueUrl(key) + const body = Array.isArray(value.body) ? Buffer.concat(value.body) : value.body + const size = body?.byteLength + + if (size && size > this.#maxEntrySize) { + return + } + + const existingValue = this.#findValue(key, true) + if (existingValue) { + // Updating an existing response, let's overwrite it + this.#updateValueQuery.run( + body, + value.deleteAt, + value.statusCode, + value.statusMessage, + value.headers ? JSON.stringify(value.headers) : null, + value.etag ? value.etag : null, + value.cacheControlDirectives ? JSON.stringify(value.cacheControlDirectives) : null, + value.cachedAt, + value.staleAt, + existingValue.id + ) + } else { + this.#prune() + // New response, let's insert it + this.#insertValueQuery.run( + url, + key.method, + body, + value.deleteAt, + value.statusCode, + value.statusMessage, + value.headers ? JSON.stringify(value.headers) : null, + value.etag ? value.etag : null, + value.cacheControlDirectives ? JSON.stringify(value.cacheControlDirectives) : null, + value.vary ? JSON.stringify(value.vary) : null, + value.cachedAt, + value.staleAt + ) + } + } + + /** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key + * @param {import('../../types/cache-interceptor.d.ts').default.CacheValue} value + * @returns {Writable | undefined} + */ + createWriteStream (key, value) { + assertCacheKey(key) + assertCacheValue(value) + + let size = 0 + /** + * @type {Buffer[] | null} + */ + const body = [] + const store = this + + return new Writable({ + decodeStrings: true, + write (chunk, encoding, callback) { + size += chunk.byteLength + + if (size < store.#maxEntrySize) { + body.push(chunk) + } else { + this.destroy() + } + + callback() + }, + final (callback) { + store.set(key, { ...value, body }) + callback() + } + }) + } + + /** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key + */ + delete (key) { + if (typeof key !== 'object') { + throw new TypeError(`expected key to be object, got ${typeof key}`) + } + + this.#deleteByUrlQuery.run(this.#makeValueUrl(key)) + } + + #prune () { + if (Number.isFinite(this.#maxCount) && this.size <= this.#maxCount) { + return 0 + } + + { + const removed = this.#deleteExpiredValuesQuery.run(Date.now()).changes + if (removed) { + return removed + } + } + + { + const removed = this.#deleteOldValuesQuery?.run(Math.max(Math.floor(this.#maxCount * 0.1), 1)).changes + if (removed) { + return removed + } + } + + return 0 + } + + /** + * Counts the number of rows in the cache + * @returns {Number} + */ + get size () { + const { total } = this.#countEntriesQuery.get() + return total + } + + /** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key + * @returns {string} + */ + #makeValueUrl (key) { + return `${key.origin}/${key.path}` + } + + /** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key + * @param {boolean} [canBeExpired=false] + * @returns {SqliteStoreValue | undefined} + */ + #findValue (key, canBeExpired = false) { + const url = this.#makeValueUrl(key) + const { headers, method } = key + + /** + * @type {SqliteStoreValue[]} + */ + const values = this.#getValuesQuery.all(url, method) + + if (values.length === 0) { + return undefined + } + + const now = Date.now() + for (const value of values) { + if (now >= value.deleteAt && !canBeExpired) { + return undefined + } + + let matches = true + + if (value.vary) { + const vary = JSON.parse(value.vary) + + for (const header in vary) { + if (!headerValueEquals(headers[header], vary[header])) { + matches = false + break + } + } + } + + if (matches) { + return value + } + } + + return undefined + } +} + +/** + * @param {string|string[]|null|undefined} lhs + * @param {string|string[]|null|undefined} rhs + * @returns {boolean} + */ +function headerValueEquals (lhs, rhs) { + if (lhs == null && rhs == null) { + return true + } + + if ((lhs == null && rhs != null) || + (lhs != null && rhs == null)) { + return false + } + + if (Array.isArray(lhs) && Array.isArray(rhs)) { + if (lhs.length !== rhs.length) { + return false + } + + return lhs.every((x, i) => x === rhs[i]) + } + + return lhs === rhs +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/core/connect.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/core/connect.js new file mode 100644 index 0000000000000000000000000000000000000000..4e11deee37feae3701a801e7e6fdf64313077f92 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/core/connect.js @@ -0,0 +1,134 @@ +'use strict' + +const net = require('node:net') +const assert = require('node:assert') +const util = require('./util') +const { InvalidArgumentError } = require('./errors') + +let tls // include tls conditionally since it is not always available + +// TODO: session re-use does not wait for the first +// connection to resolve the session and might therefore +// resolve the same servername multiple times even when +// re-use is enabled. + +const SessionCache = class WeakSessionCache { + constructor (maxCachedSessions) { + this._maxCachedSessions = maxCachedSessions + this._sessionCache = new Map() + this._sessionRegistry = new FinalizationRegistry((key) => { + if (this._sessionCache.size < this._maxCachedSessions) { + return + } + + const ref = this._sessionCache.get(key) + if (ref !== undefined && ref.deref() === undefined) { + this._sessionCache.delete(key) + } + }) + } + + get (sessionKey) { + const ref = this._sessionCache.get(sessionKey) + return ref ? ref.deref() : null + } + + set (sessionKey, session) { + if (this._maxCachedSessions === 0) { + return + } + + this._sessionCache.set(sessionKey, new WeakRef(session)) + this._sessionRegistry.register(session, sessionKey) + } +} + +function buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, session: customSession, ...opts }) { + if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) { + throw new InvalidArgumentError('maxCachedSessions must be a positive integer or zero') + } + + const options = { path: socketPath, ...opts } + const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions) + timeout = timeout == null ? 10e3 : timeout + allowH2 = allowH2 != null ? allowH2 : false + return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) { + let socket + if (protocol === 'https:') { + if (!tls) { + tls = require('node:tls') + } + servername = servername || options.servername || util.getServerName(host) || null + + const sessionKey = servername || hostname + assert(sessionKey) + + const session = customSession || sessionCache.get(sessionKey) || null + + port = port || 443 + + socket = tls.connect({ + highWaterMark: 16384, // TLS in node can't have bigger HWM anyway... + ...options, + servername, + session, + localAddress, + ALPNProtocols: allowH2 ? ['http/1.1', 'h2'] : ['http/1.1'], + socket: httpSocket, // upgrade socket connection + port, + host: hostname + }) + + socket + .on('session', function (session) { + // TODO (fix): Can a session become invalid once established? Don't think so? + sessionCache.set(sessionKey, session) + }) + } else { + assert(!httpSocket, 'httpSocket can only be sent on TLS update') + + port = port || 80 + + socket = net.connect({ + highWaterMark: 64 * 1024, // Same as nodejs fs streams. + ...options, + localAddress, + port, + host: hostname + }) + } + + // Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket + if (options.keepAlive == null || options.keepAlive) { + const keepAliveInitialDelay = options.keepAliveInitialDelay === undefined ? 60e3 : options.keepAliveInitialDelay + socket.setKeepAlive(true, keepAliveInitialDelay) + } + + const clearConnectTimeout = util.setupConnectTimeout(new WeakRef(socket), { timeout, hostname, port }) + + socket + .setNoDelay(true) + .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () { + queueMicrotask(clearConnectTimeout) + + if (callback) { + const cb = callback + callback = null + cb(null, this) + } + }) + .on('error', function (err) { + queueMicrotask(clearConnectTimeout) + + if (callback) { + const cb = callback + callback = null + cb(err) + } + }) + + return socket + } +} + +module.exports = buildConnector diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/core/constants.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/core/constants.js new file mode 100644 index 0000000000000000000000000000000000000000..088cf47d80f1d71eb7fe041742428601ce9fac4d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/core/constants.js @@ -0,0 +1,143 @@ +'use strict' + +/** + * @see https://developer.mozilla.org/docs/Web/HTTP/Headers + */ +const wellknownHeaderNames = /** @type {const} */ ([ + 'Accept', + 'Accept-Encoding', + 'Accept-Language', + 'Accept-Ranges', + 'Access-Control-Allow-Credentials', + 'Access-Control-Allow-Headers', + 'Access-Control-Allow-Methods', + 'Access-Control-Allow-Origin', + 'Access-Control-Expose-Headers', + 'Access-Control-Max-Age', + 'Access-Control-Request-Headers', + 'Access-Control-Request-Method', + 'Age', + 'Allow', + 'Alt-Svc', + 'Alt-Used', + 'Authorization', + 'Cache-Control', + 'Clear-Site-Data', + 'Connection', + 'Content-Disposition', + 'Content-Encoding', + 'Content-Language', + 'Content-Length', + 'Content-Location', + 'Content-Range', + 'Content-Security-Policy', + 'Content-Security-Policy-Report-Only', + 'Content-Type', + 'Cookie', + 'Cross-Origin-Embedder-Policy', + 'Cross-Origin-Opener-Policy', + 'Cross-Origin-Resource-Policy', + 'Date', + 'Device-Memory', + 'Downlink', + 'ECT', + 'ETag', + 'Expect', + 'Expect-CT', + 'Expires', + 'Forwarded', + 'From', + 'Host', + 'If-Match', + 'If-Modified-Since', + 'If-None-Match', + 'If-Range', + 'If-Unmodified-Since', + 'Keep-Alive', + 'Last-Modified', + 'Link', + 'Location', + 'Max-Forwards', + 'Origin', + 'Permissions-Policy', + 'Pragma', + 'Proxy-Authenticate', + 'Proxy-Authorization', + 'RTT', + 'Range', + 'Referer', + 'Referrer-Policy', + 'Refresh', + 'Retry-After', + 'Sec-WebSocket-Accept', + 'Sec-WebSocket-Extensions', + 'Sec-WebSocket-Key', + 'Sec-WebSocket-Protocol', + 'Sec-WebSocket-Version', + 'Server', + 'Server-Timing', + 'Service-Worker-Allowed', + 'Service-Worker-Navigation-Preload', + 'Set-Cookie', + 'SourceMap', + 'Strict-Transport-Security', + 'Supports-Loading-Mode', + 'TE', + 'Timing-Allow-Origin', + 'Trailer', + 'Transfer-Encoding', + 'Upgrade', + 'Upgrade-Insecure-Requests', + 'User-Agent', + 'Vary', + 'Via', + 'WWW-Authenticate', + 'X-Content-Type-Options', + 'X-DNS-Prefetch-Control', + 'X-Frame-Options', + 'X-Permitted-Cross-Domain-Policies', + 'X-Powered-By', + 'X-Requested-With', + 'X-XSS-Protection' +]) + +/** @type {Record, string>} */ +const headerNameLowerCasedRecord = {} + +// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. +Object.setPrototypeOf(headerNameLowerCasedRecord, null) + +/** + * @type {Record, Buffer>} + */ +const wellknownHeaderNameBuffers = {} + +// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. +Object.setPrototypeOf(wellknownHeaderNameBuffers, null) + +/** + * @param {string} header Lowercased header + * @returns {Buffer} + */ +function getHeaderNameAsBuffer (header) { + let buffer = wellknownHeaderNameBuffers[header] + + if (buffer === undefined) { + buffer = Buffer.from(header) + } + + return buffer +} + +for (let i = 0; i < wellknownHeaderNames.length; ++i) { + const key = wellknownHeaderNames[i] + const lowerCasedKey = key.toLowerCase() + headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] = + lowerCasedKey +} + +module.exports = { + wellknownHeaderNames, + headerNameLowerCasedRecord, + getHeaderNameAsBuffer +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/core/diagnostics.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/core/diagnostics.js new file mode 100644 index 0000000000000000000000000000000000000000..224a5c49f5da2c108451279088876a87b098fced --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/core/diagnostics.js @@ -0,0 +1,198 @@ +'use strict' + +const diagnosticsChannel = require('node:diagnostics_channel') +const util = require('node:util') + +const undiciDebugLog = util.debuglog('undici') +const fetchDebuglog = util.debuglog('fetch') +const websocketDebuglog = util.debuglog('websocket') + +const channels = { + // Client + beforeConnect: diagnosticsChannel.channel('undici:client:beforeConnect'), + connected: diagnosticsChannel.channel('undici:client:connected'), + connectError: diagnosticsChannel.channel('undici:client:connectError'), + sendHeaders: diagnosticsChannel.channel('undici:client:sendHeaders'), + // Request + create: diagnosticsChannel.channel('undici:request:create'), + bodySent: diagnosticsChannel.channel('undici:request:bodySent'), + bodyChunkSent: diagnosticsChannel.channel('undici:request:bodyChunkSent'), + bodyChunkReceived: diagnosticsChannel.channel('undici:request:bodyChunkReceived'), + headers: diagnosticsChannel.channel('undici:request:headers'), + trailers: diagnosticsChannel.channel('undici:request:trailers'), + error: diagnosticsChannel.channel('undici:request:error'), + // WebSocket + open: diagnosticsChannel.channel('undici:websocket:open'), + close: diagnosticsChannel.channel('undici:websocket:close'), + socketError: diagnosticsChannel.channel('undici:websocket:socket_error'), + ping: diagnosticsChannel.channel('undici:websocket:ping'), + pong: diagnosticsChannel.channel('undici:websocket:pong') +} + +let isTrackingClientEvents = false + +function trackClientEvents (debugLog = undiciDebugLog) { + if (isTrackingClientEvents) { + return + } + + isTrackingClientEvents = true + + diagnosticsChannel.subscribe('undici:client:beforeConnect', + evt => { + const { + connectParams: { version, protocol, port, host } + } = evt + debugLog( + 'connecting to %s%s using %s%s', + host, + port ? `:${port}` : '', + protocol, + version + ) + }) + + diagnosticsChannel.subscribe('undici:client:connected', + evt => { + const { + connectParams: { version, protocol, port, host } + } = evt + debugLog( + 'connected to %s%s using %s%s', + host, + port ? `:${port}` : '', + protocol, + version + ) + }) + + diagnosticsChannel.subscribe('undici:client:connectError', + evt => { + const { + connectParams: { version, protocol, port, host }, + error + } = evt + debugLog( + 'connection to %s%s using %s%s errored - %s', + host, + port ? `:${port}` : '', + protocol, + version, + error.message + ) + }) + + diagnosticsChannel.subscribe('undici:client:sendHeaders', + evt => { + const { + request: { method, path, origin } + } = evt + debugLog('sending request to %s %s%s', method, origin, path) + }) +} + +let isTrackingRequestEvents = false + +function trackRequestEvents (debugLog = undiciDebugLog) { + if (isTrackingRequestEvents) { + return + } + + isTrackingRequestEvents = true + + diagnosticsChannel.subscribe('undici:request:headers', + evt => { + const { + request: { method, path, origin }, + response: { statusCode } + } = evt + debugLog( + 'received response to %s %s%s - HTTP %d', + method, + origin, + path, + statusCode + ) + }) + + diagnosticsChannel.subscribe('undici:request:trailers', + evt => { + const { + request: { method, path, origin } + } = evt + debugLog('trailers received from %s %s%s', method, origin, path) + }) + + diagnosticsChannel.subscribe('undici:request:error', + evt => { + const { + request: { method, path, origin }, + error + } = evt + debugLog( + 'request to %s %s%s errored - %s', + method, + origin, + path, + error.message + ) + }) +} + +let isTrackingWebSocketEvents = false + +function trackWebSocketEvents (debugLog = websocketDebuglog) { + if (isTrackingWebSocketEvents) { + return + } + + isTrackingWebSocketEvents = true + + diagnosticsChannel.subscribe('undici:websocket:open', + evt => { + const { + address: { address, port } + } = evt + debugLog('connection opened %s%s', address, port ? `:${port}` : '') + }) + + diagnosticsChannel.subscribe('undici:websocket:close', + evt => { + const { websocket, code, reason } = evt + debugLog( + 'closed connection to %s - %s %s', + websocket.url, + code, + reason + ) + }) + + diagnosticsChannel.subscribe('undici:websocket:socket_error', + err => { + debugLog('connection errored - %s', err.message) + }) + + diagnosticsChannel.subscribe('undici:websocket:ping', + evt => { + debugLog('ping received') + }) + + diagnosticsChannel.subscribe('undici:websocket:pong', + evt => { + debugLog('pong received') + }) +} + +if (undiciDebugLog.enabled || fetchDebuglog.enabled) { + trackClientEvents(fetchDebuglog.enabled ? fetchDebuglog : undiciDebugLog) + trackRequestEvents(fetchDebuglog.enabled ? fetchDebuglog : undiciDebugLog) +} + +if (websocketDebuglog.enabled) { + trackClientEvents(undiciDebugLog.enabled ? undiciDebugLog : websocketDebuglog) + trackWebSocketEvents(websocketDebuglog) +} + +module.exports = { + channels +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/core/errors.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/core/errors.js new file mode 100644 index 0000000000000000000000000000000000000000..b2b3f326bc4a3663f35131222912d4a50078ab41 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/core/errors.js @@ -0,0 +1,244 @@ +'use strict' + +class UndiciError extends Error { + constructor (message, options) { + super(message, options) + this.name = 'UndiciError' + this.code = 'UND_ERR' + } +} + +class ConnectTimeoutError extends UndiciError { + constructor (message) { + super(message) + this.name = 'ConnectTimeoutError' + this.message = message || 'Connect Timeout Error' + this.code = 'UND_ERR_CONNECT_TIMEOUT' + } +} + +class HeadersTimeoutError extends UndiciError { + constructor (message) { + super(message) + this.name = 'HeadersTimeoutError' + this.message = message || 'Headers Timeout Error' + this.code = 'UND_ERR_HEADERS_TIMEOUT' + } +} + +class HeadersOverflowError extends UndiciError { + constructor (message) { + super(message) + this.name = 'HeadersOverflowError' + this.message = message || 'Headers Overflow Error' + this.code = 'UND_ERR_HEADERS_OVERFLOW' + } +} + +class BodyTimeoutError extends UndiciError { + constructor (message) { + super(message) + this.name = 'BodyTimeoutError' + this.message = message || 'Body Timeout Error' + this.code = 'UND_ERR_BODY_TIMEOUT' + } +} + +class ResponseStatusCodeError extends UndiciError { + constructor (message, statusCode, headers, body) { + super(message) + this.name = 'ResponseStatusCodeError' + this.message = message || 'Response Status Code Error' + this.code = 'UND_ERR_RESPONSE_STATUS_CODE' + this.body = body + this.status = statusCode + this.statusCode = statusCode + this.headers = headers + } +} + +class InvalidArgumentError extends UndiciError { + constructor (message) { + super(message) + this.name = 'InvalidArgumentError' + this.message = message || 'Invalid Argument Error' + this.code = 'UND_ERR_INVALID_ARG' + } +} + +class InvalidReturnValueError extends UndiciError { + constructor (message) { + super(message) + this.name = 'InvalidReturnValueError' + this.message = message || 'Invalid Return Value Error' + this.code = 'UND_ERR_INVALID_RETURN_VALUE' + } +} + +class AbortError extends UndiciError { + constructor (message) { + super(message) + this.name = 'AbortError' + this.message = message || 'The operation was aborted' + } +} + +class RequestAbortedError extends AbortError { + constructor (message) { + super(message) + this.name = 'AbortError' + this.message = message || 'Request aborted' + this.code = 'UND_ERR_ABORTED' + } +} + +class InformationalError extends UndiciError { + constructor (message) { + super(message) + this.name = 'InformationalError' + this.message = message || 'Request information' + this.code = 'UND_ERR_INFO' + } +} + +class RequestContentLengthMismatchError extends UndiciError { + constructor (message) { + super(message) + this.name = 'RequestContentLengthMismatchError' + this.message = message || 'Request body length does not match content-length header' + this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH' + } +} + +class ResponseContentLengthMismatchError extends UndiciError { + constructor (message) { + super(message) + this.name = 'ResponseContentLengthMismatchError' + this.message = message || 'Response body length does not match content-length header' + this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH' + } +} + +class ClientDestroyedError extends UndiciError { + constructor (message) { + super(message) + this.name = 'ClientDestroyedError' + this.message = message || 'The client is destroyed' + this.code = 'UND_ERR_DESTROYED' + } +} + +class ClientClosedError extends UndiciError { + constructor (message) { + super(message) + this.name = 'ClientClosedError' + this.message = message || 'The client is closed' + this.code = 'UND_ERR_CLOSED' + } +} + +class SocketError extends UndiciError { + constructor (message, socket) { + super(message) + this.name = 'SocketError' + this.message = message || 'Socket error' + this.code = 'UND_ERR_SOCKET' + this.socket = socket + } +} + +class NotSupportedError extends UndiciError { + constructor (message) { + super(message) + this.name = 'NotSupportedError' + this.message = message || 'Not supported error' + this.code = 'UND_ERR_NOT_SUPPORTED' + } +} + +class BalancedPoolMissingUpstreamError extends UndiciError { + constructor (message) { + super(message) + this.name = 'MissingUpstreamError' + this.message = message || 'No upstream has been added to the BalancedPool' + this.code = 'UND_ERR_BPL_MISSING_UPSTREAM' + } +} + +class HTTPParserError extends Error { + constructor (message, code, data) { + super(message) + this.name = 'HTTPParserError' + this.code = code ? `HPE_${code}` : undefined + this.data = data ? data.toString() : undefined + } +} + +class ResponseExceededMaxSizeError extends UndiciError { + constructor (message) { + super(message) + this.name = 'ResponseExceededMaxSizeError' + this.message = message || 'Response content exceeded max size' + this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE' + } +} + +class RequestRetryError extends UndiciError { + constructor (message, code, { headers, data }) { + super(message) + this.name = 'RequestRetryError' + this.message = message || 'Request retry error' + this.code = 'UND_ERR_REQ_RETRY' + this.statusCode = code + this.data = data + this.headers = headers + } +} + +class ResponseError extends UndiciError { + constructor (message, code, { headers, body }) { + super(message) + this.name = 'ResponseError' + this.message = message || 'Response error' + this.code = 'UND_ERR_RESPONSE' + this.statusCode = code + this.body = body + this.headers = headers + } +} + +class SecureProxyConnectionError extends UndiciError { + constructor (cause, message, options = {}) { + super(message, { cause, ...options }) + this.name = 'SecureProxyConnectionError' + this.message = message || 'Secure Proxy Connection failed' + this.code = 'UND_ERR_PRX_TLS' + this.cause = cause + } +} + +module.exports = { + AbortError, + HTTPParserError, + UndiciError, + HeadersTimeoutError, + HeadersOverflowError, + BodyTimeoutError, + RequestContentLengthMismatchError, + ConnectTimeoutError, + ResponseStatusCodeError, + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError, + ClientDestroyedError, + ClientClosedError, + InformationalError, + SocketError, + NotSupportedError, + ResponseContentLengthMismatchError, + BalancedPoolMissingUpstreamError, + ResponseExceededMaxSizeError, + RequestRetryError, + ResponseError, + SecureProxyConnectionError +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/core/request.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/core/request.js new file mode 100644 index 0000000000000000000000000000000000000000..d970fafd8d315c139fd813645830c86987ac9eff --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/core/request.js @@ -0,0 +1,408 @@ +'use strict' + +const { + InvalidArgumentError, + NotSupportedError +} = require('./errors') +const assert = require('node:assert') +const { + isValidHTTPToken, + isValidHeaderValue, + isStream, + destroy, + isBuffer, + isFormDataLike, + isIterable, + isBlobLike, + serializePathWithQuery, + assertRequestHandler, + getServerName, + normalizedMethodRecords +} = require('./util') +const { channels } = require('./diagnostics.js') +const { headerNameLowerCasedRecord } = require('./constants') + +// Verifies that a given path is valid does not contain control chars \x00 to \x20 +const invalidPathRegex = /[^\u0021-\u00ff]/ + +const kHandler = Symbol('handler') + +class Request { + constructor (origin, { + path, + method, + body, + headers, + query, + idempotent, + blocking, + upgrade, + headersTimeout, + bodyTimeout, + reset, + expectContinue, + servername, + throwOnError, + maxRedirections + }, handler) { + if (typeof path !== 'string') { + throw new InvalidArgumentError('path must be a string') + } else if ( + path[0] !== '/' && + !(path.startsWith('http://') || path.startsWith('https://')) && + method !== 'CONNECT' + ) { + throw new InvalidArgumentError('path must be an absolute URL or start with a slash') + } else if (invalidPathRegex.test(path)) { + throw new InvalidArgumentError('invalid request path') + } + + if (typeof method !== 'string') { + throw new InvalidArgumentError('method must be a string') + } else if (normalizedMethodRecords[method] === undefined && !isValidHTTPToken(method)) { + throw new InvalidArgumentError('invalid request method') + } + + if (upgrade && typeof upgrade !== 'string') { + throw new InvalidArgumentError('upgrade must be a string') + } + + if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) { + throw new InvalidArgumentError('invalid headersTimeout') + } + + if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) { + throw new InvalidArgumentError('invalid bodyTimeout') + } + + if (reset != null && typeof reset !== 'boolean') { + throw new InvalidArgumentError('invalid reset') + } + + if (expectContinue != null && typeof expectContinue !== 'boolean') { + throw new InvalidArgumentError('invalid expectContinue') + } + + if (throwOnError != null) { + throw new InvalidArgumentError('invalid throwOnError') + } + + if (maxRedirections != null && maxRedirections !== 0) { + throw new InvalidArgumentError('maxRedirections is not supported, use the redirect interceptor') + } + + this.headersTimeout = headersTimeout + + this.bodyTimeout = bodyTimeout + + this.method = method + + this.abort = null + + if (body == null) { + this.body = null + } else if (isStream(body)) { + this.body = body + + const rState = this.body._readableState + if (!rState || !rState.autoDestroy) { + this.endHandler = function autoDestroy () { + destroy(this) + } + this.body.on('end', this.endHandler) + } + + this.errorHandler = err => { + if (this.abort) { + this.abort(err) + } else { + this.error = err + } + } + this.body.on('error', this.errorHandler) + } else if (isBuffer(body)) { + this.body = body.byteLength ? body : null + } else if (ArrayBuffer.isView(body)) { + this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null + } else if (body instanceof ArrayBuffer) { + this.body = body.byteLength ? Buffer.from(body) : null + } else if (typeof body === 'string') { + this.body = body.length ? Buffer.from(body) : null + } else if (isFormDataLike(body) || isIterable(body) || isBlobLike(body)) { + this.body = body + } else { + throw new InvalidArgumentError('body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable') + } + + this.completed = false + this.aborted = false + + this.upgrade = upgrade || null + + this.path = query ? serializePathWithQuery(path, query) : path + + this.origin = origin + + this.idempotent = idempotent == null + ? method === 'HEAD' || method === 'GET' + : idempotent + + this.blocking = blocking ?? this.method !== 'HEAD' + + this.reset = reset == null ? null : reset + + this.host = null + + this.contentLength = null + + this.contentType = null + + this.headers = [] + + // Only for H2 + this.expectContinue = expectContinue != null ? expectContinue : false + + if (Array.isArray(headers)) { + if (headers.length % 2 !== 0) { + throw new InvalidArgumentError('headers array must be even') + } + for (let i = 0; i < headers.length; i += 2) { + processHeader(this, headers[i], headers[i + 1]) + } + } else if (headers && typeof headers === 'object') { + if (headers[Symbol.iterator]) { + for (const header of headers) { + if (!Array.isArray(header) || header.length !== 2) { + throw new InvalidArgumentError('headers must be in key-value pair format') + } + processHeader(this, header[0], header[1]) + } + } else { + const keys = Object.keys(headers) + for (let i = 0; i < keys.length; ++i) { + processHeader(this, keys[i], headers[keys[i]]) + } + } + } else if (headers != null) { + throw new InvalidArgumentError('headers must be an object or an array') + } + + assertRequestHandler(handler, method, upgrade) + + this.servername = servername || getServerName(this.host) || null + + this[kHandler] = handler + + if (channels.create.hasSubscribers) { + channels.create.publish({ request: this }) + } + } + + onBodySent (chunk) { + if (channels.bodyChunkSent.hasSubscribers) { + channels.bodyChunkSent.publish({ request: this, chunk }) + } + if (this[kHandler].onBodySent) { + try { + return this[kHandler].onBodySent(chunk) + } catch (err) { + this.abort(err) + } + } + } + + onRequestSent () { + if (channels.bodySent.hasSubscribers) { + channels.bodySent.publish({ request: this }) + } + + if (this[kHandler].onRequestSent) { + try { + return this[kHandler].onRequestSent() + } catch (err) { + this.abort(err) + } + } + } + + onConnect (abort) { + assert(!this.aborted) + assert(!this.completed) + + if (this.error) { + abort(this.error) + } else { + this.abort = abort + return this[kHandler].onConnect(abort) + } + } + + onResponseStarted () { + return this[kHandler].onResponseStarted?.() + } + + onHeaders (statusCode, headers, resume, statusText) { + assert(!this.aborted) + assert(!this.completed) + + if (channels.headers.hasSubscribers) { + channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }) + } + + try { + return this[kHandler].onHeaders(statusCode, headers, resume, statusText) + } catch (err) { + this.abort(err) + } + } + + onData (chunk) { + assert(!this.aborted) + assert(!this.completed) + + if (channels.bodyChunkReceived.hasSubscribers) { + channels.bodyChunkReceived.publish({ request: this, chunk }) + } + try { + return this[kHandler].onData(chunk) + } catch (err) { + this.abort(err) + return false + } + } + + onUpgrade (statusCode, headers, socket) { + assert(!this.aborted) + assert(!this.completed) + + return this[kHandler].onUpgrade(statusCode, headers, socket) + } + + onComplete (trailers) { + this.onFinally() + + assert(!this.aborted) + assert(!this.completed) + + this.completed = true + if (channels.trailers.hasSubscribers) { + channels.trailers.publish({ request: this, trailers }) + } + + try { + return this[kHandler].onComplete(trailers) + } catch (err) { + // TODO (fix): This might be a bad idea? + this.onError(err) + } + } + + onError (error) { + this.onFinally() + + if (channels.error.hasSubscribers) { + channels.error.publish({ request: this, error }) + } + + if (this.aborted) { + return + } + this.aborted = true + + return this[kHandler].onError(error) + } + + onFinally () { + if (this.errorHandler) { + this.body.off('error', this.errorHandler) + this.errorHandler = null + } + + if (this.endHandler) { + this.body.off('end', this.endHandler) + this.endHandler = null + } + } + + addHeader (key, value) { + processHeader(this, key, value) + return this + } +} + +function processHeader (request, key, val) { + if (val && (typeof val === 'object' && !Array.isArray(val))) { + throw new InvalidArgumentError(`invalid ${key} header`) + } else if (val === undefined) { + return + } + + let headerName = headerNameLowerCasedRecord[key] + + if (headerName === undefined) { + headerName = key.toLowerCase() + if (headerNameLowerCasedRecord[headerName] === undefined && !isValidHTTPToken(headerName)) { + throw new InvalidArgumentError('invalid header key') + } + } + + if (Array.isArray(val)) { + const arr = [] + for (let i = 0; i < val.length; i++) { + if (typeof val[i] === 'string') { + if (!isValidHeaderValue(val[i])) { + throw new InvalidArgumentError(`invalid ${key} header`) + } + arr.push(val[i]) + } else if (val[i] === null) { + arr.push('') + } else if (typeof val[i] === 'object') { + throw new InvalidArgumentError(`invalid ${key} header`) + } else { + arr.push(`${val[i]}`) + } + } + val = arr + } else if (typeof val === 'string') { + if (!isValidHeaderValue(val)) { + throw new InvalidArgumentError(`invalid ${key} header`) + } + } else if (val === null) { + val = '' + } else { + val = `${val}` + } + + if (request.host === null && headerName === 'host') { + if (typeof val !== 'string') { + throw new InvalidArgumentError('invalid host header') + } + // Consumed by Client + request.host = val + } else if (request.contentLength === null && headerName === 'content-length') { + request.contentLength = parseInt(val, 10) + if (!Number.isFinite(request.contentLength)) { + throw new InvalidArgumentError('invalid content-length header') + } + } else if (request.contentType === null && headerName === 'content-type') { + request.contentType = val + request.headers.push(key, val) + } else if (headerName === 'transfer-encoding' || headerName === 'keep-alive' || headerName === 'upgrade') { + throw new InvalidArgumentError(`invalid ${headerName} header`) + } else if (headerName === 'connection') { + const value = typeof val === 'string' ? val.toLowerCase() : null + if (value !== 'close' && value !== 'keep-alive') { + throw new InvalidArgumentError('invalid connection header') + } + + if (value === 'close') { + request.reset = true + } + } else if (headerName === 'expect') { + throw new NotSupportedError('expect header not supported') + } else { + request.headers.push(key, val) + } +} + +module.exports = Request diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/core/symbols.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/core/symbols.js new file mode 100644 index 0000000000000000000000000000000000000000..f3b563a5419b97bc9561f5af732babc8dfb9e22c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/core/symbols.js @@ -0,0 +1,68 @@ +'use strict' + +module.exports = { + kClose: Symbol('close'), + kDestroy: Symbol('destroy'), + kDispatch: Symbol('dispatch'), + kUrl: Symbol('url'), + kWriting: Symbol('writing'), + kResuming: Symbol('resuming'), + kQueue: Symbol('queue'), + kConnect: Symbol('connect'), + kConnecting: Symbol('connecting'), + kKeepAliveDefaultTimeout: Symbol('default keep alive timeout'), + kKeepAliveMaxTimeout: Symbol('max keep alive timeout'), + kKeepAliveTimeoutThreshold: Symbol('keep alive timeout threshold'), + kKeepAliveTimeoutValue: Symbol('keep alive timeout'), + kKeepAlive: Symbol('keep alive'), + kHeadersTimeout: Symbol('headers timeout'), + kBodyTimeout: Symbol('body timeout'), + kServerName: Symbol('server name'), + kLocalAddress: Symbol('local address'), + kHost: Symbol('host'), + kNoRef: Symbol('no ref'), + kBodyUsed: Symbol('used'), + kBody: Symbol('abstracted request body'), + kRunning: Symbol('running'), + kBlocking: Symbol('blocking'), + kPending: Symbol('pending'), + kSize: Symbol('size'), + kBusy: Symbol('busy'), + kQueued: Symbol('queued'), + kFree: Symbol('free'), + kConnected: Symbol('connected'), + kClosed: Symbol('closed'), + kNeedDrain: Symbol('need drain'), + kReset: Symbol('reset'), + kDestroyed: Symbol.for('nodejs.stream.destroyed'), + kResume: Symbol('resume'), + kOnError: Symbol('on error'), + kMaxHeadersSize: Symbol('max headers size'), + kRunningIdx: Symbol('running index'), + kPendingIdx: Symbol('pending index'), + kError: Symbol('error'), + kClients: Symbol('clients'), + kClient: Symbol('client'), + kParser: Symbol('parser'), + kOnDestroyed: Symbol('destroy callbacks'), + kPipelining: Symbol('pipelining'), + kSocket: Symbol('socket'), + kHostHeader: Symbol('host header'), + kConnector: Symbol('connector'), + kStrictContentLength: Symbol('strict content length'), + kMaxRedirections: Symbol('maxRedirections'), + kMaxRequests: Symbol('maxRequestsPerClient'), + kProxy: Symbol('proxy agent options'), + kCounter: Symbol('socket request counter'), + kMaxResponseSize: Symbol('max response size'), + kHTTP2Session: Symbol('http2Session'), + kHTTP2SessionState: Symbol('http2Session state'), + kRetryHandlerDefaultRetry: Symbol('retry agent default retry'), + kConstruct: Symbol('constructable'), + kListeners: Symbol('listeners'), + kHTTPContext: Symbol('http context'), + kMaxConcurrentStreams: Symbol('max concurrent streams'), + kNoProxyAgent: Symbol('no proxy agent'), + kHttpProxyAgent: Symbol('http proxy agent'), + kHttpsProxyAgent: Symbol('https proxy agent') +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/core/tree.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/core/tree.js new file mode 100644 index 0000000000000000000000000000000000000000..6eed58aad694e33f1bac8942e73110ec90fcebec --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/core/tree.js @@ -0,0 +1,160 @@ +'use strict' + +const { + wellknownHeaderNames, + headerNameLowerCasedRecord +} = require('./constants') + +class TstNode { + /** @type {any} */ + value = null + /** @type {null | TstNode} */ + left = null + /** @type {null | TstNode} */ + middle = null + /** @type {null | TstNode} */ + right = null + /** @type {number} */ + code + /** + * @param {string} key + * @param {any} value + * @param {number} index + */ + constructor (key, value, index) { + if (index === undefined || index >= key.length) { + throw new TypeError('Unreachable') + } + const code = this.code = key.charCodeAt(index) + // check code is ascii string + if (code > 0x7F) { + throw new TypeError('key must be ascii string') + } + if (key.length !== ++index) { + this.middle = new TstNode(key, value, index) + } else { + this.value = value + } + } + + /** + * @param {string} key + * @param {any} value + * @returns {void} + */ + add (key, value) { + const length = key.length + if (length === 0) { + throw new TypeError('Unreachable') + } + let index = 0 + /** + * @type {TstNode} + */ + let node = this + while (true) { + const code = key.charCodeAt(index) + // check code is ascii string + if (code > 0x7F) { + throw new TypeError('key must be ascii string') + } + if (node.code === code) { + if (length === ++index) { + node.value = value + break + } else if (node.middle !== null) { + node = node.middle + } else { + node.middle = new TstNode(key, value, index) + break + } + } else if (node.code < code) { + if (node.left !== null) { + node = node.left + } else { + node.left = new TstNode(key, value, index) + break + } + } else if (node.right !== null) { + node = node.right + } else { + node.right = new TstNode(key, value, index) + break + } + } + } + + /** + * @param {Uint8Array} key + * @returns {TstNode | null} + */ + search (key) { + const keylength = key.length + let index = 0 + /** + * @type {TstNode|null} + */ + let node = this + while (node !== null && index < keylength) { + let code = key[index] + // A-Z + // First check if it is bigger than 0x5a. + // Lowercase letters have higher char codes than uppercase ones. + // Also we assume that headers will mostly contain lowercase characters. + if (code <= 0x5a && code >= 0x41) { + // Lowercase for uppercase. + code |= 32 + } + while (node !== null) { + if (code === node.code) { + if (keylength === ++index) { + // Returns Node since it is the last key. + return node + } + node = node.middle + break + } + node = node.code < code ? node.left : node.right + } + } + return null + } +} + +class TernarySearchTree { + /** @type {TstNode | null} */ + node = null + + /** + * @param {string} key + * @param {any} value + * @returns {void} + * */ + insert (key, value) { + if (this.node === null) { + this.node = new TstNode(key, value, 0) + } else { + this.node.add(key, value) + } + } + + /** + * @param {Uint8Array} key + * @returns {any} + */ + lookup (key) { + return this.node?.search(key)?.value ?? null + } +} + +const tree = new TernarySearchTree() + +for (let i = 0; i < wellknownHeaderNames.length; ++i) { + const key = headerNameLowerCasedRecord[wellknownHeaderNames[i]] + tree.insert(key, key) +} + +module.exports = { + TernarySearchTree, + tree +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/core/util.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/core/util.js new file mode 100644 index 0000000000000000000000000000000000000000..eda0d03c30dbcd764a7697ff1b9104cfa349ea84 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/core/util.js @@ -0,0 +1,954 @@ +'use strict' + +const assert = require('node:assert') +const { kDestroyed, kBodyUsed, kListeners, kBody } = require('./symbols') +const { IncomingMessage } = require('node:http') +const stream = require('node:stream') +const net = require('node:net') +const { stringify } = require('node:querystring') +const { EventEmitter: EE } = require('node:events') +const timers = require('../util/timers') +const { InvalidArgumentError, ConnectTimeoutError } = require('./errors') +const { headerNameLowerCasedRecord } = require('./constants') +const { tree } = require('./tree') + +const [nodeMajor, nodeMinor] = process.versions.node.split('.', 2).map(v => Number(v)) + +class BodyAsyncIterable { + constructor (body) { + this[kBody] = body + this[kBodyUsed] = false + } + + async * [Symbol.asyncIterator] () { + assert(!this[kBodyUsed], 'disturbed') + this[kBodyUsed] = true + yield * this[kBody] + } +} + +function noop () {} + +/** + * @param {*} body + * @returns {*} + */ +function wrapRequestBody (body) { + if (isStream(body)) { + // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp + // so that it can be dispatched again? + // TODO (fix): Do we need 100-expect support to provide a way to do this properly? + if (bodyLength(body) === 0) { + body + .on('data', function () { + assert(false) + }) + } + + if (typeof body.readableDidRead !== 'boolean') { + body[kBodyUsed] = false + EE.prototype.on.call(body, 'data', function () { + this[kBodyUsed] = true + }) + } + + return body + } else if (body && typeof body.pipeTo === 'function') { + // TODO (fix): We can't access ReadableStream internal state + // to determine whether or not it has been disturbed. This is just + // a workaround. + return new BodyAsyncIterable(body) + } else if ( + body && + typeof body !== 'string' && + !ArrayBuffer.isView(body) && + isIterable(body) + ) { + // TODO: Should we allow re-using iterable if !this.opts.idempotent + // or through some other flag? + return new BodyAsyncIterable(body) + } else { + return body + } +} + +/** + * @param {*} obj + * @returns {obj is import('node:stream').Stream} + */ +function isStream (obj) { + return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function' +} + +/** + * @param {*} object + * @returns {object is Blob} + * based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License) + */ +function isBlobLike (object) { + if (object === null) { + return false + } else if (object instanceof Blob) { + return true + } else if (typeof object !== 'object') { + return false + } else { + const sTag = object[Symbol.toStringTag] + + return (sTag === 'Blob' || sTag === 'File') && ( + ('stream' in object && typeof object.stream === 'function') || + ('arrayBuffer' in object && typeof object.arrayBuffer === 'function') + ) + } +} + +/** + * @param {string} url The path to check for query strings or fragments. + * @returns {boolean} Returns true if the path contains a query string or fragment. + */ +function pathHasQueryOrFragment (url) { + return ( + url.includes('?') || + url.includes('#') + ) +} + +/** + * @param {string} url The URL to add the query params to + * @param {import('node:querystring').ParsedUrlQueryInput} queryParams The object to serialize into a URL query string + * @returns {string} The URL with the query params added + */ +function serializePathWithQuery (url, queryParams) { + if (pathHasQueryOrFragment(url)) { + throw new Error('Query params cannot be passed when url already contains "?" or "#".') + } + + const stringified = stringify(queryParams) + + if (stringified) { + url += '?' + stringified + } + + return url +} + +/** + * @param {number|string|undefined} port + * @returns {boolean} + */ +function isValidPort (port) { + const value = parseInt(port, 10) + return ( + value === Number(port) && + value >= 0 && + value <= 65535 + ) +} + +/** + * Check if the value is a valid http or https prefixed string. + * + * @param {string} value + * @returns {boolean} + */ +function isHttpOrHttpsPrefixed (value) { + return ( + value != null && + value[0] === 'h' && + value[1] === 't' && + value[2] === 't' && + value[3] === 'p' && + ( + value[4] === ':' || + ( + value[4] === 's' && + value[5] === ':' + ) + ) + ) +} + +/** + * @param {string|URL|Record} url + * @returns {URL} + */ +function parseURL (url) { + if (typeof url === 'string') { + /** + * @type {URL} + */ + url = new URL(url) + + if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) { + throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') + } + + return url + } + + if (!url || typeof url !== 'object') { + throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.') + } + + if (!(url instanceof URL)) { + if (url.port != null && url.port !== '' && isValidPort(url.port) === false) { + throw new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.') + } + + if (url.path != null && typeof url.path !== 'string') { + throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.') + } + + if (url.pathname != null && typeof url.pathname !== 'string') { + throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.') + } + + if (url.hostname != null && typeof url.hostname !== 'string') { + throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.') + } + + if (url.origin != null && typeof url.origin !== 'string') { + throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.') + } + + if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) { + throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') + } + + const port = url.port != null + ? url.port + : (url.protocol === 'https:' ? 443 : 80) + let origin = url.origin != null + ? url.origin + : `${url.protocol || ''}//${url.hostname || ''}:${port}` + let path = url.path != null + ? url.path + : `${url.pathname || ''}${url.search || ''}` + + if (origin[origin.length - 1] === '/') { + origin = origin.slice(0, origin.length - 1) + } + + if (path && path[0] !== '/') { + path = `/${path}` + } + // new URL(path, origin) is unsafe when `path` contains an absolute URL + // From https://developer.mozilla.org/en-US/docs/Web/API/URL/URL: + // If first parameter is a relative URL, second param is required, and will be used as the base URL. + // If first parameter is an absolute URL, a given second param will be ignored. + return new URL(`${origin}${path}`) + } + + if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) { + throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') + } + + return url +} + +/** + * @param {string|URL|Record} url + * @returns {URL} + */ +function parseOrigin (url) { + url = parseURL(url) + + if (url.pathname !== '/' || url.search || url.hash) { + throw new InvalidArgumentError('invalid url') + } + + return url +} + +/** + * @param {string} host + * @returns {string} + */ +function getHostname (host) { + if (host[0] === '[') { + const idx = host.indexOf(']') + + assert(idx !== -1) + return host.substring(1, idx) + } + + const idx = host.indexOf(':') + if (idx === -1) return host + + return host.substring(0, idx) +} + +/** + * IP addresses are not valid server names per RFC6066 + * Currently, the only server names supported are DNS hostnames + * @param {string|null} host + * @returns {string|null} + */ +function getServerName (host) { + if (!host) { + return null + } + + assert(typeof host === 'string') + + const servername = getHostname(host) + if (net.isIP(servername)) { + return '' + } + + return servername +} + +/** + * @function + * @template T + * @param {T} obj + * @returns {T} + */ +function deepClone (obj) { + return JSON.parse(JSON.stringify(obj)) +} + +/** + * @param {*} obj + * @returns {obj is AsyncIterable} + */ +function isAsyncIterable (obj) { + return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function') +} + +/** + * @param {*} obj + * @returns {obj is Iterable} + */ +function isIterable (obj) { + return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function')) +} + +/** + * @param {Blob|Buffer|import ('stream').Stream} body + * @returns {number|null} + */ +function bodyLength (body) { + if (body == null) { + return 0 + } else if (isStream(body)) { + const state = body._readableState + return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length) + ? state.length + : null + } else if (isBlobLike(body)) { + return body.size != null ? body.size : null + } else if (isBuffer(body)) { + return body.byteLength + } + + return null +} + +/** + * @param {import ('stream').Stream} body + * @returns {boolean} + */ +function isDestroyed (body) { + return body && !!(body.destroyed || body[kDestroyed] || (stream.isDestroyed?.(body))) +} + +/** + * @param {import ('stream').Stream} stream + * @param {Error} [err] + * @returns {void} + */ +function destroy (stream, err) { + if (stream == null || !isStream(stream) || isDestroyed(stream)) { + return + } + + if (typeof stream.destroy === 'function') { + if (Object.getPrototypeOf(stream).constructor === IncomingMessage) { + // See: https://github.com/nodejs/node/pull/38505/files + stream.socket = null + } + + stream.destroy(err) + } else if (err) { + queueMicrotask(() => { + stream.emit('error', err) + }) + } + + if (stream.destroyed !== true) { + stream[kDestroyed] = true + } +} + +const KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/ +/** + * @param {string} val + * @returns {number | null} + */ +function parseKeepAliveTimeout (val) { + const m = val.match(KEEPALIVE_TIMEOUT_EXPR) + return m ? parseInt(m[1], 10) * 1000 : null +} + +/** + * Retrieves a header name and returns its lowercase value. + * @param {string | Buffer} value Header name + * @returns {string} + */ +function headerNameToString (value) { + return typeof value === 'string' + ? headerNameLowerCasedRecord[value] ?? value.toLowerCase() + : tree.lookup(value) ?? value.toString('latin1').toLowerCase() +} + +/** + * Receive the buffer as a string and return its lowercase value. + * @param {Buffer} value Header name + * @returns {string} + */ +function bufferToLowerCasedHeaderName (value) { + return tree.lookup(value) ?? value.toString('latin1').toLowerCase() +} + +/** + * @param {(Buffer | string)[]} headers + * @param {Record} [obj] + * @returns {Record} + */ +function parseHeaders (headers, obj) { + if (obj === undefined) obj = {} + + for (let i = 0; i < headers.length; i += 2) { + const key = headerNameToString(headers[i]) + let val = obj[key] + + if (val) { + if (typeof val === 'string') { + val = [val] + obj[key] = val + } + val.push(headers[i + 1].toString('utf8')) + } else { + const headersValue = headers[i + 1] + if (typeof headersValue === 'string') { + obj[key] = headersValue + } else { + obj[key] = Array.isArray(headersValue) ? headersValue.map(x => x.toString('utf8')) : headersValue.toString('utf8') + } + } + } + + // See https://github.com/nodejs/node/pull/46528 + if ('content-length' in obj && 'content-disposition' in obj) { + obj['content-disposition'] = Buffer.from(obj['content-disposition']).toString('latin1') + } + + return obj +} + +/** + * @param {Buffer[]} headers + * @returns {string[]} + */ +function parseRawHeaders (headers) { + const headersLength = headers.length + /** + * @type {string[]} + */ + const ret = new Array(headersLength) + + let hasContentLength = false + let contentDispositionIdx = -1 + let key + let val + let kLen = 0 + + for (let n = 0; n < headersLength; n += 2) { + key = headers[n] + val = headers[n + 1] + + typeof key !== 'string' && (key = key.toString()) + typeof val !== 'string' && (val = val.toString('utf8')) + + kLen = key.length + if (kLen === 14 && key[7] === '-' && (key === 'content-length' || key.toLowerCase() === 'content-length')) { + hasContentLength = true + } else if (kLen === 19 && key[7] === '-' && (key === 'content-disposition' || key.toLowerCase() === 'content-disposition')) { + contentDispositionIdx = n + 1 + } + ret[n] = key + ret[n + 1] = val + } + + // See https://github.com/nodejs/node/pull/46528 + if (hasContentLength && contentDispositionIdx !== -1) { + ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1') + } + + return ret +} + +/** + * @param {string[]} headers + * @param {Buffer[]} headers + */ +function encodeRawHeaders (headers) { + if (!Array.isArray(headers)) { + throw new TypeError('expected headers to be an array') + } + return headers.map(x => Buffer.from(x)) +} + +/** + * @param {*} buffer + * @returns {buffer is Buffer} + */ +function isBuffer (buffer) { + // See, https://github.com/mcollina/undici/pull/319 + return buffer instanceof Uint8Array || Buffer.isBuffer(buffer) +} + +/** + * Asserts that the handler object is a request handler. + * + * @param {object} handler + * @param {string} method + * @param {string} [upgrade] + * @returns {asserts handler is import('../api/api-request').RequestHandler} + */ +function assertRequestHandler (handler, method, upgrade) { + if (!handler || typeof handler !== 'object') { + throw new InvalidArgumentError('handler must be an object') + } + + if (typeof handler.onRequestStart === 'function') { + // TODO (fix): More checks... + return + } + + if (typeof handler.onConnect !== 'function') { + throw new InvalidArgumentError('invalid onConnect method') + } + + if (typeof handler.onError !== 'function') { + throw new InvalidArgumentError('invalid onError method') + } + + if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) { + throw new InvalidArgumentError('invalid onBodySent method') + } + + if (upgrade || method === 'CONNECT') { + if (typeof handler.onUpgrade !== 'function') { + throw new InvalidArgumentError('invalid onUpgrade method') + } + } else { + if (typeof handler.onHeaders !== 'function') { + throw new InvalidArgumentError('invalid onHeaders method') + } + + if (typeof handler.onData !== 'function') { + throw new InvalidArgumentError('invalid onData method') + } + + if (typeof handler.onComplete !== 'function') { + throw new InvalidArgumentError('invalid onComplete method') + } + } +} + +/** + * A body is disturbed if it has been read from and it cannot be re-used without + * losing state or data. + * @param {import('node:stream').Readable} body + * @returns {boolean} + */ +function isDisturbed (body) { + // TODO (fix): Why is body[kBodyUsed] needed? + return !!(body && (stream.isDisturbed(body) || body[kBodyUsed])) +} + +/** + * @typedef {object} SocketInfo + * @property {string} [localAddress] + * @property {number} [localPort] + * @property {string} [remoteAddress] + * @property {number} [remotePort] + * @property {string} [remoteFamily] + * @property {number} [timeout] + * @property {number} bytesWritten + * @property {number} bytesRead + */ + +/** + * @param {import('net').Socket} socket + * @returns {SocketInfo} + */ +function getSocketInfo (socket) { + return { + localAddress: socket.localAddress, + localPort: socket.localPort, + remoteAddress: socket.remoteAddress, + remotePort: socket.remotePort, + remoteFamily: socket.remoteFamily, + timeout: socket.timeout, + bytesWritten: socket.bytesWritten, + bytesRead: socket.bytesRead + } +} + +/** + * @param {Iterable} iterable + * @returns {ReadableStream} + */ +function ReadableStreamFrom (iterable) { + // We cannot use ReadableStream.from here because it does not return a byte stream. + + let iterator + return new ReadableStream( + { + async start () { + iterator = iterable[Symbol.asyncIterator]() + }, + pull (controller) { + async function pull () { + const { done, value } = await iterator.next() + if (done) { + queueMicrotask(() => { + controller.close() + controller.byobRequest?.respond(0) + }) + } else { + const buf = Buffer.isBuffer(value) ? value : Buffer.from(value) + if (buf.byteLength) { + controller.enqueue(new Uint8Array(buf)) + } else { + return await pull() + } + } + } + + return pull() + }, + async cancel () { + await iterator.return() + }, + type: 'bytes' + } + ) +} + +/** + * The object should be a FormData instance and contains all the required + * methods. + * @param {*} object + * @returns {object is FormData} + */ +function isFormDataLike (object) { + return ( + object && + typeof object === 'object' && + typeof object.append === 'function' && + typeof object.delete === 'function' && + typeof object.get === 'function' && + typeof object.getAll === 'function' && + typeof object.has === 'function' && + typeof object.set === 'function' && + object[Symbol.toStringTag] === 'FormData' + ) +} + +function addAbortListener (signal, listener) { + if ('addEventListener' in signal) { + signal.addEventListener('abort', listener, { once: true }) + return () => signal.removeEventListener('abort', listener) + } + signal.once('abort', listener) + return () => signal.removeListener('abort', listener) +} + +/** + * @see https://tools.ietf.org/html/rfc7230#section-3.2.6 + * @param {number} c + * @returns {boolean} + */ +function isTokenCharCode (c) { + switch (c) { + case 0x22: + case 0x28: + case 0x29: + case 0x2c: + case 0x2f: + case 0x3a: + case 0x3b: + case 0x3c: + case 0x3d: + case 0x3e: + case 0x3f: + case 0x40: + case 0x5b: + case 0x5c: + case 0x5d: + case 0x7b: + case 0x7d: + // DQUOTE and "(),/:;<=>?@[\]{}" + return false + default: + // VCHAR %x21-7E + return c >= 0x21 && c <= 0x7e + } +} + +/** + * @param {string} characters + * @returns {boolean} + */ +function isValidHTTPToken (characters) { + if (characters.length === 0) { + return false + } + for (let i = 0; i < characters.length; ++i) { + if (!isTokenCharCode(characters.charCodeAt(i))) { + return false + } + } + return true +} + +// headerCharRegex have been lifted from +// https://github.com/nodejs/node/blob/main/lib/_http_common.js + +/** + * Matches if val contains an invalid field-vchar + * field-value = *( field-content / obs-fold ) + * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] + * field-vchar = VCHAR / obs-text + */ +const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/ + +/** + * @param {string} characters + * @returns {boolean} + */ +function isValidHeaderValue (characters) { + return !headerCharRegex.test(characters) +} + +const rangeHeaderRegex = /^bytes (\d+)-(\d+)\/(\d+)?$/ + +/** + * @typedef {object} RangeHeader + * @property {number} start + * @property {number | null} end + * @property {number | null} size + */ + +/** + * Parse accordingly to RFC 9110 + * @see https://www.rfc-editor.org/rfc/rfc9110#field.content-range + * @param {string} [range] + * @returns {RangeHeader|null} + */ +function parseRangeHeader (range) { + if (range == null || range === '') return { start: 0, end: null, size: null } + + const m = range ? range.match(rangeHeaderRegex) : null + return m + ? { + start: parseInt(m[1]), + end: m[2] ? parseInt(m[2]) : null, + size: m[3] ? parseInt(m[3]) : null + } + : null +} + +/** + * @template {import("events").EventEmitter} T + * @param {T} obj + * @param {string} name + * @param {(...args: any[]) => void} listener + * @returns {T} + */ +function addListener (obj, name, listener) { + const listeners = (obj[kListeners] ??= []) + listeners.push([name, listener]) + obj.on(name, listener) + return obj +} + +/** + * @template {import("events").EventEmitter} T + * @param {T} obj + * @returns {T} + */ +function removeAllListeners (obj) { + if (obj[kListeners] != null) { + for (const [name, listener] of obj[kListeners]) { + obj.removeListener(name, listener) + } + obj[kListeners] = null + } + return obj +} + +/** + * @param {import ('../dispatcher/client')} client + * @param {import ('../core/request')} request + * @param {Error} err + */ +function errorRequest (client, request, err) { + try { + request.onError(err) + assert(request.aborted) + } catch (err) { + client.emit('error', err) + } +} + +/** + * @param {WeakRef} socketWeakRef + * @param {object} opts + * @param {number} opts.timeout + * @param {string} opts.hostname + * @param {number} opts.port + * @returns {() => void} + */ +const setupConnectTimeout = process.platform === 'win32' + ? (socketWeakRef, opts) => { + if (!opts.timeout) { + return noop + } + + let s1 = null + let s2 = null + const fastTimer = timers.setFastTimeout(() => { + // setImmediate is added to make sure that we prioritize socket error events over timeouts + s1 = setImmediate(() => { + // Windows needs an extra setImmediate probably due to implementation differences in the socket logic + s2 = setImmediate(() => onConnectTimeout(socketWeakRef.deref(), opts)) + }) + }, opts.timeout) + return () => { + timers.clearFastTimeout(fastTimer) + clearImmediate(s1) + clearImmediate(s2) + } + } + : (socketWeakRef, opts) => { + if (!opts.timeout) { + return noop + } + + let s1 = null + const fastTimer = timers.setFastTimeout(() => { + // setImmediate is added to make sure that we prioritize socket error events over timeouts + s1 = setImmediate(() => { + onConnectTimeout(socketWeakRef.deref(), opts) + }) + }, opts.timeout) + return () => { + timers.clearFastTimeout(fastTimer) + clearImmediate(s1) + } + } + +/** + * @param {net.Socket} socket + * @param {object} opts + * @param {number} opts.timeout + * @param {string} opts.hostname + * @param {number} opts.port + */ +function onConnectTimeout (socket, opts) { + // The socket could be already garbage collected + if (socket == null) { + return + } + + let message = 'Connect Timeout Error' + if (Array.isArray(socket.autoSelectFamilyAttemptedAddresses)) { + message += ` (attempted addresses: ${socket.autoSelectFamilyAttemptedAddresses.join(', ')},` + } else { + message += ` (attempted address: ${opts.hostname}:${opts.port},` + } + + message += ` timeout: ${opts.timeout}ms)` + + destroy(socket, new ConnectTimeoutError(message)) +} + +const kEnumerableProperty = Object.create(null) +kEnumerableProperty.enumerable = true + +const normalizedMethodRecordsBase = { + delete: 'DELETE', + DELETE: 'DELETE', + get: 'GET', + GET: 'GET', + head: 'HEAD', + HEAD: 'HEAD', + options: 'OPTIONS', + OPTIONS: 'OPTIONS', + post: 'POST', + POST: 'POST', + put: 'PUT', + PUT: 'PUT' +} + +const normalizedMethodRecords = { + ...normalizedMethodRecordsBase, + patch: 'patch', + PATCH: 'PATCH' +} + +// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. +Object.setPrototypeOf(normalizedMethodRecordsBase, null) +Object.setPrototypeOf(normalizedMethodRecords, null) + +module.exports = { + kEnumerableProperty, + isDisturbed, + isBlobLike, + parseOrigin, + parseURL, + getServerName, + isStream, + isIterable, + isAsyncIterable, + isDestroyed, + headerNameToString, + bufferToLowerCasedHeaderName, + addListener, + removeAllListeners, + errorRequest, + parseRawHeaders, + encodeRawHeaders, + parseHeaders, + parseKeepAliveTimeout, + destroy, + bodyLength, + deepClone, + ReadableStreamFrom, + isBuffer, + assertRequestHandler, + getSocketInfo, + isFormDataLike, + pathHasQueryOrFragment, + serializePathWithQuery, + addAbortListener, + isValidHTTPToken, + isValidHeaderValue, + isTokenCharCode, + parseRangeHeader, + normalizedMethodRecordsBase, + normalizedMethodRecords, + isValidPort, + isHttpOrHttpsPrefixed, + nodeMajor, + nodeMinor, + safeHTTPMethods: Object.freeze(['GET', 'HEAD', 'OPTIONS', 'TRACE']), + wrapRequestBody, + setupConnectTimeout +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/agent.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/agent.js new file mode 100644 index 0000000000000000000000000000000000000000..af761eb3e6c964396832c705f03e187955a3cf10 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/agent.js @@ -0,0 +1,144 @@ +'use strict' + +const { InvalidArgumentError } = require('../core/errors') +const { kClients, kRunning, kClose, kDestroy, kDispatch, kUrl } = require('../core/symbols') +const DispatcherBase = require('./dispatcher-base') +const Pool = require('./pool') +const Client = require('./client') +const util = require('../core/util') + +const kOnConnect = Symbol('onConnect') +const kOnDisconnect = Symbol('onDisconnect') +const kOnConnectionError = Symbol('onConnectionError') +const kOnDrain = Symbol('onDrain') +const kFactory = Symbol('factory') +const kOptions = Symbol('options') + +function defaultFactory (origin, opts) { + return opts && opts.connections === 1 + ? new Client(origin, opts) + : new Pool(origin, opts) +} + +class Agent extends DispatcherBase { + constructor ({ factory = defaultFactory, connect, ...options } = {}) { + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') + } + + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') + } + + super() + + if (connect && typeof connect !== 'function') { + connect = { ...connect } + } + + this[kOptions] = { ...util.deepClone(options), connect } + this[kFactory] = factory + this[kClients] = new Map() + + this[kOnDrain] = (origin, targets) => { + this.emit('drain', origin, [this, ...targets]) + } + + this[kOnConnect] = (origin, targets) => { + this.emit('connect', origin, [this, ...targets]) + } + + this[kOnDisconnect] = (origin, targets, err) => { + this.emit('disconnect', origin, [this, ...targets], err) + } + + this[kOnConnectionError] = (origin, targets, err) => { + this.emit('connectionError', origin, [this, ...targets], err) + } + } + + get [kRunning] () { + let ret = 0 + for (const { dispatcher } of this[kClients].values()) { + ret += dispatcher[kRunning] + } + return ret + } + + [kDispatch] (opts, handler) { + let key + if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) { + key = String(opts.origin) + } else { + throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.') + } + + const result = this[kClients].get(key) + let dispatcher = result && result.dispatcher + if (!dispatcher) { + const closeClientIfUnused = (connected) => { + const result = this[kClients].get(key) + if (result) { + if (connected) result.count -= 1 + if (result.count <= 0) { + this[kClients].delete(key) + result.dispatcher.close() + } + } + } + dispatcher = this[kFactory](opts.origin, this[kOptions]) + .on('drain', this[kOnDrain]) + .on('connect', (origin, targets) => { + const result = this[kClients].get(key) + if (result) { + result.count += 1 + } + this[kOnConnect](origin, targets) + }) + .on('disconnect', (origin, targets, err) => { + closeClientIfUnused(true) + this[kOnDisconnect](origin, targets, err) + }) + .on('connectionError', (origin, targets, err) => { + closeClientIfUnused(false) + this[kOnConnectionError](origin, targets, err) + }) + + this[kClients].set(key, { count: 0, dispatcher }) + } + + return dispatcher.dispatch(opts, handler) + } + + async [kClose] () { + const closePromises = [] + for (const { dispatcher } of this[kClients].values()) { + closePromises.push(dispatcher.close()) + } + this[kClients].clear() + + await Promise.all(closePromises) + } + + async [kDestroy] (err) { + const destroyPromises = [] + for (const { dispatcher } of this[kClients].values()) { + destroyPromises.push(dispatcher.destroy(err)) + } + this[kClients].clear() + + await Promise.all(destroyPromises) + } + + get stats () { + const allClientStats = {} + for (const { dispatcher } of this[kClients].values()) { + if (dispatcher.stats) { + allClientStats[dispatcher[kUrl].origin] = dispatcher.stats + } + } + return allClientStats + } +} + +module.exports = Agent diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/balanced-pool.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/balanced-pool.js new file mode 100644 index 0000000000000000000000000000000000000000..5bbec0e618dbb5adaae9559093e04a2722224396 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/balanced-pool.js @@ -0,0 +1,206 @@ +'use strict' + +const { + BalancedPoolMissingUpstreamError, + InvalidArgumentError +} = require('../core/errors') +const { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kRemoveClient, + kGetDispatcher +} = require('./pool-base') +const Pool = require('./pool') +const { kUrl } = require('../core/symbols') +const { parseOrigin } = require('../core/util') +const kFactory = Symbol('factory') + +const kOptions = Symbol('options') +const kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor') +const kCurrentWeight = Symbol('kCurrentWeight') +const kIndex = Symbol('kIndex') +const kWeight = Symbol('kWeight') +const kMaxWeightPerServer = Symbol('kMaxWeightPerServer') +const kErrorPenalty = Symbol('kErrorPenalty') + +/** + * Calculate the greatest common divisor of two numbers by + * using the Euclidean algorithm. + * + * @param {number} a + * @param {number} b + * @returns {number} + */ +function getGreatestCommonDivisor (a, b) { + if (a === 0) return b + + while (b !== 0) { + const t = b + b = a % b + a = t + } + return a +} + +function defaultFactory (origin, opts) { + return new Pool(origin, opts) +} + +class BalancedPool extends PoolBase { + constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) { + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') + } + + super() + + this[kOptions] = opts + this[kIndex] = -1 + this[kCurrentWeight] = 0 + + this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100 + this[kErrorPenalty] = this[kOptions].errorPenalty || 15 + + if (!Array.isArray(upstreams)) { + upstreams = [upstreams] + } + + this[kFactory] = factory + + for (const upstream of upstreams) { + this.addUpstream(upstream) + } + this._updateBalancedPoolStats() + } + + addUpstream (upstream) { + const upstreamOrigin = parseOrigin(upstream).origin + + if (this[kClients].find((pool) => ( + pool[kUrl].origin === upstreamOrigin && + pool.closed !== true && + pool.destroyed !== true + ))) { + return this + } + const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions])) + + this[kAddClient](pool) + pool.on('connect', () => { + pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty]) + }) + + pool.on('connectionError', () => { + pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) + this._updateBalancedPoolStats() + }) + + pool.on('disconnect', (...args) => { + const err = args[2] + if (err && err.code === 'UND_ERR_SOCKET') { + // decrease the weight of the pool. + pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) + this._updateBalancedPoolStats() + } + }) + + for (const client of this[kClients]) { + client[kWeight] = this[kMaxWeightPerServer] + } + + this._updateBalancedPoolStats() + + return this + } + + _updateBalancedPoolStats () { + let result = 0 + for (let i = 0; i < this[kClients].length; i++) { + result = getGreatestCommonDivisor(this[kClients][i][kWeight], result) + } + + this[kGreatestCommonDivisor] = result + } + + removeUpstream (upstream) { + const upstreamOrigin = parseOrigin(upstream).origin + + const pool = this[kClients].find((pool) => ( + pool[kUrl].origin === upstreamOrigin && + pool.closed !== true && + pool.destroyed !== true + )) + + if (pool) { + this[kRemoveClient](pool) + } + + return this + } + + get upstreams () { + return this[kClients] + .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true) + .map((p) => p[kUrl].origin) + } + + [kGetDispatcher] () { + // We validate that pools is greater than 0, + // otherwise we would have to wait until an upstream + // is added, which might never happen. + if (this[kClients].length === 0) { + throw new BalancedPoolMissingUpstreamError() + } + + const dispatcher = this[kClients].find(dispatcher => ( + !dispatcher[kNeedDrain] && + dispatcher.closed !== true && + dispatcher.destroyed !== true + )) + + if (!dispatcher) { + return + } + + const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true) + + if (allClientsBusy) { + return + } + + let counter = 0 + + let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain]) + + while (counter++ < this[kClients].length) { + this[kIndex] = (this[kIndex] + 1) % this[kClients].length + const pool = this[kClients][this[kIndex]] + + // find pool index with the largest weight + if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) { + maxWeightIndex = this[kIndex] + } + + // decrease the current weight every `this[kClients].length`. + if (this[kIndex] === 0) { + // Set the current weight to the next lower weight. + this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor] + + if (this[kCurrentWeight] <= 0) { + this[kCurrentWeight] = this[kMaxWeightPerServer] + } + } + if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) { + return pool + } + } + + this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight] + this[kIndex] = maxWeightIndex + return this[kClients][maxWeightIndex] + } +} + +module.exports = BalancedPool diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/client-h1.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/client-h1.js new file mode 100644 index 0000000000000000000000000000000000000000..5e5d89a7b9e03a7ff54950a348c63a59c6fa48ad --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/client-h1.js @@ -0,0 +1,1606 @@ +'use strict' + +/* global WebAssembly */ + +const assert = require('node:assert') +const util = require('../core/util.js') +const { channels } = require('../core/diagnostics.js') +const timers = require('../util/timers.js') +const { + RequestContentLengthMismatchError, + ResponseContentLengthMismatchError, + RequestAbortedError, + HeadersTimeoutError, + HeadersOverflowError, + SocketError, + InformationalError, + BodyTimeoutError, + HTTPParserError, + ResponseExceededMaxSizeError +} = require('../core/errors.js') +const { + kUrl, + kReset, + kClient, + kParser, + kBlocking, + kRunning, + kPending, + kSize, + kWriting, + kQueue, + kNoRef, + kKeepAliveDefaultTimeout, + kHostHeader, + kPendingIdx, + kRunningIdx, + kError, + kPipelining, + kSocket, + kKeepAliveTimeoutValue, + kMaxHeadersSize, + kKeepAliveMaxTimeout, + kKeepAliveTimeoutThreshold, + kHeadersTimeout, + kBodyTimeout, + kStrictContentLength, + kMaxRequests, + kCounter, + kMaxResponseSize, + kOnError, + kResume, + kHTTPContext, + kClosed +} = require('../core/symbols.js') + +const constants = require('../llhttp/constants.js') +const EMPTY_BUF = Buffer.alloc(0) +const FastBuffer = Buffer[Symbol.species] +const removeAllListeners = util.removeAllListeners + +let extractBody + +function lazyllhttp () { + const llhttpWasmData = process.env.JEST_WORKER_ID ? require('../llhttp/llhttp-wasm.js') : undefined + + let mod + try { + mod = new WebAssembly.Module(require('../llhttp/llhttp_simd-wasm.js')) + } catch { + /* istanbul ignore next */ + + // We could check if the error was caused by the simd option not + // being enabled, but the occurring of this other error + // * https://github.com/emscripten-core/emscripten/issues/11495 + // got me to remove that check to avoid breaking Node 12. + mod = new WebAssembly.Module(llhttpWasmData || require('../llhttp/llhttp-wasm.js')) + } + + return new WebAssembly.Instance(mod, { + env: { + /** + * @param {number} p + * @param {number} at + * @param {number} len + * @returns {number} + */ + wasm_on_url: (p, at, len) => { + /* istanbul ignore next */ + return 0 + }, + /** + * @param {number} p + * @param {number} at + * @param {number} len + * @returns {number} + */ + wasm_on_status: (p, at, len) => { + assert(currentParser.ptr === p) + const start = at - currentBufferPtr + currentBufferRef.byteOffset + return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) + }, + /** + * @param {number} p + * @returns {number} + */ + wasm_on_message_begin: (p) => { + assert(currentParser.ptr === p) + return currentParser.onMessageBegin() + }, + /** + * @param {number} p + * @param {number} at + * @param {number} len + * @returns {number} + */ + wasm_on_header_field: (p, at, len) => { + assert(currentParser.ptr === p) + const start = at - currentBufferPtr + currentBufferRef.byteOffset + return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) + }, + /** + * @param {number} p + * @param {number} at + * @param {number} len + * @returns {number} + */ + wasm_on_header_value: (p, at, len) => { + assert(currentParser.ptr === p) + const start = at - currentBufferPtr + currentBufferRef.byteOffset + return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) + }, + /** + * @param {number} p + * @param {number} statusCode + * @param {0|1} upgrade + * @param {0|1} shouldKeepAlive + * @returns {number} + */ + wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => { + assert(currentParser.ptr === p) + return currentParser.onHeadersComplete(statusCode, upgrade === 1, shouldKeepAlive === 1) + }, + /** + * @param {number} p + * @param {number} at + * @param {number} len + * @returns {number} + */ + wasm_on_body: (p, at, len) => { + assert(currentParser.ptr === p) + const start = at - currentBufferPtr + currentBufferRef.byteOffset + return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) + }, + /** + * @param {number} p + * @returns {number} + */ + wasm_on_message_complete: (p) => { + assert(currentParser.ptr === p) + return currentParser.onMessageComplete() + } + + } + }) +} + +let llhttpInstance = null + +/** + * @type {Parser|null} + */ +let currentParser = null +let currentBufferRef = null +/** + * @type {number} + */ +let currentBufferSize = 0 +let currentBufferPtr = null + +const USE_NATIVE_TIMER = 0 +const USE_FAST_TIMER = 1 + +// Use fast timers for headers and body to take eventual event loop +// latency into account. +const TIMEOUT_HEADERS = 2 | USE_FAST_TIMER +const TIMEOUT_BODY = 4 | USE_FAST_TIMER + +// Use native timers to ignore event loop latency for keep-alive +// handling. +const TIMEOUT_KEEP_ALIVE = 8 | USE_NATIVE_TIMER + +class Parser { + /** + * @param {import('./client.js')} client + * @param {import('net').Socket} socket + * @param {*} llhttp + */ + constructor (client, socket, { exports }) { + this.llhttp = exports + this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE) + this.client = client + /** + * @type {import('net').Socket} + */ + this.socket = socket + this.timeout = null + this.timeoutValue = null + this.timeoutType = null + this.statusCode = 0 + this.statusText = '' + this.upgrade = false + this.headers = [] + this.headersSize = 0 + this.headersMaxSize = client[kMaxHeadersSize] + this.shouldKeepAlive = false + this.paused = false + this.resume = this.resume.bind(this) + + this.bytesRead = 0 + + this.keepAlive = '' + this.contentLength = '' + this.connection = '' + this.maxResponseSize = client[kMaxResponseSize] + } + + setTimeout (delay, type) { + // If the existing timer and the new timer are of different timer type + // (fast or native) or have different delay, we need to clear the existing + // timer and set a new one. + if ( + delay !== this.timeoutValue || + (type & USE_FAST_TIMER) ^ (this.timeoutType & USE_FAST_TIMER) + ) { + // If a timeout is already set, clear it with clearTimeout of the fast + // timer implementation, as it can clear fast and native timers. + if (this.timeout) { + timers.clearTimeout(this.timeout) + this.timeout = null + } + + if (delay) { + if (type & USE_FAST_TIMER) { + this.timeout = timers.setFastTimeout(onParserTimeout, delay, new WeakRef(this)) + } else { + this.timeout = setTimeout(onParserTimeout, delay, new WeakRef(this)) + this.timeout?.unref() + } + } + + this.timeoutValue = delay + } else if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh() + } + } + + this.timeoutType = type + } + + resume () { + if (this.socket.destroyed || !this.paused) { + return + } + + assert(this.ptr != null) + assert(currentParser === null) + + this.llhttp.llhttp_resume(this.ptr) + + assert(this.timeoutType === TIMEOUT_BODY) + if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh() + } + } + + this.paused = false + this.execute(this.socket.read() || EMPTY_BUF) // Flush parser. + this.readMore() + } + + readMore () { + while (!this.paused && this.ptr) { + const chunk = this.socket.read() + if (chunk === null) { + break + } + this.execute(chunk) + } + } + + /** + * @param {Buffer} chunk + */ + execute (chunk) { + assert(currentParser === null) + assert(this.ptr != null) + assert(!this.paused) + + const { socket, llhttp } = this + + // Allocate a new buffer if the current buffer is too small. + if (chunk.length > currentBufferSize) { + if (currentBufferPtr) { + llhttp.free(currentBufferPtr) + } + // Allocate a buffer that is a multiple of 4096 bytes. + currentBufferSize = Math.ceil(chunk.length / 4096) * 4096 + currentBufferPtr = llhttp.malloc(currentBufferSize) + } + + new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(chunk) + + // Call `execute` on the wasm parser. + // We pass the `llhttp_parser` pointer address, the pointer address of buffer view data, + // and finally the length of bytes to parse. + // The return value is an error code or `constants.ERROR.OK`. + try { + let ret + + try { + currentBufferRef = chunk + currentParser = this + ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, chunk.length) + /* eslint-disable-next-line no-useless-catch */ + } catch (err) { + /* istanbul ignore next: difficult to make a test case for */ + throw err + } finally { + currentParser = null + currentBufferRef = null + } + + if (ret !== constants.ERROR.OK) { + const data = chunk.subarray(llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr) + + if (ret === constants.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data) + } else if (ret === constants.ERROR.PAUSED) { + this.paused = true + socket.unshift(data) + } else { + const ptr = llhttp.llhttp_get_error_reason(this.ptr) + let message = '' + /* istanbul ignore else: difficult to make a test case for */ + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0) + message = + 'Response does not match the HTTP/1.1 protocol (' + + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + + ')' + } + throw new HTTPParserError(message, constants.ERROR[ret], data) + } + } + } catch (err) { + util.destroy(socket, err) + } + } + + destroy () { + assert(currentParser === null) + assert(this.ptr != null) + + this.llhttp.llhttp_free(this.ptr) + this.ptr = null + + this.timeout && timers.clearTimeout(this.timeout) + this.timeout = null + this.timeoutValue = null + this.timeoutType = null + + this.paused = false + } + + /** + * @param {Buffer} buf + * @returns {0} + */ + onStatus (buf) { + this.statusText = buf.toString() + return 0 + } + + /** + * @returns {0|-1} + */ + onMessageBegin () { + const { socket, client } = this + + /* istanbul ignore next: difficult to make a test case for */ + if (socket.destroyed) { + return -1 + } + + const request = client[kQueue][client[kRunningIdx]] + if (!request) { + return -1 + } + request.onResponseStarted() + + return 0 + } + + /** + * @param {Buffer} buf + * @returns {number} + */ + onHeaderField (buf) { + const len = this.headers.length + + if ((len & 1) === 0) { + this.headers.push(buf) + } else { + this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) + } + + this.trackHeader(buf.length) + + return 0 + } + + /** + * @param {Buffer} buf + * @returns {number} + */ + onHeaderValue (buf) { + let len = this.headers.length + + if ((len & 1) === 1) { + this.headers.push(buf) + len += 1 + } else { + this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) + } + + const key = this.headers[len - 2] + if (key.length === 10) { + const headerName = util.bufferToLowerCasedHeaderName(key) + if (headerName === 'keep-alive') { + this.keepAlive += buf.toString() + } else if (headerName === 'connection') { + this.connection += buf.toString() + } + } else if (key.length === 14 && util.bufferToLowerCasedHeaderName(key) === 'content-length') { + this.contentLength += buf.toString() + } + + this.trackHeader(buf.length) + + return 0 + } + + /** + * @param {number} len + */ + trackHeader (len) { + this.headersSize += len + if (this.headersSize >= this.headersMaxSize) { + util.destroy(this.socket, new HeadersOverflowError()) + } + } + + /** + * @param {Buffer} head + */ + onUpgrade (head) { + const { upgrade, client, socket, headers, statusCode } = this + + assert(upgrade) + assert(client[kSocket] === socket) + assert(!socket.destroyed) + assert(!this.paused) + assert((headers.length & 1) === 0) + + const request = client[kQueue][client[kRunningIdx]] + assert(request) + assert(request.upgrade || request.method === 'CONNECT') + + this.statusCode = 0 + this.statusText = '' + this.shouldKeepAlive = false + + this.headers = [] + this.headersSize = 0 + + socket.unshift(head) + + socket[kParser].destroy() + socket[kParser] = null + + socket[kClient] = null + socket[kError] = null + + removeAllListeners(socket) + + client[kSocket] = null + client[kHTTPContext] = null // TODO (fix): This is hacky... + client[kQueue][client[kRunningIdx]++] = null + client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade')) + + try { + request.onUpgrade(statusCode, headers, socket) + } catch (err) { + util.destroy(socket, err) + } + + client[kResume]() + } + + /** + * @param {number} statusCode + * @param {boolean} upgrade + * @param {boolean} shouldKeepAlive + * @returns {number} + */ + onHeadersComplete (statusCode, upgrade, shouldKeepAlive) { + const { client, socket, headers, statusText } = this + + /* istanbul ignore next: difficult to make a test case for */ + if (socket.destroyed) { + return -1 + } + + const request = client[kQueue][client[kRunningIdx]] + + /* istanbul ignore next: difficult to make a test case for */ + if (!request) { + return -1 + } + + assert(!this.upgrade) + assert(this.statusCode < 200) + + if (statusCode === 100) { + util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket))) + return -1 + } + + /* this can only happen if server is misbehaving */ + if (upgrade && !request.upgrade) { + util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket))) + return -1 + } + + assert(this.timeoutType === TIMEOUT_HEADERS) + + this.statusCode = statusCode + this.shouldKeepAlive = ( + shouldKeepAlive || + // Override llhttp value which does not allow keepAlive for HEAD. + (request.method === 'HEAD' && !socket[kReset] && this.connection.toLowerCase() === 'keep-alive') + ) + + if (this.statusCode >= 200) { + const bodyTimeout = request.bodyTimeout != null + ? request.bodyTimeout + : client[kBodyTimeout] + this.setTimeout(bodyTimeout, TIMEOUT_BODY) + } else if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh() + } + } + + if (request.method === 'CONNECT') { + assert(client[kRunning] === 1) + this.upgrade = true + return 2 + } + + if (upgrade) { + assert(client[kRunning] === 1) + this.upgrade = true + return 2 + } + + assert((this.headers.length & 1) === 0) + this.headers = [] + this.headersSize = 0 + + if (this.shouldKeepAlive && client[kPipelining]) { + const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null + + if (keepAliveTimeout != null) { + const timeout = Math.min( + keepAliveTimeout - client[kKeepAliveTimeoutThreshold], + client[kKeepAliveMaxTimeout] + ) + if (timeout <= 0) { + socket[kReset] = true + } else { + client[kKeepAliveTimeoutValue] = timeout + } + } else { + client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout] + } + } else { + // Stop more requests from being dispatched. + socket[kReset] = true + } + + const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false + + if (request.aborted) { + return -1 + } + + if (request.method === 'HEAD') { + return 1 + } + + if (statusCode < 200) { + return 1 + } + + if (socket[kBlocking]) { + socket[kBlocking] = false + client[kResume]() + } + + return pause ? constants.ERROR.PAUSED : 0 + } + + /** + * @param {Buffer} buf + * @returns {number} + */ + onBody (buf) { + const { client, socket, statusCode, maxResponseSize } = this + + if (socket.destroyed) { + return -1 + } + + const request = client[kQueue][client[kRunningIdx]] + assert(request) + + assert(this.timeoutType === TIMEOUT_BODY) + if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh() + } + } + + assert(statusCode >= 200) + + if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) { + util.destroy(socket, new ResponseExceededMaxSizeError()) + return -1 + } + + this.bytesRead += buf.length + + if (request.onData(buf) === false) { + return constants.ERROR.PAUSED + } + + return 0 + } + + /** + * @returns {number} + */ + onMessageComplete () { + const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this + + if (socket.destroyed && (!statusCode || shouldKeepAlive)) { + return -1 + } + + if (upgrade) { + return 0 + } + + assert(statusCode >= 100) + assert((this.headers.length & 1) === 0) + + const request = client[kQueue][client[kRunningIdx]] + assert(request) + + this.statusCode = 0 + this.statusText = '' + this.bytesRead = 0 + this.contentLength = '' + this.keepAlive = '' + this.connection = '' + + this.headers = [] + this.headersSize = 0 + + if (statusCode < 200) { + return 0 + } + + /* istanbul ignore next: should be handled by llhttp? */ + if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) { + util.destroy(socket, new ResponseContentLengthMismatchError()) + return -1 + } + + request.onComplete(headers) + + client[kQueue][client[kRunningIdx]++] = null + + if (socket[kWriting]) { + assert(client[kRunning] === 0) + // Response completed before request. + util.destroy(socket, new InformationalError('reset')) + return constants.ERROR.PAUSED + } else if (!shouldKeepAlive) { + util.destroy(socket, new InformationalError('reset')) + return constants.ERROR.PAUSED + } else if (socket[kReset] && client[kRunning] === 0) { + // Destroy socket once all requests have completed. + // The request at the tail of the pipeline is the one + // that requested reset and no further requests should + // have been queued since then. + util.destroy(socket, new InformationalError('reset')) + return constants.ERROR.PAUSED + } else if (client[kPipelining] == null || client[kPipelining] === 1) { + // We must wait a full event loop cycle to reuse this socket to make sure + // that non-spec compliant servers are not closing the connection even if they + // said they won't. + setImmediate(client[kResume]) + } else { + client[kResume]() + } + + return 0 + } +} + +function onParserTimeout (parser) { + const { socket, timeoutType, client, paused } = parser.deref() + + /* istanbul ignore else */ + if (timeoutType === TIMEOUT_HEADERS) { + if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) { + assert(!paused, 'cannot be paused while waiting for headers') + util.destroy(socket, new HeadersTimeoutError()) + } + } else if (timeoutType === TIMEOUT_BODY) { + if (!paused) { + util.destroy(socket, new BodyTimeoutError()) + } + } else if (timeoutType === TIMEOUT_KEEP_ALIVE) { + assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue]) + util.destroy(socket, new InformationalError('socket idle timeout')) + } +} + +/** + * @param {import ('./client.js')} client + * @param {import('net').Socket} socket + * @returns + */ +async function connectH1 (client, socket) { + client[kSocket] = socket + + if (!llhttpInstance) { + llhttpInstance = lazyllhttp() + } + + if (socket.errored) { + throw socket.errored + } + + if (socket.destroyed) { + throw new SocketError('destroyed') + } + + socket[kNoRef] = false + socket[kWriting] = false + socket[kReset] = false + socket[kBlocking] = false + socket[kParser] = new Parser(client, socket, llhttpInstance) + + util.addListener(socket, 'error', onHttpSocketError) + util.addListener(socket, 'readable', onHttpSocketReadable) + util.addListener(socket, 'end', onHttpSocketEnd) + util.addListener(socket, 'close', onHttpSocketClose) + + socket[kClosed] = false + socket.on('close', onSocketClose) + + return { + version: 'h1', + defaultPipelining: 1, + write (request) { + return writeH1(client, request) + }, + resume () { + resumeH1(client) + }, + /** + * @param {Error|undefined} err + * @param {() => void} callback + */ + destroy (err, callback) { + if (socket[kClosed]) { + queueMicrotask(callback) + } else { + socket.on('close', callback) + socket.destroy(err) + } + }, + /** + * @returns {boolean} + */ + get destroyed () { + return socket.destroyed + }, + /** + * @param {import('../core/request.js')} request + * @returns {boolean} + */ + busy (request) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { + return true + } + + if (request) { + if (client[kRunning] > 0 && !request.idempotent) { + // Non-idempotent request cannot be retried. + // Ensure that no other requests are inflight and + // could cause failure. + return true + } + + if (client[kRunning] > 0 && (request.upgrade || request.method === 'CONNECT')) { + // Don't dispatch an upgrade until all preceding requests have completed. + // A misbehaving server might upgrade the connection before all pipelined + // request has completed. + return true + } + + if (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 && + (util.isStream(request.body) || util.isAsyncIterable(request.body) || util.isFormDataLike(request.body))) { + // Request with stream or iterator body can error while other requests + // are inflight and indirectly error those as well. + // Ensure this doesn't happen by waiting for inflight + // to complete before dispatching. + + // Request with stream or iterator body cannot be retried. + // Ensure that no other requests are inflight and + // could cause failure. + return true + } + } + + return false + } + } +} + +function onHttpSocketError (err) { + assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') + + const parser = this[kParser] + + // On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded + // to the user. + if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) { + // We treat all incoming data so for as a valid response. + parser.onMessageComplete() + return + } + + this[kError] = err + + this[kClient][kOnError](err) +} + +function onHttpSocketReadable () { + this[kParser]?.readMore() +} + +function onHttpSocketEnd () { + const parser = this[kParser] + + if (parser.statusCode && !parser.shouldKeepAlive) { + // We treat all incoming data so far as a valid response. + parser.onMessageComplete() + return + } + + util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this))) +} + +function onHttpSocketClose () { + const parser = this[kParser] + + if (parser) { + if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { + // We treat all incoming data so far as a valid response. + parser.onMessageComplete() + } + + this[kParser].destroy() + this[kParser] = null + } + + const err = this[kError] || new SocketError('closed', util.getSocketInfo(this)) + + const client = this[kClient] + + client[kSocket] = null + client[kHTTPContext] = null // TODO (fix): This is hacky... + + if (client.destroyed) { + assert(client[kPending] === 0) + + // Fail entire queue. + const requests = client[kQueue].splice(client[kRunningIdx]) + for (let i = 0; i < requests.length; i++) { + const request = requests[i] + util.errorRequest(client, request, err) + } + } else if (client[kRunning] > 0 && err.code !== 'UND_ERR_INFO') { + // Fail head of pipeline. + const request = client[kQueue][client[kRunningIdx]] + client[kQueue][client[kRunningIdx]++] = null + + util.errorRequest(client, request, err) + } + + client[kPendingIdx] = client[kRunningIdx] + + assert(client[kRunning] === 0) + + client.emit('disconnect', client[kUrl], [client], err) + + client[kResume]() +} + +function onSocketClose () { + this[kClosed] = true +} + +/** + * @param {import('./client.js')} client + */ +function resumeH1 (client) { + const socket = client[kSocket] + + if (socket && !socket.destroyed) { + if (client[kSize] === 0) { + if (!socket[kNoRef] && socket.unref) { + socket.unref() + socket[kNoRef] = true + } + } else if (socket[kNoRef] && socket.ref) { + socket.ref() + socket[kNoRef] = false + } + + if (client[kSize] === 0) { + if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { + socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE) + } + } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) { + if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) { + const request = client[kQueue][client[kRunningIdx]] + const headersTimeout = request.headersTimeout != null + ? request.headersTimeout + : client[kHeadersTimeout] + socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS) + } + } + } +} + +// https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2 +function shouldSendContentLength (method) { + return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT' +} + +/** + * @param {import('./client.js')} client + * @param {import('../core/request.js')} request + * @returns + */ +function writeH1 (client, request) { + const { method, path, host, upgrade, blocking, reset } = request + + let { body, headers, contentLength } = request + + // https://tools.ietf.org/html/rfc7231#section-4.3.1 + // https://tools.ietf.org/html/rfc7231#section-4.3.2 + // https://tools.ietf.org/html/rfc7231#section-4.3.5 + + // Sending a payload body on a request that does not + // expect it can cause undefined behavior on some + // servers and corrupt connection state. Do not + // re-use the connection for further requests. + + const expectsPayload = ( + method === 'PUT' || + method === 'POST' || + method === 'PATCH' || + method === 'QUERY' || + method === 'PROPFIND' || + method === 'PROPPATCH' + ) + + if (util.isFormDataLike(body)) { + if (!extractBody) { + extractBody = require('../web/fetch/body.js').extractBody + } + + const [bodyStream, contentType] = extractBody(body) + if (request.contentType == null) { + headers.push('content-type', contentType) + } + body = bodyStream.stream + contentLength = bodyStream.length + } else if (util.isBlobLike(body) && request.contentType == null && body.type) { + headers.push('content-type', body.type) + } + + if (body && typeof body.read === 'function') { + // Try to read EOF in order to get length. + body.read(0) + } + + const bodyLength = util.bodyLength(body) + + contentLength = bodyLength ?? contentLength + + if (contentLength === null) { + contentLength = request.contentLength + } + + if (contentLength === 0 && !expectsPayload) { + // https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD NOT send a Content-Length header field when + // the request message does not contain a payload body and the method + // semantics do not anticipate such a body. + + contentLength = null + } + + // https://github.com/nodejs/undici/issues/2046 + // A user agent may send a Content-Length header with 0 value, this should be allowed. + if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) { + if (client[kStrictContentLength]) { + util.errorRequest(client, request, new RequestContentLengthMismatchError()) + return false + } + + process.emitWarning(new RequestContentLengthMismatchError()) + } + + const socket = client[kSocket] + + /** + * @param {Error} [err] + * @returns {void} + */ + const abort = (err) => { + if (request.aborted || request.completed) { + return + } + + util.errorRequest(client, request, err || new RequestAbortedError()) + + util.destroy(body) + util.destroy(socket, new InformationalError('aborted')) + } + + try { + request.onConnect(abort) + } catch (err) { + util.errorRequest(client, request, err) + } + + if (request.aborted) { + return false + } + + if (method === 'HEAD') { + // https://github.com/mcollina/undici/issues/258 + // Close after a HEAD request to interop with misbehaving servers + // that may send a body in the response. + + socket[kReset] = true + } + + if (upgrade || method === 'CONNECT') { + // On CONNECT or upgrade, block pipeline from dispatching further + // requests on this connection. + + socket[kReset] = true + } + + if (reset != null) { + socket[kReset] = reset + } + + if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) { + socket[kReset] = true + } + + if (blocking) { + socket[kBlocking] = true + } + + let header = `${method} ${path} HTTP/1.1\r\n` + + if (typeof host === 'string') { + header += `host: ${host}\r\n` + } else { + header += client[kHostHeader] + } + + if (upgrade) { + header += `connection: upgrade\r\nupgrade: ${upgrade}\r\n` + } else if (client[kPipelining] && !socket[kReset]) { + header += 'connection: keep-alive\r\n' + } else { + header += 'connection: close\r\n' + } + + if (Array.isArray(headers)) { + for (let n = 0; n < headers.length; n += 2) { + const key = headers[n + 0] + const val = headers[n + 1] + + if (Array.isArray(val)) { + for (let i = 0; i < val.length; i++) { + header += `${key}: ${val[i]}\r\n` + } + } else { + header += `${key}: ${val}\r\n` + } + } + } + + if (channels.sendHeaders.hasSubscribers) { + channels.sendHeaders.publish({ request, headers: header, socket }) + } + + /* istanbul ignore else: assertion */ + if (!body || bodyLength === 0) { + writeBuffer(abort, null, client, request, socket, contentLength, header, expectsPayload) + } else if (util.isBuffer(body)) { + writeBuffer(abort, body, client, request, socket, contentLength, header, expectsPayload) + } else if (util.isBlobLike(body)) { + if (typeof body.stream === 'function') { + writeIterable(abort, body.stream(), client, request, socket, contentLength, header, expectsPayload) + } else { + writeBlob(abort, body, client, request, socket, contentLength, header, expectsPayload) + } + } else if (util.isStream(body)) { + writeStream(abort, body, client, request, socket, contentLength, header, expectsPayload) + } else if (util.isIterable(body)) { + writeIterable(abort, body, client, request, socket, contentLength, header, expectsPayload) + } else { + assert(false) + } + + return true +} + +/** + * @param {AbortCallback} abort + * @param {import('stream').Stream} body + * @param {import('./client.js')} client + * @param {import('../core/request.js')} request + * @param {import('net').Socket} socket + * @param {number} contentLength + * @param {string} header + * @param {boolean} expectsPayload + */ +function writeStream (abort, body, client, request, socket, contentLength, header, expectsPayload) { + assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined') + + let finished = false + + const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header }) + + /** + * @param {Buffer} chunk + * @returns {void} + */ + const onData = function (chunk) { + if (finished) { + return + } + + try { + if (!writer.write(chunk) && this.pause) { + this.pause() + } + } catch (err) { + util.destroy(this, err) + } + } + + /** + * @returns {void} + */ + const onDrain = function () { + if (finished) { + return + } + + if (body.resume) { + body.resume() + } + } + + /** + * @returns {void} + */ + const onClose = function () { + // 'close' might be emitted *before* 'error' for + // broken streams. Wait a tick to avoid this case. + queueMicrotask(() => { + // It's only safe to remove 'error' listener after + // 'close'. + body.removeListener('error', onFinished) + }) + + if (!finished) { + const err = new RequestAbortedError() + queueMicrotask(() => onFinished(err)) + } + } + + /** + * @param {Error} [err] + * @returns + */ + const onFinished = function (err) { + if (finished) { + return + } + + finished = true + + assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1)) + + socket + .off('drain', onDrain) + .off('error', onFinished) + + body + .removeListener('data', onData) + .removeListener('end', onFinished) + .removeListener('close', onClose) + + if (!err) { + try { + writer.end() + } catch (er) { + err = er + } + } + + writer.destroy(err) + + if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) { + util.destroy(body, err) + } else { + util.destroy(body) + } + } + + body + .on('data', onData) + .on('end', onFinished) + .on('error', onFinished) + .on('close', onClose) + + if (body.resume) { + body.resume() + } + + socket + .on('drain', onDrain) + .on('error', onFinished) + + if (body.errorEmitted ?? body.errored) { + setImmediate(onFinished, body.errored) + } else if (body.endEmitted ?? body.readableEnded) { + setImmediate(onFinished, null) + } + + if (body.closeEmitted ?? body.closed) { + setImmediate(onClose) + } +} + +/** + * @typedef AbortCallback + * @type {Function} + * @param {Error} [err] + * @returns {void} + */ + +/** + * @param {AbortCallback} abort + * @param {Uint8Array|null} body + * @param {import('./client.js')} client + * @param {import('../core/request.js')} request + * @param {import('net').Socket} socket + * @param {number} contentLength + * @param {string} header + * @param {boolean} expectsPayload + * @returns {void} + */ +function writeBuffer (abort, body, client, request, socket, contentLength, header, expectsPayload) { + try { + if (!body) { + if (contentLength === 0) { + socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1') + } else { + assert(contentLength === null, 'no body must not have content length') + socket.write(`${header}\r\n`, 'latin1') + } + } else if (util.isBuffer(body)) { + assert(contentLength === body.byteLength, 'buffer body must have content length') + + socket.cork() + socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') + socket.write(body) + socket.uncork() + request.onBodySent(body) + + if (!expectsPayload && request.reset !== false) { + socket[kReset] = true + } + } + request.onRequestSent() + + client[kResume]() + } catch (err) { + abort(err) + } +} + +/** + * @param {AbortCallback} abort + * @param {Blob} body + * @param {import('./client.js')} client + * @param {import('../core/request.js')} request + * @param {import('net').Socket} socket + * @param {number} contentLength + * @param {string} header + * @param {boolean} expectsPayload + * @returns {Promise} + */ +async function writeBlob (abort, body, client, request, socket, contentLength, header, expectsPayload) { + assert(contentLength === body.size, 'blob body must have content length') + + try { + if (contentLength != null && contentLength !== body.size) { + throw new RequestContentLengthMismatchError() + } + + const buffer = Buffer.from(await body.arrayBuffer()) + + socket.cork() + socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') + socket.write(buffer) + socket.uncork() + + request.onBodySent(buffer) + request.onRequestSent() + + if (!expectsPayload && request.reset !== false) { + socket[kReset] = true + } + + client[kResume]() + } catch (err) { + abort(err) + } +} + +/** + * @param {AbortCallback} abort + * @param {Iterable} body + * @param {import('./client.js')} client + * @param {import('../core/request.js')} request + * @param {import('net').Socket} socket + * @param {number} contentLength + * @param {string} header + * @param {boolean} expectsPayload + * @returns {Promise} + */ +async function writeIterable (abort, body, client, request, socket, contentLength, header, expectsPayload) { + assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined') + + let callback = null + function onDrain () { + if (callback) { + const cb = callback + callback = null + cb() + } + } + + const waitForDrain = () => new Promise((resolve, reject) => { + assert(callback === null) + + if (socket[kError]) { + reject(socket[kError]) + } else { + callback = resolve + } + }) + + socket + .on('close', onDrain) + .on('drain', onDrain) + + const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header }) + try { + // It's up to the user to somehow abort the async iterable. + for await (const chunk of body) { + if (socket[kError]) { + throw socket[kError] + } + + if (!writer.write(chunk)) { + await waitForDrain() + } + } + + writer.end() + } catch (err) { + writer.destroy(err) + } finally { + socket + .off('close', onDrain) + .off('drain', onDrain) + } +} + +class AsyncWriter { + /** + * + * @param {object} arg + * @param {AbortCallback} arg.abort + * @param {import('net').Socket} arg.socket + * @param {import('../core/request.js')} arg.request + * @param {number} arg.contentLength + * @param {import('./client.js')} arg.client + * @param {boolean} arg.expectsPayload + * @param {string} arg.header + */ + constructor ({ abort, socket, request, contentLength, client, expectsPayload, header }) { + this.socket = socket + this.request = request + this.contentLength = contentLength + this.client = client + this.bytesWritten = 0 + this.expectsPayload = expectsPayload + this.header = header + this.abort = abort + + socket[kWriting] = true + } + + /** + * @param {Buffer} chunk + * @returns + */ + write (chunk) { + const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this + + if (socket[kError]) { + throw socket[kError] + } + + if (socket.destroyed) { + return false + } + + const len = Buffer.byteLength(chunk) + if (!len) { + return true + } + + // We should defer writing chunks. + if (contentLength !== null && bytesWritten + len > contentLength) { + if (client[kStrictContentLength]) { + throw new RequestContentLengthMismatchError() + } + + process.emitWarning(new RequestContentLengthMismatchError()) + } + + socket.cork() + + if (bytesWritten === 0) { + if (!expectsPayload && request.reset !== false) { + socket[kReset] = true + } + + if (contentLength === null) { + socket.write(`${header}transfer-encoding: chunked\r\n`, 'latin1') + } else { + socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') + } + } + + if (contentLength === null) { + socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1') + } + + this.bytesWritten += len + + const ret = socket.write(chunk) + + socket.uncork() + + request.onBodySent(chunk) + + if (!ret) { + if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { + // istanbul ignore else: only for jest + if (socket[kParser].timeout.refresh) { + socket[kParser].timeout.refresh() + } + } + } + + return ret + } + + /** + * @returns {void} + */ + end () { + const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this + request.onRequestSent() + + socket[kWriting] = false + + if (socket[kError]) { + throw socket[kError] + } + + if (socket.destroyed) { + return + } + + if (bytesWritten === 0) { + if (expectsPayload) { + // https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD send a Content-Length in a request message when + // no Transfer-Encoding is sent and the request method defines a meaning + // for an enclosed payload body. + + socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1') + } else { + socket.write(`${header}\r\n`, 'latin1') + } + } else if (contentLength === null) { + socket.write('\r\n0\r\n\r\n', 'latin1') + } + + if (contentLength !== null && bytesWritten !== contentLength) { + if (client[kStrictContentLength]) { + throw new RequestContentLengthMismatchError() + } else { + process.emitWarning(new RequestContentLengthMismatchError()) + } + } + + if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { + // istanbul ignore else: only for jest + if (socket[kParser].timeout.refresh) { + socket[kParser].timeout.refresh() + } + } + + client[kResume]() + } + + /** + * @param {Error} [err] + * @returns {void} + */ + destroy (err) { + const { socket, client, abort } = this + + socket[kWriting] = false + + if (err) { + assert(client[kRunning] <= 1, 'pipeline should only contain this request') + abort(err) + } + } +} + +module.exports = connectH1 diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/client-h2.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/client-h2.js new file mode 100644 index 0000000000000000000000000000000000000000..661d857bee1413cc1c669bdca924b220ef58569b --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/client-h2.js @@ -0,0 +1,798 @@ +'use strict' + +const assert = require('node:assert') +const { pipeline } = require('node:stream') +const util = require('../core/util.js') +const { + RequestContentLengthMismatchError, + RequestAbortedError, + SocketError, + InformationalError +} = require('../core/errors.js') +const { + kUrl, + kReset, + kClient, + kRunning, + kPending, + kQueue, + kPendingIdx, + kRunningIdx, + kError, + kSocket, + kStrictContentLength, + kOnError, + kMaxConcurrentStreams, + kHTTP2Session, + kResume, + kSize, + kHTTPContext, + kClosed, + kBodyTimeout +} = require('../core/symbols.js') +const { channels } = require('../core/diagnostics.js') + +const kOpenStreams = Symbol('open streams') + +let extractBody + +/** @type {import('http2')} */ +let http2 +try { + http2 = require('node:http2') +} catch { + // @ts-ignore + http2 = { constants: {} } +} + +const { + constants: { + HTTP2_HEADER_AUTHORITY, + HTTP2_HEADER_METHOD, + HTTP2_HEADER_PATH, + HTTP2_HEADER_SCHEME, + HTTP2_HEADER_CONTENT_LENGTH, + HTTP2_HEADER_EXPECT, + HTTP2_HEADER_STATUS + } +} = http2 + +function parseH2Headers (headers) { + const result = [] + + for (const [name, value] of Object.entries(headers)) { + // h2 may concat the header value by array + // e.g. Set-Cookie + if (Array.isArray(value)) { + for (const subvalue of value) { + // we need to provide each header value of header name + // because the headers handler expect name-value pair + result.push(Buffer.from(name), Buffer.from(subvalue)) + } + } else { + result.push(Buffer.from(name), Buffer.from(value)) + } + } + + return result +} + +async function connectH2 (client, socket) { + client[kSocket] = socket + + const session = http2.connect(client[kUrl], { + createConnection: () => socket, + peerMaxConcurrentStreams: client[kMaxConcurrentStreams], + settings: { + // TODO(metcoder95): add support for PUSH + enablePush: false + } + }) + + session[kOpenStreams] = 0 + session[kClient] = client + session[kSocket] = socket + session[kHTTP2Session] = null + + util.addListener(session, 'error', onHttp2SessionError) + util.addListener(session, 'frameError', onHttp2FrameError) + util.addListener(session, 'end', onHttp2SessionEnd) + util.addListener(session, 'goaway', onHttp2SessionGoAway) + util.addListener(session, 'close', onHttp2SessionClose) + + session.unref() + + client[kHTTP2Session] = session + socket[kHTTP2Session] = session + + util.addListener(socket, 'error', onHttp2SocketError) + util.addListener(socket, 'end', onHttp2SocketEnd) + util.addListener(socket, 'close', onHttp2SocketClose) + + socket[kClosed] = false + socket.on('close', onSocketClose) + + return { + version: 'h2', + defaultPipelining: Infinity, + write (request) { + return writeH2(client, request) + }, + resume () { + resumeH2(client) + }, + destroy (err, callback) { + if (socket[kClosed]) { + queueMicrotask(callback) + } else { + socket.destroy(err).on('close', callback) + } + }, + get destroyed () { + return socket.destroyed + }, + busy () { + return false + } + } +} + +function resumeH2 (client) { + const socket = client[kSocket] + + if (socket?.destroyed === false) { + if (client[kSize] === 0 || client[kMaxConcurrentStreams] === 0) { + socket.unref() + client[kHTTP2Session].unref() + } else { + socket.ref() + client[kHTTP2Session].ref() + } + } +} + +function onHttp2SessionError (err) { + assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') + + this[kSocket][kError] = err + this[kClient][kOnError](err) +} + +function onHttp2FrameError (type, code, id) { + if (id === 0) { + const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`) + this[kSocket][kError] = err + this[kClient][kOnError](err) + } +} + +function onHttp2SessionEnd () { + const err = new SocketError('other side closed', util.getSocketInfo(this[kSocket])) + this.destroy(err) + util.destroy(this[kSocket], err) +} + +/** + * This is the root cause of #3011 + * We need to handle GOAWAY frames properly, and trigger the session close + * along with the socket right away + * + * @this {import('http2').ClientHttp2Session} + * @param {number} errorCode + */ +function onHttp2SessionGoAway (errorCode) { + // TODO(mcollina): Verify if GOAWAY implements the spec correctly: + // https://datatracker.ietf.org/doc/html/rfc7540#section-6.8 + // Specifically, we do not verify the "valid" stream id. + + const err = this[kError] || new SocketError(`HTTP/2: "GOAWAY" frame received with code ${errorCode}`, util.getSocketInfo(this[kSocket])) + const client = this[kClient] + + client[kSocket] = null + client[kHTTPContext] = null + + // this is an HTTP2 session + this.close() + this[kHTTP2Session] = null + + util.destroy(this[kSocket], err) + + // Fail head of pipeline. + if (client[kRunningIdx] < client[kQueue].length) { + const request = client[kQueue][client[kRunningIdx]] + client[kQueue][client[kRunningIdx]++] = null + util.errorRequest(client, request, err) + client[kPendingIdx] = client[kRunningIdx] + } + + assert(client[kRunning] === 0) + + client.emit('disconnect', client[kUrl], [client], err) + client.emit('connectionError', client[kUrl], [client], err) + + client[kResume]() +} + +function onHttp2SessionClose () { + const { [kClient]: client } = this + const { [kSocket]: socket } = client + + const err = this[kSocket][kError] || this[kError] || new SocketError('closed', util.getSocketInfo(socket)) + + client[kSocket] = null + client[kHTTPContext] = null + + if (client.destroyed) { + assert(client[kPending] === 0) + + // Fail entire queue. + const requests = client[kQueue].splice(client[kRunningIdx]) + for (let i = 0; i < requests.length; i++) { + const request = requests[i] + util.errorRequest(client, request, err) + } + } +} + +function onHttp2SocketClose () { + const err = this[kError] || new SocketError('closed', util.getSocketInfo(this)) + + const client = this[kHTTP2Session][kClient] + + client[kSocket] = null + client[kHTTPContext] = null + + if (this[kHTTP2Session] !== null) { + this[kHTTP2Session].destroy(err) + } + + client[kPendingIdx] = client[kRunningIdx] + + assert(client[kRunning] === 0) + + client.emit('disconnect', client[kUrl], [client], err) + + client[kResume]() +} + +function onHttp2SocketError (err) { + assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') + + this[kError] = err + + this[kClient][kOnError](err) +} + +function onHttp2SocketEnd () { + util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this))) +} + +function onSocketClose () { + this[kClosed] = true +} + +// https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2 +function shouldSendContentLength (method) { + return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT' +} + +function writeH2 (client, request) { + const requestTimeout = request.bodyTimeout ?? client[kBodyTimeout] + const session = client[kHTTP2Session] + const { method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request + let { body } = request + + if (upgrade) { + util.errorRequest(client, request, new Error('Upgrade not supported for H2')) + return false + } + + const headers = {} + for (let n = 0; n < reqHeaders.length; n += 2) { + const key = reqHeaders[n + 0] + const val = reqHeaders[n + 1] + + if (Array.isArray(val)) { + for (let i = 0; i < val.length; i++) { + if (headers[key]) { + headers[key] += `, ${val[i]}` + } else { + headers[key] = val[i] + } + } + } else if (headers[key]) { + headers[key] += `, ${val}` + } else { + headers[key] = val + } + } + + /** @type {import('node:http2').ClientHttp2Stream} */ + let stream = null + + const { hostname, port } = client[kUrl] + + headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ''}` + headers[HTTP2_HEADER_METHOD] = method + + const abort = (err) => { + if (request.aborted || request.completed) { + return + } + + err = err || new RequestAbortedError() + + util.errorRequest(client, request, err) + + if (stream != null) { + // Some chunks might still come after abort, + // let's ignore them + stream.removeAllListeners('data') + + // On Abort, we close the stream to send RST_STREAM frame + stream.close() + + // We move the running index to the next request + client[kOnError](err) + client[kResume]() + } + + // We do not destroy the socket as we can continue using the session + // the stream gets destroyed and the session remains to create new streams + util.destroy(body, err) + } + + try { + // We are already connected, streams are pending. + // We can call on connect, and wait for abort + request.onConnect(abort) + } catch (err) { + util.errorRequest(client, request, err) + } + + if (request.aborted) { + return false + } + + if (method === 'CONNECT') { + session.ref() + // We are already connected, streams are pending, first request + // will create a new stream. We trigger a request to create the stream and wait until + // `ready` event is triggered + // We disabled endStream to allow the user to write to the stream + stream = session.request(headers, { endStream: false, signal }) + + if (!stream.pending) { + request.onUpgrade(null, null, stream) + ++session[kOpenStreams] + client[kQueue][client[kRunningIdx]++] = null + } else { + stream.once('ready', () => { + request.onUpgrade(null, null, stream) + ++session[kOpenStreams] + client[kQueue][client[kRunningIdx]++] = null + }) + } + + stream.once('close', () => { + session[kOpenStreams] -= 1 + if (session[kOpenStreams] === 0) session.unref() + }) + stream.setTimeout(requestTimeout) + + return true + } + + // https://tools.ietf.org/html/rfc7540#section-8.3 + // :path and :scheme headers must be omitted when sending CONNECT + + headers[HTTP2_HEADER_PATH] = path + headers[HTTP2_HEADER_SCHEME] = 'https' + + // https://tools.ietf.org/html/rfc7231#section-4.3.1 + // https://tools.ietf.org/html/rfc7231#section-4.3.2 + // https://tools.ietf.org/html/rfc7231#section-4.3.5 + + // Sending a payload body on a request that does not + // expect it can cause undefined behavior on some + // servers and corrupt connection state. Do not + // re-use the connection for further requests. + + const expectsPayload = ( + method === 'PUT' || + method === 'POST' || + method === 'PATCH' + ) + + if (body && typeof body.read === 'function') { + // Try to read EOF in order to get length. + body.read(0) + } + + let contentLength = util.bodyLength(body) + + if (util.isFormDataLike(body)) { + extractBody ??= require('../web/fetch/body.js').extractBody + + const [bodyStream, contentType] = extractBody(body) + headers['content-type'] = contentType + + body = bodyStream.stream + contentLength = bodyStream.length + } + + if (contentLength == null) { + contentLength = request.contentLength + } + + if (contentLength === 0 || !expectsPayload) { + // https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD NOT send a Content-Length header field when + // the request message does not contain a payload body and the method + // semantics do not anticipate such a body. + + contentLength = null + } + + // https://github.com/nodejs/undici/issues/2046 + // A user agent may send a Content-Length header with 0 value, this should be allowed. + if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength != null && request.contentLength !== contentLength) { + if (client[kStrictContentLength]) { + util.errorRequest(client, request, new RequestContentLengthMismatchError()) + return false + } + + process.emitWarning(new RequestContentLengthMismatchError()) + } + + if (contentLength != null) { + assert(body, 'no body must not have content length') + headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}` + } + + session.ref() + + if (channels.sendHeaders.hasSubscribers) { + let header = '' + for (const key in headers) { + header += `${key}: ${headers[key]}\r\n` + } + channels.sendHeaders.publish({ request, headers: header, socket: session[kSocket] }) + } + + // TODO(metcoder95): add support for sending trailers + const shouldEndStream = method === 'GET' || method === 'HEAD' || body === null + if (expectContinue) { + headers[HTTP2_HEADER_EXPECT] = '100-continue' + stream = session.request(headers, { endStream: shouldEndStream, signal }) + + stream.once('continue', writeBodyH2) + } else { + stream = session.request(headers, { + endStream: shouldEndStream, + signal + }) + + writeBodyH2() + } + + // Increment counter as we have new streams open + ++session[kOpenStreams] + stream.setTimeout(requestTimeout) + + stream.once('response', headers => { + const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers + request.onResponseStarted() + + // Due to the stream nature, it is possible we face a race condition + // where the stream has been assigned, but the request has been aborted + // the request remains in-flight and headers hasn't been received yet + // for those scenarios, best effort is to destroy the stream immediately + // as there's no value to keep it open. + if (request.aborted) { + stream.removeAllListeners('data') + return + } + + if (request.onHeaders(Number(statusCode), parseH2Headers(realHeaders), stream.resume.bind(stream), '') === false) { + stream.pause() + } + }) + + stream.on('data', (chunk) => { + if (request.onData(chunk) === false) { + stream.pause() + } + }) + + stream.once('end', (err) => { + stream.removeAllListeners('data') + // When state is null, it means we haven't consumed body and the stream still do not have + // a state. + // Present specially when using pipeline or stream + if (stream.state?.state == null || stream.state.state < 6) { + // Do not complete the request if it was aborted + // Not prone to happen for as safety net to avoid race conditions with 'trailers' + if (!request.aborted && !request.completed) { + request.onComplete({}) + } + + client[kQueue][client[kRunningIdx]++] = null + client[kResume]() + } else { + // Stream is closed or half-closed-remote (6), decrement counter and cleanup + // It does not have sense to continue working with the stream as we do not + // have yet RST_STREAM support on client-side + --session[kOpenStreams] + if (session[kOpenStreams] === 0) { + session.unref() + } + + abort(err ?? new InformationalError('HTTP/2: stream half-closed (remote)')) + client[kQueue][client[kRunningIdx]++] = null + client[kPendingIdx] = client[kRunningIdx] + client[kResume]() + } + }) + + stream.once('close', () => { + stream.removeAllListeners('data') + session[kOpenStreams] -= 1 + if (session[kOpenStreams] === 0) { + session.unref() + } + }) + + stream.once('error', function (err) { + stream.removeAllListeners('data') + abort(err) + }) + + stream.once('frameError', (type, code) => { + stream.removeAllListeners('data') + abort(new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`)) + }) + + stream.on('aborted', () => { + stream.removeAllListeners('data') + }) + + stream.on('timeout', () => { + const err = new InformationalError(`HTTP/2: "stream timeout after ${requestTimeout}"`) + stream.removeAllListeners('data') + session[kOpenStreams] -= 1 + + if (session[kOpenStreams] === 0) { + session.unref() + } + + abort(err) + }) + + stream.once('trailers', trailers => { + if (request.aborted || request.completed) { + return + } + + request.onComplete(trailers) + }) + + return true + + function writeBodyH2 () { + /* istanbul ignore else: assertion */ + if (!body || contentLength === 0) { + writeBuffer( + abort, + stream, + null, + client, + request, + client[kSocket], + contentLength, + expectsPayload + ) + } else if (util.isBuffer(body)) { + writeBuffer( + abort, + stream, + body, + client, + request, + client[kSocket], + contentLength, + expectsPayload + ) + } else if (util.isBlobLike(body)) { + if (typeof body.stream === 'function') { + writeIterable( + abort, + stream, + body.stream(), + client, + request, + client[kSocket], + contentLength, + expectsPayload + ) + } else { + writeBlob( + abort, + stream, + body, + client, + request, + client[kSocket], + contentLength, + expectsPayload + ) + } + } else if (util.isStream(body)) { + writeStream( + abort, + client[kSocket], + expectsPayload, + stream, + body, + client, + request, + contentLength + ) + } else if (util.isIterable(body)) { + writeIterable( + abort, + stream, + body, + client, + request, + client[kSocket], + contentLength, + expectsPayload + ) + } else { + assert(false) + } + } +} + +function writeBuffer (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) { + try { + if (body != null && util.isBuffer(body)) { + assert(contentLength === body.byteLength, 'buffer body must have content length') + h2stream.cork() + h2stream.write(body) + h2stream.uncork() + h2stream.end() + + request.onBodySent(body) + } + + if (!expectsPayload) { + socket[kReset] = true + } + + request.onRequestSent() + client[kResume]() + } catch (error) { + abort(error) + } +} + +function writeStream (abort, socket, expectsPayload, h2stream, body, client, request, contentLength) { + assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined') + + // For HTTP/2, is enough to pipe the stream + const pipe = pipeline( + body, + h2stream, + (err) => { + if (err) { + util.destroy(pipe, err) + abort(err) + } else { + util.removeAllListeners(pipe) + request.onRequestSent() + + if (!expectsPayload) { + socket[kReset] = true + } + + client[kResume]() + } + } + ) + + util.addListener(pipe, 'data', onPipeData) + + function onPipeData (chunk) { + request.onBodySent(chunk) + } +} + +async function writeBlob (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) { + assert(contentLength === body.size, 'blob body must have content length') + + try { + if (contentLength != null && contentLength !== body.size) { + throw new RequestContentLengthMismatchError() + } + + const buffer = Buffer.from(await body.arrayBuffer()) + + h2stream.cork() + h2stream.write(buffer) + h2stream.uncork() + h2stream.end() + + request.onBodySent(buffer) + request.onRequestSent() + + if (!expectsPayload) { + socket[kReset] = true + } + + client[kResume]() + } catch (err) { + abort(err) + } +} + +async function writeIterable (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) { + assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined') + + let callback = null + function onDrain () { + if (callback) { + const cb = callback + callback = null + cb() + } + } + + const waitForDrain = () => new Promise((resolve, reject) => { + assert(callback === null) + + if (socket[kError]) { + reject(socket[kError]) + } else { + callback = resolve + } + }) + + h2stream + .on('close', onDrain) + .on('drain', onDrain) + + try { + // It's up to the user to somehow abort the async iterable. + for await (const chunk of body) { + if (socket[kError]) { + throw socket[kError] + } + + const res = h2stream.write(chunk) + request.onBodySent(chunk) + if (!res) { + await waitForDrain() + } + } + + h2stream.end() + + request.onRequestSent() + + if (!expectsPayload) { + socket[kReset] = true + } + + client[kResume]() + } catch (err) { + abort(err) + } finally { + h2stream + .off('close', onDrain) + .off('drain', onDrain) + } +} + +module.exports = connectH2 diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/client.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/client.js new file mode 100644 index 0000000000000000000000000000000000000000..0b0990206e715841bd0ec52f03225c9d3c92dfa8 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/client.js @@ -0,0 +1,614 @@ +'use strict' + +const assert = require('node:assert') +const net = require('node:net') +const http = require('node:http') +const util = require('../core/util.js') +const { ClientStats } = require('../util/stats.js') +const { channels } = require('../core/diagnostics.js') +const Request = require('../core/request.js') +const DispatcherBase = require('./dispatcher-base') +const { + InvalidArgumentError, + InformationalError, + ClientDestroyedError +} = require('../core/errors.js') +const buildConnector = require('../core/connect.js') +const { + kUrl, + kServerName, + kClient, + kBusy, + kConnect, + kResuming, + kRunning, + kPending, + kSize, + kQueue, + kConnected, + kConnecting, + kNeedDrain, + kKeepAliveDefaultTimeout, + kHostHeader, + kPendingIdx, + kRunningIdx, + kError, + kPipelining, + kKeepAliveTimeoutValue, + kMaxHeadersSize, + kKeepAliveMaxTimeout, + kKeepAliveTimeoutThreshold, + kHeadersTimeout, + kBodyTimeout, + kStrictContentLength, + kConnector, + kMaxRequests, + kCounter, + kClose, + kDestroy, + kDispatch, + kLocalAddress, + kMaxResponseSize, + kOnError, + kHTTPContext, + kMaxConcurrentStreams, + kResume +} = require('../core/symbols.js') +const connectH1 = require('./client-h1.js') +const connectH2 = require('./client-h2.js') + +const kClosedResolve = Symbol('kClosedResolve') + +const getDefaultNodeMaxHeaderSize = http && + http.maxHeaderSize && + Number.isInteger(http.maxHeaderSize) && + http.maxHeaderSize > 0 + ? () => http.maxHeaderSize + : () => { throw new InvalidArgumentError('http module not available or http.maxHeaderSize invalid') } + +const noop = () => {} + +function getPipelining (client) { + return client[kPipelining] ?? client[kHTTPContext]?.defaultPipelining ?? 1 +} + +/** + * @type {import('../../types/client.js').default} + */ +class Client extends DispatcherBase { + /** + * + * @param {string|URL} url + * @param {import('../../types/client.js').Client.Options} options + */ + constructor (url, { + maxHeaderSize, + headersTimeout, + socketTimeout, + requestTimeout, + connectTimeout, + bodyTimeout, + idleTimeout, + keepAlive, + keepAliveTimeout, + maxKeepAliveTimeout, + keepAliveMaxTimeout, + keepAliveTimeoutThreshold, + socketPath, + pipelining, + tls, + strictContentLength, + maxCachedSessions, + connect, + maxRequestsPerClient, + localAddress, + maxResponseSize, + autoSelectFamily, + autoSelectFamilyAttemptTimeout, + // h2 + maxConcurrentStreams, + allowH2 + } = {}) { + if (keepAlive !== undefined) { + throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead') + } + + if (socketTimeout !== undefined) { + throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead') + } + + if (requestTimeout !== undefined) { + throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead') + } + + if (idleTimeout !== undefined) { + throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead') + } + + if (maxKeepAliveTimeout !== undefined) { + throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead') + } + + if (maxHeaderSize != null) { + if (!Number.isInteger(maxHeaderSize) || maxHeaderSize < 1) { + throw new InvalidArgumentError('invalid maxHeaderSize') + } + } else { + // If maxHeaderSize is not provided, use the default value from the http module + // or if that is not available, throw an error. + maxHeaderSize = getDefaultNodeMaxHeaderSize() + } + + if (socketPath != null && typeof socketPath !== 'string') { + throw new InvalidArgumentError('invalid socketPath') + } + + if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) { + throw new InvalidArgumentError('invalid connectTimeout') + } + + if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) { + throw new InvalidArgumentError('invalid keepAliveTimeout') + } + + if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) { + throw new InvalidArgumentError('invalid keepAliveMaxTimeout') + } + + if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) { + throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold') + } + + if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) { + throw new InvalidArgumentError('headersTimeout must be a positive integer or zero') + } + + if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) { + throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero') + } + + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') + } + + if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) { + throw new InvalidArgumentError('maxRequestsPerClient must be a positive number') + } + + if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) { + throw new InvalidArgumentError('localAddress must be valid string IP address') + } + + if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) { + throw new InvalidArgumentError('maxResponseSize must be a positive number') + } + + if ( + autoSelectFamilyAttemptTimeout != null && + (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1) + ) { + throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number') + } + + // h2 + if (allowH2 != null && typeof allowH2 !== 'boolean') { + throw new InvalidArgumentError('allowH2 must be a valid boolean value') + } + + if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) { + throw new InvalidArgumentError('maxConcurrentStreams must be a positive integer, greater than 0') + } + + super() + + if (typeof connect !== 'function') { + connect = buildConnector({ + ...tls, + maxCachedSessions, + allowH2, + socketPath, + timeout: connectTimeout, + ...(typeof autoSelectFamily === 'boolean' ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), + ...connect + }) + } + + this[kUrl] = util.parseOrigin(url) + this[kConnector] = connect + this[kPipelining] = pipelining != null ? pipelining : 1 + this[kMaxHeadersSize] = maxHeaderSize + this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout + this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout + this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 2e3 : keepAliveTimeoutThreshold + this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout] + this[kServerName] = null + this[kLocalAddress] = localAddress != null ? localAddress : null + this[kResuming] = 0 // 0, idle, 1, scheduled, 2 resuming + this[kNeedDrain] = 0 // 0, idle, 1, scheduled, 2 resuming + this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}\r\n` + this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 300e3 + this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 300e3 + this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength + this[kMaxRequests] = maxRequestsPerClient + this[kClosedResolve] = null + this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1 + this[kMaxConcurrentStreams] = maxConcurrentStreams != null ? maxConcurrentStreams : 100 // Max peerConcurrentStreams for a Node h2 server + this[kHTTPContext] = null + + // kQueue is built up of 3 sections separated by + // the kRunningIdx and kPendingIdx indices. + // | complete | running | pending | + // ^ kRunningIdx ^ kPendingIdx ^ kQueue.length + // kRunningIdx points to the first running element. + // kPendingIdx points to the first pending element. + // This implements a fast queue with an amortized + // time of O(1). + + this[kQueue] = [] + this[kRunningIdx] = 0 + this[kPendingIdx] = 0 + + this[kResume] = (sync) => resume(this, sync) + this[kOnError] = (err) => onError(this, err) + } + + get pipelining () { + return this[kPipelining] + } + + set pipelining (value) { + this[kPipelining] = value + this[kResume](true) + } + + get stats () { + return new ClientStats(this) + } + + get [kPending] () { + return this[kQueue].length - this[kPendingIdx] + } + + get [kRunning] () { + return this[kPendingIdx] - this[kRunningIdx] + } + + get [kSize] () { + return this[kQueue].length - this[kRunningIdx] + } + + get [kConnected] () { + return !!this[kHTTPContext] && !this[kConnecting] && !this[kHTTPContext].destroyed + } + + get [kBusy] () { + return Boolean( + this[kHTTPContext]?.busy(null) || + (this[kSize] >= (getPipelining(this) || 1)) || + this[kPending] > 0 + ) + } + + /* istanbul ignore: only used for test */ + [kConnect] (cb) { + connect(this) + this.once('connect', cb) + } + + [kDispatch] (opts, handler) { + const origin = opts.origin || this[kUrl].origin + const request = new Request(origin, opts, handler) + + this[kQueue].push(request) + if (this[kResuming]) { + // Do nothing. + } else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) { + // Wait a tick in case stream/iterator is ended in the same tick. + this[kResuming] = 1 + queueMicrotask(() => resume(this)) + } else { + this[kResume](true) + } + + if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) { + this[kNeedDrain] = 2 + } + + return this[kNeedDrain] < 2 + } + + async [kClose] () { + // TODO: for H2 we need to gracefully flush the remaining enqueued + // request and close each stream. + return new Promise((resolve) => { + if (this[kSize]) { + this[kClosedResolve] = resolve + } else { + resolve(null) + } + }) + } + + async [kDestroy] (err) { + return new Promise((resolve) => { + const requests = this[kQueue].splice(this[kPendingIdx]) + for (let i = 0; i < requests.length; i++) { + const request = requests[i] + util.errorRequest(this, request, err) + } + + const callback = () => { + if (this[kClosedResolve]) { + // TODO (fix): Should we error here with ClientDestroyedError? + this[kClosedResolve]() + this[kClosedResolve] = null + } + resolve(null) + } + + if (this[kHTTPContext]) { + this[kHTTPContext].destroy(err, callback) + this[kHTTPContext] = null + } else { + queueMicrotask(callback) + } + + this[kResume]() + }) + } +} + +function onError (client, err) { + if ( + client[kRunning] === 0 && + err.code !== 'UND_ERR_INFO' && + err.code !== 'UND_ERR_SOCKET' + ) { + // Error is not caused by running request and not a recoverable + // socket error. + + assert(client[kPendingIdx] === client[kRunningIdx]) + + const requests = client[kQueue].splice(client[kRunningIdx]) + + for (let i = 0; i < requests.length; i++) { + const request = requests[i] + util.errorRequest(client, request, err) + } + assert(client[kSize] === 0) + } +} + +/** + * @param {Client} client + * @returns + */ +async function connect (client) { + assert(!client[kConnecting]) + assert(!client[kHTTPContext]) + + let { host, hostname, protocol, port } = client[kUrl] + + // Resolve ipv6 + if (hostname[0] === '[') { + const idx = hostname.indexOf(']') + + assert(idx !== -1) + const ip = hostname.substring(1, idx) + + assert(net.isIPv6(ip)) + hostname = ip + } + + client[kConnecting] = true + + if (channels.beforeConnect.hasSubscribers) { + channels.beforeConnect.publish({ + connectParams: { + host, + hostname, + protocol, + port, + version: client[kHTTPContext]?.version, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector] + }) + } + + try { + const socket = await new Promise((resolve, reject) => { + client[kConnector]({ + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, (err, socket) => { + if (err) { + reject(err) + } else { + resolve(socket) + } + }) + }) + + if (client.destroyed) { + util.destroy(socket.on('error', noop), new ClientDestroyedError()) + return + } + + assert(socket) + + try { + client[kHTTPContext] = socket.alpnProtocol === 'h2' + ? await connectH2(client, socket) + : await connectH1(client, socket) + } catch (err) { + socket.destroy().on('error', noop) + throw err + } + + client[kConnecting] = false + + socket[kCounter] = 0 + socket[kMaxRequests] = client[kMaxRequests] + socket[kClient] = client + socket[kError] = null + + if (channels.connected.hasSubscribers) { + channels.connected.publish({ + connectParams: { + host, + hostname, + protocol, + port, + version: client[kHTTPContext]?.version, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector], + socket + }) + } + client.emit('connect', client[kUrl], [client]) + } catch (err) { + if (client.destroyed) { + return + } + + client[kConnecting] = false + + if (channels.connectError.hasSubscribers) { + channels.connectError.publish({ + connectParams: { + host, + hostname, + protocol, + port, + version: client[kHTTPContext]?.version, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector], + error: err + }) + } + + if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') { + assert(client[kRunning] === 0) + while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) { + const request = client[kQueue][client[kPendingIdx]++] + util.errorRequest(client, request, err) + } + } else { + onError(client, err) + } + + client.emit('connectionError', client[kUrl], [client], err) + } + + client[kResume]() +} + +function emitDrain (client) { + client[kNeedDrain] = 0 + client.emit('drain', client[kUrl], [client]) +} + +function resume (client, sync) { + if (client[kResuming] === 2) { + return + } + + client[kResuming] = 2 + + _resume(client, sync) + client[kResuming] = 0 + + if (client[kRunningIdx] > 256) { + client[kQueue].splice(0, client[kRunningIdx]) + client[kPendingIdx] -= client[kRunningIdx] + client[kRunningIdx] = 0 + } +} + +function _resume (client, sync) { + while (true) { + if (client.destroyed) { + assert(client[kPending] === 0) + return + } + + if (client[kClosedResolve] && !client[kSize]) { + client[kClosedResolve]() + client[kClosedResolve] = null + return + } + + if (client[kHTTPContext]) { + client[kHTTPContext].resume() + } + + if (client[kBusy]) { + client[kNeedDrain] = 2 + } else if (client[kNeedDrain] === 2) { + if (sync) { + client[kNeedDrain] = 1 + queueMicrotask(() => emitDrain(client)) + } else { + emitDrain(client) + } + continue + } + + if (client[kPending] === 0) { + return + } + + if (client[kRunning] >= (getPipelining(client) || 1)) { + return + } + + const request = client[kQueue][client[kPendingIdx]] + + if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) { + if (client[kRunning] > 0) { + return + } + + client[kServerName] = request.servername + client[kHTTPContext]?.destroy(new InformationalError('servername changed'), () => { + client[kHTTPContext] = null + resume(client) + }) + } + + if (client[kConnecting]) { + return + } + + if (!client[kHTTPContext]) { + connect(client) + return + } + + if (client[kHTTPContext].destroyed) { + return + } + + if (client[kHTTPContext].busy(request)) { + return + } + + if (!request.aborted && client[kHTTPContext].write(request)) { + client[kPendingIdx]++ + } else { + client[kQueue].splice(client[kPendingIdx], 1) + } + } +} + +module.exports = Client diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/dispatcher-base.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/dispatcher-base.js new file mode 100644 index 0000000000000000000000000000000000000000..615754d0fb54a80cde347184b2c76cafd1f5ad5d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/dispatcher-base.js @@ -0,0 +1,161 @@ +'use strict' + +const Dispatcher = require('./dispatcher') +const UnwrapHandler = require('../handler/unwrap-handler') +const { + ClientDestroyedError, + ClientClosedError, + InvalidArgumentError +} = require('../core/errors') +const { kDestroy, kClose, kClosed, kDestroyed, kDispatch } = require('../core/symbols') + +const kOnDestroyed = Symbol('onDestroyed') +const kOnClosed = Symbol('onClosed') + +class DispatcherBase extends Dispatcher { + constructor () { + super() + + this[kDestroyed] = false + this[kOnDestroyed] = null + this[kClosed] = false + this[kOnClosed] = [] + } + + get destroyed () { + return this[kDestroyed] + } + + get closed () { + return this[kClosed] + } + + close (callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + this.close((err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + if (this[kDestroyed]) { + queueMicrotask(() => callback(new ClientDestroyedError(), null)) + return + } + + if (this[kClosed]) { + if (this[kOnClosed]) { + this[kOnClosed].push(callback) + } else { + queueMicrotask(() => callback(null, null)) + } + return + } + + this[kClosed] = true + this[kOnClosed].push(callback) + + const onClosed = () => { + const callbacks = this[kOnClosed] + this[kOnClosed] = null + for (let i = 0; i < callbacks.length; i++) { + callbacks[i](null, null) + } + } + + // Should not error. + this[kClose]() + .then(() => this.destroy()) + .then(() => { + queueMicrotask(onClosed) + }) + } + + destroy (err, callback) { + if (typeof err === 'function') { + callback = err + err = null + } + + if (callback === undefined) { + return new Promise((resolve, reject) => { + this.destroy(err, (err, data) => { + return err ? /* istanbul ignore next: should never error */ reject(err) : resolve(data) + }) + }) + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + if (this[kDestroyed]) { + if (this[kOnDestroyed]) { + this[kOnDestroyed].push(callback) + } else { + queueMicrotask(() => callback(null, null)) + } + return + } + + if (!err) { + err = new ClientDestroyedError() + } + + this[kDestroyed] = true + this[kOnDestroyed] = this[kOnDestroyed] || [] + this[kOnDestroyed].push(callback) + + const onDestroyed = () => { + const callbacks = this[kOnDestroyed] + this[kOnDestroyed] = null + for (let i = 0; i < callbacks.length; i++) { + callbacks[i](null, null) + } + } + + // Should not error. + this[kDestroy](err).then(() => { + queueMicrotask(onDestroyed) + }) + } + + dispatch (opts, handler) { + if (!handler || typeof handler !== 'object') { + throw new InvalidArgumentError('handler must be an object') + } + + handler = UnwrapHandler.unwrap(handler) + + try { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('opts must be an object.') + } + + if (this[kDestroyed] || this[kOnDestroyed]) { + throw new ClientDestroyedError() + } + + if (this[kClosed]) { + throw new ClientClosedError() + } + + return this[kDispatch](opts, handler) + } catch (err) { + if (typeof handler.onError !== 'function') { + throw err + } + + handler.onError(err) + + return false + } + } +} + +module.exports = DispatcherBase diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/dispatcher.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/dispatcher.js new file mode 100644 index 0000000000000000000000000000000000000000..824dfb6d82204f517cf7cd01cdb939566fa30404 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/dispatcher.js @@ -0,0 +1,48 @@ +'use strict' +const EventEmitter = require('node:events') +const WrapHandler = require('../handler/wrap-handler') + +const wrapInterceptor = (dispatch) => (opts, handler) => dispatch(opts, WrapHandler.wrap(handler)) + +class Dispatcher extends EventEmitter { + dispatch () { + throw new Error('not implemented') + } + + close () { + throw new Error('not implemented') + } + + destroy () { + throw new Error('not implemented') + } + + compose (...args) { + // So we handle [interceptor1, interceptor2] or interceptor1, interceptor2, ... + const interceptors = Array.isArray(args[0]) ? args[0] : args + let dispatch = this.dispatch.bind(this) + + for (const interceptor of interceptors) { + if (interceptor == null) { + continue + } + + if (typeof interceptor !== 'function') { + throw new TypeError(`invalid interceptor, expected function received ${typeof interceptor}`) + } + + dispatch = interceptor(dispatch) + dispatch = wrapInterceptor(dispatch) + + if (dispatch == null || typeof dispatch !== 'function' || dispatch.length !== 2) { + throw new TypeError('invalid interceptor') + } + } + + return new Proxy(this, { + get: (target, key) => key === 'dispatch' ? dispatch : target[key] + }) + } +} + +module.exports = Dispatcher diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/env-http-proxy-agent.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/env-http-proxy-agent.js new file mode 100644 index 0000000000000000000000000000000000000000..48cc3f88e7f0ae54db611b226da2fce29adaa102 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/env-http-proxy-agent.js @@ -0,0 +1,151 @@ +'use strict' + +const DispatcherBase = require('./dispatcher-base') +const { kClose, kDestroy, kClosed, kDestroyed, kDispatch, kNoProxyAgent, kHttpProxyAgent, kHttpsProxyAgent } = require('../core/symbols') +const ProxyAgent = require('./proxy-agent') +const Agent = require('./agent') + +const DEFAULT_PORTS = { + 'http:': 80, + 'https:': 443 +} + +class EnvHttpProxyAgent extends DispatcherBase { + #noProxyValue = null + #noProxyEntries = null + #opts = null + + constructor (opts = {}) { + super() + this.#opts = opts + + const { httpProxy, httpsProxy, noProxy, ...agentOpts } = opts + + this[kNoProxyAgent] = new Agent(agentOpts) + + const HTTP_PROXY = httpProxy ?? process.env.http_proxy ?? process.env.HTTP_PROXY + if (HTTP_PROXY) { + this[kHttpProxyAgent] = new ProxyAgent({ ...agentOpts, uri: HTTP_PROXY }) + } else { + this[kHttpProxyAgent] = this[kNoProxyAgent] + } + + const HTTPS_PROXY = httpsProxy ?? process.env.https_proxy ?? process.env.HTTPS_PROXY + if (HTTPS_PROXY) { + this[kHttpsProxyAgent] = new ProxyAgent({ ...agentOpts, uri: HTTPS_PROXY }) + } else { + this[kHttpsProxyAgent] = this[kHttpProxyAgent] + } + + this.#parseNoProxy() + } + + [kDispatch] (opts, handler) { + const url = new URL(opts.origin) + const agent = this.#getProxyAgentForUrl(url) + return agent.dispatch(opts, handler) + } + + async [kClose] () { + await this[kNoProxyAgent].close() + if (!this[kHttpProxyAgent][kClosed]) { + await this[kHttpProxyAgent].close() + } + if (!this[kHttpsProxyAgent][kClosed]) { + await this[kHttpsProxyAgent].close() + } + } + + async [kDestroy] (err) { + await this[kNoProxyAgent].destroy(err) + if (!this[kHttpProxyAgent][kDestroyed]) { + await this[kHttpProxyAgent].destroy(err) + } + if (!this[kHttpsProxyAgent][kDestroyed]) { + await this[kHttpsProxyAgent].destroy(err) + } + } + + #getProxyAgentForUrl (url) { + let { protocol, host: hostname, port } = url + + // Stripping ports in this way instead of using parsedUrl.hostname to make + // sure that the brackets around IPv6 addresses are kept. + hostname = hostname.replace(/:\d*$/, '').toLowerCase() + port = Number.parseInt(port, 10) || DEFAULT_PORTS[protocol] || 0 + if (!this.#shouldProxy(hostname, port)) { + return this[kNoProxyAgent] + } + if (protocol === 'https:') { + return this[kHttpsProxyAgent] + } + return this[kHttpProxyAgent] + } + + #shouldProxy (hostname, port) { + if (this.#noProxyChanged) { + this.#parseNoProxy() + } + + if (this.#noProxyEntries.length === 0) { + return true // Always proxy if NO_PROXY is not set or empty. + } + if (this.#noProxyValue === '*') { + return false // Never proxy if wildcard is set. + } + + for (let i = 0; i < this.#noProxyEntries.length; i++) { + const entry = this.#noProxyEntries[i] + if (entry.port && entry.port !== port) { + continue // Skip if ports don't match. + } + if (!/^[.*]/.test(entry.hostname)) { + // No wildcards, so don't proxy only if there is not an exact match. + if (hostname === entry.hostname) { + return false + } + } else { + // Don't proxy if the hostname ends with the no_proxy host. + if (hostname.endsWith(entry.hostname.replace(/^\*/, ''))) { + return false + } + } + } + + return true + } + + #parseNoProxy () { + const noProxyValue = this.#opts.noProxy ?? this.#noProxyEnv + const noProxySplit = noProxyValue.split(/[,\s]/) + const noProxyEntries = [] + + for (let i = 0; i < noProxySplit.length; i++) { + const entry = noProxySplit[i] + if (!entry) { + continue + } + const parsed = entry.match(/^(.+):(\d+)$/) + noProxyEntries.push({ + hostname: (parsed ? parsed[1] : entry).toLowerCase(), + port: parsed ? Number.parseInt(parsed[2], 10) : 0 + }) + } + + this.#noProxyValue = noProxyValue + this.#noProxyEntries = noProxyEntries + } + + get #noProxyChanged () { + if (this.#opts.noProxy !== undefined) { + return false + } + return this.#noProxyValue !== this.#noProxyEnv + } + + get #noProxyEnv () { + return process.env.no_proxy ?? process.env.NO_PROXY ?? '' + } +} + +module.exports = EnvHttpProxyAgent diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/fixed-queue.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/fixed-queue.js new file mode 100644 index 0000000000000000000000000000000000000000..5f7a08bc47ffd99c20db933c11d5bf8a28402bff --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/fixed-queue.js @@ -0,0 +1,159 @@ +'use strict' + +// Extracted from node/lib/internal/fixed_queue.js + +// Currently optimal queue size, tested on V8 6.0 - 6.6. Must be power of two. +const kSize = 2048 +const kMask = kSize - 1 + +// The FixedQueue is implemented as a singly-linked list of fixed-size +// circular buffers. It looks something like this: +// +// head tail +// | | +// v v +// +-----------+ <-----\ +-----------+ <------\ +-----------+ +// | [null] | \----- | next | \------- | next | +// +-----------+ +-----------+ +-----------+ +// | item | <-- bottom | item | <-- bottom | undefined | +// | item | | item | | undefined | +// | item | | item | | undefined | +// | item | | item | | undefined | +// | item | | item | bottom --> | item | +// | item | | item | | item | +// | ... | | ... | | ... | +// | item | | item | | item | +// | item | | item | | item | +// | undefined | <-- top | item | | item | +// | undefined | | item | | item | +// | undefined | | undefined | <-- top top --> | undefined | +// +-----------+ +-----------+ +-----------+ +// +// Or, if there is only one circular buffer, it looks something +// like either of these: +// +// head tail head tail +// | | | | +// v v v v +// +-----------+ +-----------+ +// | [null] | | [null] | +// +-----------+ +-----------+ +// | undefined | | item | +// | undefined | | item | +// | item | <-- bottom top --> | undefined | +// | item | | undefined | +// | undefined | <-- top bottom --> | item | +// | undefined | | item | +// +-----------+ +-----------+ +// +// Adding a value means moving `top` forward by one, removing means +// moving `bottom` forward by one. After reaching the end, the queue +// wraps around. +// +// When `top === bottom` the current queue is empty and when +// `top + 1 === bottom` it's full. This wastes a single space of storage +// but allows much quicker checks. + +/** + * @type {FixedCircularBuffer} + * @template T + */ +class FixedCircularBuffer { + constructor () { + /** + * @type {number} + */ + this.bottom = 0 + /** + * @type {number} + */ + this.top = 0 + /** + * @type {Array} + */ + this.list = new Array(kSize).fill(undefined) + /** + * @type {T|null} + */ + this.next = null + } + + /** + * @returns {boolean} + */ + isEmpty () { + return this.top === this.bottom + } + + /** + * @returns {boolean} + */ + isFull () { + return ((this.top + 1) & kMask) === this.bottom + } + + /** + * @param {T} data + * @returns {void} + */ + push (data) { + this.list[this.top] = data + this.top = (this.top + 1) & kMask + } + + /** + * @returns {T|null} + */ + shift () { + const nextItem = this.list[this.bottom] + if (nextItem === undefined) { return null } + this.list[this.bottom] = undefined + this.bottom = (this.bottom + 1) & kMask + return nextItem + } +} + +/** + * @template T + */ +module.exports = class FixedQueue { + constructor () { + /** + * @type {FixedCircularBuffer} + */ + this.head = this.tail = new FixedCircularBuffer() + } + + /** + * @returns {boolean} + */ + isEmpty () { + return this.head.isEmpty() + } + + /** + * @param {T} data + */ + push (data) { + if (this.head.isFull()) { + // Head is full: Creates a new queue, sets the old queue's `.next` to it, + // and sets it as the new main queue. + this.head = this.head.next = new FixedCircularBuffer() + } + this.head.push(data) + } + + /** + * @returns {T|null} + */ + shift () { + const tail = this.tail + const next = tail.shift() + if (tail.isEmpty() && tail.next !== null) { + // If there is another queue, it forms the new tail. + this.tail = tail.next + tail.next = null + } + return next + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/h2c-client.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/h2c-client.js new file mode 100644 index 0000000000000000000000000000000000000000..3a876fd4553cc7e3979f92cc05d458112e251b9b --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/h2c-client.js @@ -0,0 +1,122 @@ +'use strict' +const { connect } = require('node:net') + +const { kClose, kDestroy } = require('../core/symbols') +const { InvalidArgumentError } = require('../core/errors') +const util = require('../core/util') + +const Client = require('./client') +const DispatcherBase = require('./dispatcher-base') + +class H2CClient extends DispatcherBase { + #client = null + + constructor (origin, clientOpts) { + super() + + if (typeof origin === 'string') { + origin = new URL(origin) + } + + if (origin.protocol !== 'http:') { + throw new InvalidArgumentError( + 'h2c-client: Only h2c protocol is supported' + ) + } + + const { connect, maxConcurrentStreams, pipelining, ...opts } = + clientOpts ?? {} + let defaultMaxConcurrentStreams = 100 + let defaultPipelining = 100 + + if ( + maxConcurrentStreams != null && + Number.isInteger(maxConcurrentStreams) && + maxConcurrentStreams > 0 + ) { + defaultMaxConcurrentStreams = maxConcurrentStreams + } + + if (pipelining != null && Number.isInteger(pipelining) && pipelining > 0) { + defaultPipelining = pipelining + } + + if (defaultPipelining > defaultMaxConcurrentStreams) { + throw new InvalidArgumentError( + 'h2c-client: pipelining cannot be greater than maxConcurrentStreams' + ) + } + + this.#client = new Client(origin, { + ...opts, + connect: this.#buildConnector(connect), + maxConcurrentStreams: defaultMaxConcurrentStreams, + pipelining: defaultPipelining, + allowH2: true + }) + } + + #buildConnector (connectOpts) { + return (opts, callback) => { + const timeout = connectOpts?.connectOpts ?? 10e3 + const { hostname, port, pathname } = opts + const socket = connect({ + ...opts, + host: hostname, + port, + pathname + }) + + // Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket + if (opts.keepAlive == null || opts.keepAlive) { + const keepAliveInitialDelay = + opts.keepAliveInitialDelay == null ? 60e3 : opts.keepAliveInitialDelay + socket.setKeepAlive(true, keepAliveInitialDelay) + } + + socket.alpnProtocol = 'h2' + + const clearConnectTimeout = util.setupConnectTimeout( + new WeakRef(socket), + { timeout, hostname, port } + ) + + socket + .setNoDelay(true) + .once('connect', function () { + queueMicrotask(clearConnectTimeout) + + if (callback) { + const cb = callback + callback = null + cb(null, this) + } + }) + .on('error', function (err) { + queueMicrotask(clearConnectTimeout) + + if (callback) { + const cb = callback + callback = null + cb(err) + } + }) + + return socket + } + } + + dispatch (opts, handler) { + return this.#client.dispatch(opts, handler) + } + + async [kClose] () { + await this.#client.close() + } + + async [kDestroy] () { + await this.#client.destroy() + } +} + +module.exports = H2CClient diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/pool-base.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/pool-base.js new file mode 100644 index 0000000000000000000000000000000000000000..4b7b6a26f1d9462ee771bc09adeb8f95bb251ba1 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/pool-base.js @@ -0,0 +1,191 @@ +'use strict' + +const { PoolStats } = require('../util/stats.js') +const DispatcherBase = require('./dispatcher-base') +const FixedQueue = require('./fixed-queue') +const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = require('../core/symbols') + +const kClients = Symbol('clients') +const kNeedDrain = Symbol('needDrain') +const kQueue = Symbol('queue') +const kClosedResolve = Symbol('closed resolve') +const kOnDrain = Symbol('onDrain') +const kOnConnect = Symbol('onConnect') +const kOnDisconnect = Symbol('onDisconnect') +const kOnConnectionError = Symbol('onConnectionError') +const kGetDispatcher = Symbol('get dispatcher') +const kAddClient = Symbol('add client') +const kRemoveClient = Symbol('remove client') + +class PoolBase extends DispatcherBase { + constructor () { + super() + + this[kQueue] = new FixedQueue() + this[kClients] = [] + this[kQueued] = 0 + + const pool = this + + this[kOnDrain] = function onDrain (origin, targets) { + const queue = pool[kQueue] + + let needDrain = false + + while (!needDrain) { + const item = queue.shift() + if (!item) { + break + } + pool[kQueued]-- + needDrain = !this.dispatch(item.opts, item.handler) + } + + this[kNeedDrain] = needDrain + + if (!this[kNeedDrain] && pool[kNeedDrain]) { + pool[kNeedDrain] = false + pool.emit('drain', origin, [pool, ...targets]) + } + + if (pool[kClosedResolve] && queue.isEmpty()) { + Promise + .all(pool[kClients].map(c => c.close())) + .then(pool[kClosedResolve]) + } + } + + this[kOnConnect] = (origin, targets) => { + pool.emit('connect', origin, [pool, ...targets]) + } + + this[kOnDisconnect] = (origin, targets, err) => { + pool.emit('disconnect', origin, [pool, ...targets], err) + } + + this[kOnConnectionError] = (origin, targets, err) => { + pool.emit('connectionError', origin, [pool, ...targets], err) + } + } + + get [kBusy] () { + return this[kNeedDrain] + } + + get [kConnected] () { + return this[kClients].filter(client => client[kConnected]).length + } + + get [kFree] () { + return this[kClients].filter(client => client[kConnected] && !client[kNeedDrain]).length + } + + get [kPending] () { + let ret = this[kQueued] + for (const { [kPending]: pending } of this[kClients]) { + ret += pending + } + return ret + } + + get [kRunning] () { + let ret = 0 + for (const { [kRunning]: running } of this[kClients]) { + ret += running + } + return ret + } + + get [kSize] () { + let ret = this[kQueued] + for (const { [kSize]: size } of this[kClients]) { + ret += size + } + return ret + } + + get stats () { + return new PoolStats(this) + } + + async [kClose] () { + if (this[kQueue].isEmpty()) { + await Promise.all(this[kClients].map(c => c.close())) + } else { + await new Promise((resolve) => { + this[kClosedResolve] = resolve + }) + } + } + + async [kDestroy] (err) { + while (true) { + const item = this[kQueue].shift() + if (!item) { + break + } + item.handler.onError(err) + } + + await Promise.all(this[kClients].map(c => c.destroy(err))) + } + + [kDispatch] (opts, handler) { + const dispatcher = this[kGetDispatcher]() + + if (!dispatcher) { + this[kNeedDrain] = true + this[kQueue].push({ opts, handler }) + this[kQueued]++ + } else if (!dispatcher.dispatch(opts, handler)) { + dispatcher[kNeedDrain] = true + this[kNeedDrain] = !this[kGetDispatcher]() + } + + return !this[kNeedDrain] + } + + [kAddClient] (client) { + client + .on('drain', this[kOnDrain]) + .on('connect', this[kOnConnect]) + .on('disconnect', this[kOnDisconnect]) + .on('connectionError', this[kOnConnectionError]) + + this[kClients].push(client) + + if (this[kNeedDrain]) { + queueMicrotask(() => { + if (this[kNeedDrain]) { + this[kOnDrain](client[kUrl], [this, client]) + } + }) + } + + return this + } + + [kRemoveClient] (client) { + client.close(() => { + const idx = this[kClients].indexOf(client) + if (idx !== -1) { + this[kClients].splice(idx, 1) + } + }) + + this[kNeedDrain] = this[kClients].some(dispatcher => ( + !dispatcher[kNeedDrain] && + dispatcher.closed !== true && + dispatcher.destroyed !== true + )) + } +} + +module.exports = { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kRemoveClient, + kGetDispatcher +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/pool.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/pool.js new file mode 100644 index 0000000000000000000000000000000000000000..00cf50c3012b2977fff455f1f66adf3d2a83ea24 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/pool.js @@ -0,0 +1,118 @@ +'use strict' + +const { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kGetDispatcher, + kRemoveClient +} = require('./pool-base') +const Client = require('./client') +const { + InvalidArgumentError +} = require('../core/errors') +const util = require('../core/util') +const { kUrl } = require('../core/symbols') +const buildConnector = require('../core/connect') + +const kOptions = Symbol('options') +const kConnections = Symbol('connections') +const kFactory = Symbol('factory') + +function defaultFactory (origin, opts) { + return new Client(origin, opts) +} + +class Pool extends PoolBase { + constructor (origin, { + connections, + factory = defaultFactory, + connect, + connectTimeout, + tls, + maxCachedSessions, + socketPath, + autoSelectFamily, + autoSelectFamilyAttemptTimeout, + allowH2, + clientTtl, + ...options + } = {}) { + if (connections != null && (!Number.isFinite(connections) || connections < 0)) { + throw new InvalidArgumentError('invalid connections') + } + + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') + } + + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') + } + + super() + + if (typeof connect !== 'function') { + connect = buildConnector({ + ...tls, + maxCachedSessions, + allowH2, + socketPath, + timeout: connectTimeout, + ...(typeof autoSelectFamily === 'boolean' ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), + ...connect + }) + } + + this[kConnections] = connections || null + this[kUrl] = util.parseOrigin(origin) + this[kOptions] = { ...util.deepClone(options), connect, allowH2, clientTtl } + this[kOptions].interceptors = options.interceptors + ? { ...options.interceptors } + : undefined + this[kFactory] = factory + + this.on('connect', (origin, targets) => { + if (clientTtl != null && clientTtl > 0) { + for (const target of targets) { + Object.assign(target, { ttl: Date.now() }) + } + } + }) + + this.on('connectionError', (origin, targets, error) => { + // If a connection error occurs, we remove the client from the pool, + // and emit a connectionError event. They will not be re-used. + // Fixes https://github.com/nodejs/undici/issues/3895 + for (const target of targets) { + // Do not use kRemoveClient here, as it will close the client, + // but the client cannot be closed in this state. + const idx = this[kClients].indexOf(target) + if (idx !== -1) { + this[kClients].splice(idx, 1) + } + } + }) + } + + [kGetDispatcher] () { + const clientTtlOption = this[kOptions].clientTtl + for (const client of this[kClients]) { + // check ttl of client and if it's stale, remove it from the pool + if (clientTtlOption != null && clientTtlOption > 0 && client.ttl && ((Date.now() - client.ttl) > clientTtlOption)) { + this[kRemoveClient](client) + } else if (!client[kNeedDrain]) { + return client + } + } + + if (!this[kConnections] || this[kClients].length < this[kConnections]) { + const dispatcher = this[kFactory](this[kUrl], this[kOptions]) + this[kAddClient](dispatcher) + return dispatcher + } + } +} + +module.exports = Pool diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/proxy-agent.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/proxy-agent.js new file mode 100644 index 0000000000000000000000000000000000000000..f0a71f7adbfb754f049d6e57ead31d3d9f3baad1 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/proxy-agent.js @@ -0,0 +1,271 @@ +'use strict' + +const { kProxy, kClose, kDestroy, kDispatch } = require('../core/symbols') +const Agent = require('./agent') +const Pool = require('./pool') +const DispatcherBase = require('./dispatcher-base') +const { InvalidArgumentError, RequestAbortedError, SecureProxyConnectionError } = require('../core/errors') +const buildConnector = require('../core/connect') +const Client = require('./client') + +const kAgent = Symbol('proxy agent') +const kClient = Symbol('proxy client') +const kProxyHeaders = Symbol('proxy headers') +const kRequestTls = Symbol('request tls settings') +const kProxyTls = Symbol('proxy tls settings') +const kConnectEndpoint = Symbol('connect endpoint function') +const kTunnelProxy = Symbol('tunnel proxy') + +function defaultProtocolPort (protocol) { + return protocol === 'https:' ? 443 : 80 +} + +function defaultFactory (origin, opts) { + return new Pool(origin, opts) +} + +const noop = () => {} + +function defaultAgentFactory (origin, opts) { + if (opts.connections === 1) { + return new Client(origin, opts) + } + return new Pool(origin, opts) +} + +class Http1ProxyWrapper extends DispatcherBase { + #client + + constructor (proxyUrl, { headers = {}, connect, factory }) { + super() + if (!proxyUrl) { + throw new InvalidArgumentError('Proxy URL is mandatory') + } + + this[kProxyHeaders] = headers + if (factory) { + this.#client = factory(proxyUrl, { connect }) + } else { + this.#client = new Client(proxyUrl, { connect }) + } + } + + [kDispatch] (opts, handler) { + const onHeaders = handler.onHeaders + handler.onHeaders = function (statusCode, data, resume) { + if (statusCode === 407) { + if (typeof handler.onError === 'function') { + handler.onError(new InvalidArgumentError('Proxy Authentication Required (407)')) + } + return + } + if (onHeaders) onHeaders.call(this, statusCode, data, resume) + } + + // Rewrite request as an HTTP1 Proxy request, without tunneling. + const { + origin, + path = '/', + headers = {} + } = opts + + opts.path = origin + path + + if (!('host' in headers) && !('Host' in headers)) { + const { host } = new URL(origin) + headers.host = host + } + opts.headers = { ...this[kProxyHeaders], ...headers } + + return this.#client[kDispatch](opts, handler) + } + + async [kClose] () { + return this.#client.close() + } + + async [kDestroy] (err) { + return this.#client.destroy(err) + } +} + +class ProxyAgent extends DispatcherBase { + constructor (opts) { + if (!opts || (typeof opts === 'object' && !(opts instanceof URL) && !opts.uri)) { + throw new InvalidArgumentError('Proxy uri is mandatory') + } + + const { clientFactory = defaultFactory } = opts + if (typeof clientFactory !== 'function') { + throw new InvalidArgumentError('Proxy opts.clientFactory must be a function.') + } + + const { proxyTunnel = true } = opts + + super() + + const url = this.#getUrl(opts) + const { href, origin, port, protocol, username, password, hostname: proxyHostname } = url + + this[kProxy] = { uri: href, protocol } + this[kRequestTls] = opts.requestTls + this[kProxyTls] = opts.proxyTls + this[kProxyHeaders] = opts.headers || {} + this[kTunnelProxy] = proxyTunnel + + if (opts.auth && opts.token) { + throw new InvalidArgumentError('opts.auth cannot be used in combination with opts.token') + } else if (opts.auth) { + /* @deprecated in favour of opts.token */ + this[kProxyHeaders]['proxy-authorization'] = `Basic ${opts.auth}` + } else if (opts.token) { + this[kProxyHeaders]['proxy-authorization'] = opts.token + } else if (username && password) { + this[kProxyHeaders]['proxy-authorization'] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString('base64')}` + } + + const connect = buildConnector({ ...opts.proxyTls }) + this[kConnectEndpoint] = buildConnector({ ...opts.requestTls }) + + const agentFactory = opts.factory || defaultAgentFactory + const factory = (origin, options) => { + const { protocol } = new URL(origin) + if (!this[kTunnelProxy] && protocol === 'http:' && this[kProxy].protocol === 'http:') { + return new Http1ProxyWrapper(this[kProxy].uri, { + headers: this[kProxyHeaders], + connect, + factory: agentFactory + }) + } + return agentFactory(origin, options) + } + this[kClient] = clientFactory(url, { connect }) + this[kAgent] = new Agent({ + ...opts, + factory, + connect: async (opts, callback) => { + let requestedPath = opts.host + if (!opts.port) { + requestedPath += `:${defaultProtocolPort(opts.protocol)}` + } + try { + const { socket, statusCode } = await this[kClient].connect({ + origin, + port, + path: requestedPath, + signal: opts.signal, + headers: { + ...this[kProxyHeaders], + host: opts.host, + ...(opts.connections == null || opts.connections > 0 ? { 'proxy-connection': 'keep-alive' } : {}) + }, + servername: this[kProxyTls]?.servername || proxyHostname + }) + if (statusCode !== 200) { + socket.on('error', noop).destroy() + callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`)) + } + if (opts.protocol !== 'https:') { + callback(null, socket) + return + } + let servername + if (this[kRequestTls]) { + servername = this[kRequestTls].servername + } else { + servername = opts.servername + } + this[kConnectEndpoint]({ ...opts, servername, httpSocket: socket }, callback) + } catch (err) { + if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') { + // Throw a custom error to avoid loop in client.js#connect + callback(new SecureProxyConnectionError(err)) + } else { + callback(err) + } + } + } + }) + } + + dispatch (opts, handler) { + const headers = buildHeaders(opts.headers) + throwIfProxyAuthIsSent(headers) + + if (headers && !('host' in headers) && !('Host' in headers)) { + const { host } = new URL(opts.origin) + headers.host = host + } + + return this[kAgent].dispatch( + { + ...opts, + headers + }, + handler + ) + } + + /** + * @param {import('../../types/proxy-agent').ProxyAgent.Options | string | URL} opts + * @returns {URL} + */ + #getUrl (opts) { + if (typeof opts === 'string') { + return new URL(opts) + } else if (opts instanceof URL) { + return opts + } else { + return new URL(opts.uri) + } + } + + async [kClose] () { + await this[kAgent].close() + await this[kClient].close() + } + + async [kDestroy] () { + await this[kAgent].destroy() + await this[kClient].destroy() + } +} + +/** + * @param {string[] | Record} headers + * @returns {Record} + */ +function buildHeaders (headers) { + // When using undici.fetch, the headers list is stored + // as an array. + if (Array.isArray(headers)) { + /** @type {Record} */ + const headersPair = {} + + for (let i = 0; i < headers.length; i += 2) { + headersPair[headers[i]] = headers[i + 1] + } + + return headersPair + } + + return headers +} + +/** + * @param {Record} headers + * + * Previous versions of ProxyAgent suggests the Proxy-Authorization in request headers + * Nevertheless, it was changed and to avoid a security vulnerability by end users + * this check was created. + * It should be removed in the next major version for performance reasons + */ +function throwIfProxyAuthIsSent (headers) { + const existProxyAuth = headers && Object.keys(headers) + .find((key) => key.toLowerCase() === 'proxy-authorization') + if (existProxyAuth) { + throw new InvalidArgumentError('Proxy-Authorization should be sent in ProxyAgent constructor') + } +} + +module.exports = ProxyAgent diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/retry-agent.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/retry-agent.js new file mode 100644 index 0000000000000000000000000000000000000000..0c2120d6f26a2dd7fca5f2dc1b3fd9b8fd767a8f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/dispatcher/retry-agent.js @@ -0,0 +1,35 @@ +'use strict' + +const Dispatcher = require('./dispatcher') +const RetryHandler = require('../handler/retry-handler') + +class RetryAgent extends Dispatcher { + #agent = null + #options = null + constructor (agent, options = {}) { + super(options) + this.#agent = agent + this.#options = options + } + + dispatch (opts, handler) { + const retry = new RetryHandler({ + ...opts, + retryOptions: this.#options + }, { + dispatch: this.#agent.dispatch.bind(this.#agent), + handler + }) + return this.#agent.dispatch(opts, retry) + } + + close () { + return this.#agent.close() + } + + destroy () { + return this.#agent.destroy() + } +} + +module.exports = RetryAgent diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/global.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/global.js new file mode 100644 index 0000000000000000000000000000000000000000..0c7528fa653169bd9b786fdc51e3662093adddab --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/global.js @@ -0,0 +1,32 @@ +'use strict' + +// We include a version number for the Dispatcher API. In case of breaking changes, +// this version number must be increased to avoid conflicts. +const globalDispatcher = Symbol.for('undici.globalDispatcher.1') +const { InvalidArgumentError } = require('./core/errors') +const Agent = require('./dispatcher/agent') + +if (getGlobalDispatcher() === undefined) { + setGlobalDispatcher(new Agent()) +} + +function setGlobalDispatcher (agent) { + if (!agent || typeof agent.dispatch !== 'function') { + throw new InvalidArgumentError('Argument agent must implement Agent') + } + Object.defineProperty(globalThis, globalDispatcher, { + value: agent, + writable: true, + enumerable: false, + configurable: false + }) +} + +function getGlobalDispatcher () { + return globalThis[globalDispatcher] +} + +module.exports = { + setGlobalDispatcher, + getGlobalDispatcher +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/handler/cache-handler.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/handler/cache-handler.js new file mode 100644 index 0000000000000000000000000000000000000000..c21a7206551660343f70a141248f6005aa21564a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/handler/cache-handler.js @@ -0,0 +1,469 @@ +'use strict' + +const util = require('../core/util') +const { + parseCacheControlHeader, + parseVaryHeader, + isEtagUsable +} = require('../util/cache') +const { parseHttpDate } = require('../util/date.js') + +function noop () {} + +// Status codes that we can use some heuristics on to cache +const HEURISTICALLY_CACHEABLE_STATUS_CODES = [ + 200, 203, 204, 206, 300, 301, 308, 404, 405, 410, 414, 501 +] + +// Status codes which semantic is not handled by the cache +// https://datatracker.ietf.org/doc/html/rfc9111#section-3 +// This list should not grow beyond 206 and 304 unless the RFC is updated +// by a newer one including more. Please introduce another list if +// implementing caching of responses with the 'must-understand' directive. +const NOT_UNDERSTOOD_STATUS_CODES = [ + 206, 304 +] + +const MAX_RESPONSE_AGE = 2147483647000 + +/** + * @typedef {import('../../types/dispatcher.d.ts').default.DispatchHandler} DispatchHandler + * + * @implements {DispatchHandler} + */ +class CacheHandler { + /** + * @type {import('../../types/cache-interceptor.d.ts').default.CacheKey} + */ + #cacheKey + + /** + * @type {import('../../types/cache-interceptor.d.ts').default.CacheHandlerOptions['type']} + */ + #cacheType + + /** + * @type {number | undefined} + */ + #cacheByDefault + + /** + * @type {import('../../types/cache-interceptor.d.ts').default.CacheStore} + */ + #store + + /** + * @type {import('../../types/dispatcher.d.ts').default.DispatchHandler} + */ + #handler + + /** + * @type {import('node:stream').Writable | undefined} + */ + #writeStream + + /** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheHandlerOptions} opts + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} cacheKey + * @param {import('../../types/dispatcher.d.ts').default.DispatchHandler} handler + */ + constructor ({ store, type, cacheByDefault }, cacheKey, handler) { + this.#store = store + this.#cacheType = type + this.#cacheByDefault = cacheByDefault + this.#cacheKey = cacheKey + this.#handler = handler + } + + onRequestStart (controller, context) { + this.#writeStream?.destroy() + this.#writeStream = undefined + this.#handler.onRequestStart?.(controller, context) + } + + onRequestUpgrade (controller, statusCode, headers, socket) { + this.#handler.onRequestUpgrade?.(controller, statusCode, headers, socket) + } + + /** + * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller + * @param {number} statusCode + * @param {import('../../types/header.d.ts').IncomingHttpHeaders} resHeaders + * @param {string} statusMessage + */ + onResponseStart ( + controller, + statusCode, + resHeaders, + statusMessage + ) { + const downstreamOnHeaders = () => + this.#handler.onResponseStart?.( + controller, + statusCode, + resHeaders, + statusMessage + ) + + if ( + !util.safeHTTPMethods.includes(this.#cacheKey.method) && + statusCode >= 200 && + statusCode <= 399 + ) { + // Successful response to an unsafe method, delete it from cache + // https://www.rfc-editor.org/rfc/rfc9111.html#name-invalidating-stored-response + try { + this.#store.delete(this.#cacheKey)?.catch?.(noop) + } catch { + // Fail silently + } + return downstreamOnHeaders() + } + + const cacheControlHeader = resHeaders['cache-control'] + const heuristicallyCacheable = resHeaders['last-modified'] && HEURISTICALLY_CACHEABLE_STATUS_CODES.includes(statusCode) + if ( + !cacheControlHeader && + !resHeaders['expires'] && + !heuristicallyCacheable && + !this.#cacheByDefault + ) { + // Don't have anything to tell us this response is cachable and we're not + // caching by default + return downstreamOnHeaders() + } + + const cacheControlDirectives = cacheControlHeader ? parseCacheControlHeader(cacheControlHeader) : {} + if (!canCacheResponse(this.#cacheType, statusCode, resHeaders, cacheControlDirectives)) { + return downstreamOnHeaders() + } + + const now = Date.now() + const resAge = resHeaders.age ? getAge(resHeaders.age) : undefined + if (resAge && resAge >= MAX_RESPONSE_AGE) { + // Response considered stale + return downstreamOnHeaders() + } + + const resDate = typeof resHeaders.date === 'string' + ? parseHttpDate(resHeaders.date) + : undefined + + const staleAt = + determineStaleAt(this.#cacheType, now, resAge, resHeaders, resDate, cacheControlDirectives) ?? + this.#cacheByDefault + if (staleAt === undefined || (resAge && resAge > staleAt)) { + return downstreamOnHeaders() + } + + const baseTime = resDate ? resDate.getTime() : now + const absoluteStaleAt = staleAt + baseTime + if (now >= absoluteStaleAt) { + // Response is already stale + return downstreamOnHeaders() + } + + let varyDirectives + if (this.#cacheKey.headers && resHeaders.vary) { + varyDirectives = parseVaryHeader(resHeaders.vary, this.#cacheKey.headers) + if (!varyDirectives) { + // Parse error + return downstreamOnHeaders() + } + } + + const deleteAt = determineDeleteAt(baseTime, cacheControlDirectives, absoluteStaleAt) + const strippedHeaders = stripNecessaryHeaders(resHeaders, cacheControlDirectives) + + /** + * @type {import('../../types/cache-interceptor.d.ts').default.CacheValue} + */ + const value = { + statusCode, + statusMessage, + headers: strippedHeaders, + vary: varyDirectives, + cacheControlDirectives, + cachedAt: resAge ? now - resAge : now, + staleAt: absoluteStaleAt, + deleteAt + } + + if (typeof resHeaders.etag === 'string' && isEtagUsable(resHeaders.etag)) { + value.etag = resHeaders.etag + } + + this.#writeStream = this.#store.createWriteStream(this.#cacheKey, value) + if (!this.#writeStream) { + return downstreamOnHeaders() + } + + const handler = this + this.#writeStream + .on('drain', () => controller.resume()) + .on('error', function () { + // TODO (fix): Make error somehow observable? + handler.#writeStream = undefined + + // Delete the value in case the cache store is holding onto state from + // the call to createWriteStream + handler.#store.delete(handler.#cacheKey) + }) + .on('close', function () { + if (handler.#writeStream === this) { + handler.#writeStream = undefined + } + + // TODO (fix): Should we resume even if was paused downstream? + controller.resume() + }) + + return downstreamOnHeaders() + } + + onResponseData (controller, chunk) { + if (this.#writeStream?.write(chunk) === false) { + controller.pause() + } + + this.#handler.onResponseData?.(controller, chunk) + } + + onResponseEnd (controller, trailers) { + this.#writeStream?.end() + this.#handler.onResponseEnd?.(controller, trailers) + } + + onResponseError (controller, err) { + this.#writeStream?.destroy(err) + this.#writeStream = undefined + this.#handler.onResponseError?.(controller, err) + } +} + +/** + * @see https://www.rfc-editor.org/rfc/rfc9111.html#name-storing-responses-to-authen + * + * @param {import('../../types/cache-interceptor.d.ts').default.CacheOptions['type']} cacheType + * @param {number} statusCode + * @param {import('../../types/header.d.ts').IncomingHttpHeaders} resHeaders + * @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives} cacheControlDirectives + */ +function canCacheResponse (cacheType, statusCode, resHeaders, cacheControlDirectives) { + // Status code must be final and understood. + if (statusCode < 200 || NOT_UNDERSTOOD_STATUS_CODES.includes(statusCode)) { + return false + } + // Responses with neither status codes that are heuristically cacheable, nor "explicit enough" caching + // directives, are not cacheable. "Explicit enough": see https://www.rfc-editor.org/rfc/rfc9111.html#section-3 + if (!HEURISTICALLY_CACHEABLE_STATUS_CODES.includes(statusCode) && !resHeaders['expires'] && + !cacheControlDirectives.public && + cacheControlDirectives['max-age'] === undefined && + // RFC 9111: a private response directive, if the cache is not shared + !(cacheControlDirectives.private && cacheType === 'private') && + !(cacheControlDirectives['s-maxage'] !== undefined && cacheType === 'shared') + ) { + return false + } + + if (cacheControlDirectives['no-store']) { + return false + } + + if (cacheType === 'shared' && cacheControlDirectives.private === true) { + return false + } + + // https://www.rfc-editor.org/rfc/rfc9111.html#section-4.1-5 + if (resHeaders.vary?.includes('*')) { + return false + } + + // https://www.rfc-editor.org/rfc/rfc9111.html#name-storing-responses-to-authen + if (resHeaders.authorization) { + if (!cacheControlDirectives.public || typeof resHeaders.authorization !== 'string') { + return false + } + + if ( + Array.isArray(cacheControlDirectives['no-cache']) && + cacheControlDirectives['no-cache'].includes('authorization') + ) { + return false + } + + if ( + Array.isArray(cacheControlDirectives['private']) && + cacheControlDirectives['private'].includes('authorization') + ) { + return false + } + } + + return true +} + +/** + * @param {string | string[]} ageHeader + * @returns {number | undefined} + */ +function getAge (ageHeader) { + const age = parseInt(Array.isArray(ageHeader) ? ageHeader[0] : ageHeader) + + return isNaN(age) ? undefined : age * 1000 +} + +/** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheOptions['type']} cacheType + * @param {number} now + * @param {number | undefined} age + * @param {import('../../types/header.d.ts').IncomingHttpHeaders} resHeaders + * @param {Date | undefined} responseDate + * @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives} cacheControlDirectives + * + * @returns {number | undefined} time that the value is stale at in seconds or undefined if it shouldn't be cached + */ +function determineStaleAt (cacheType, now, age, resHeaders, responseDate, cacheControlDirectives) { + if (cacheType === 'shared') { + // Prioritize s-maxage since we're a shared cache + // s-maxage > max-age > Expire + // https://www.rfc-editor.org/rfc/rfc9111.html#section-5.2.2.10-3 + const sMaxAge = cacheControlDirectives['s-maxage'] + if (sMaxAge !== undefined) { + return sMaxAge > 0 ? sMaxAge * 1000 : undefined + } + } + + const maxAge = cacheControlDirectives['max-age'] + if (maxAge !== undefined) { + return maxAge > 0 ? maxAge * 1000 : undefined + } + + if (typeof resHeaders.expires === 'string') { + // https://www.rfc-editor.org/rfc/rfc9111.html#section-5.3 + const expiresDate = parseHttpDate(resHeaders.expires) + if (expiresDate) { + if (now >= expiresDate.getTime()) { + return undefined + } + + if (responseDate) { + if (responseDate >= expiresDate) { + return undefined + } + + if (age !== undefined && age > (expiresDate - responseDate)) { + return undefined + } + } + + return expiresDate.getTime() - now + } + } + + if (typeof resHeaders['last-modified'] === 'string') { + // https://www.rfc-editor.org/rfc/rfc9111.html#name-calculating-heuristic-fresh + const lastModified = new Date(resHeaders['last-modified']) + if (isValidDate(lastModified)) { + if (lastModified.getTime() >= now) { + return undefined + } + + const responseAge = now - lastModified.getTime() + + return responseAge * 0.1 + } + } + + if (cacheControlDirectives.immutable) { + // https://www.rfc-editor.org/rfc/rfc8246.html#section-2.2 + return 31536000 + } + + return undefined +} + +/** + * @param {number} now + * @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives} cacheControlDirectives + * @param {number} staleAt + */ +function determineDeleteAt (now, cacheControlDirectives, staleAt) { + let staleWhileRevalidate = -Infinity + let staleIfError = -Infinity + let immutable = -Infinity + + if (cacheControlDirectives['stale-while-revalidate']) { + staleWhileRevalidate = staleAt + (cacheControlDirectives['stale-while-revalidate'] * 1000) + } + + if (cacheControlDirectives['stale-if-error']) { + staleIfError = staleAt + (cacheControlDirectives['stale-if-error'] * 1000) + } + + if (staleWhileRevalidate === -Infinity && staleIfError === -Infinity) { + immutable = now + 31536000000 + } + + return Math.max(staleAt, staleWhileRevalidate, staleIfError, immutable) +} + +/** + * Strips headers required to be removed in cached responses + * @param {import('../../types/header.d.ts').IncomingHttpHeaders} resHeaders + * @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives} cacheControlDirectives + * @returns {Record} + */ +function stripNecessaryHeaders (resHeaders, cacheControlDirectives) { + const headersToRemove = [ + 'connection', + 'proxy-authenticate', + 'proxy-authentication-info', + 'proxy-authorization', + 'proxy-connection', + 'te', + 'transfer-encoding', + 'upgrade', + // We'll add age back when serving it + 'age' + ] + + if (resHeaders['connection']) { + if (Array.isArray(resHeaders['connection'])) { + // connection: a + // connection: b + headersToRemove.push(...resHeaders['connection'].map(header => header.trim())) + } else { + // connection: a, b + headersToRemove.push(...resHeaders['connection'].split(',').map(header => header.trim())) + } + } + + if (Array.isArray(cacheControlDirectives['no-cache'])) { + headersToRemove.push(...cacheControlDirectives['no-cache']) + } + + if (Array.isArray(cacheControlDirectives['private'])) { + headersToRemove.push(...cacheControlDirectives['private']) + } + + let strippedHeaders + for (const headerName of headersToRemove) { + if (resHeaders[headerName]) { + strippedHeaders ??= { ...resHeaders } + delete strippedHeaders[headerName] + } + } + + return strippedHeaders ?? resHeaders +} + +/** + * @param {Date} date + * @returns {boolean} + */ +function isValidDate (date) { + return date instanceof Date && Number.isFinite(date.valueOf()) +} + +module.exports = CacheHandler diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/handler/cache-revalidation-handler.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/handler/cache-revalidation-handler.js new file mode 100644 index 0000000000000000000000000000000000000000..393d16d52c60fb861e3154ec47e3552829c432e0 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/handler/cache-revalidation-handler.js @@ -0,0 +1,124 @@ +'use strict' + +const assert = require('node:assert') + +/** + * This takes care of revalidation requests we send to the origin. If we get + * a response indicating that what we have is cached (via a HTTP 304), we can + * continue using the cached value. Otherwise, we'll receive the new response + * here, which we then just pass on to the next handler (most likely a + * CacheHandler). Note that this assumes the proper headers were already + * included in the request to tell the origin that we want to revalidate the + * response (i.e. if-modified-since or if-none-match). + * + * @see https://www.rfc-editor.org/rfc/rfc9111.html#name-validation + * + * @implements {import('../../types/dispatcher.d.ts').default.DispatchHandler} + */ +class CacheRevalidationHandler { + #successful = false + + /** + * @type {((boolean, any) => void) | null} + */ + #callback + + /** + * @type {(import('../../types/dispatcher.d.ts').default.DispatchHandler)} + */ + #handler + + #context + + /** + * @type {boolean} + */ + #allowErrorStatusCodes + + /** + * @param {(boolean) => void} callback Function to call if the cached value is valid + * @param {import('../../types/dispatcher.d.ts').default.DispatchHandlers} handler + * @param {boolean} allowErrorStatusCodes + */ + constructor (callback, handler, allowErrorStatusCodes) { + if (typeof callback !== 'function') { + throw new TypeError('callback must be a function') + } + + this.#callback = callback + this.#handler = handler + this.#allowErrorStatusCodes = allowErrorStatusCodes + } + + onRequestStart (_, context) { + this.#successful = false + this.#context = context + } + + onRequestUpgrade (controller, statusCode, headers, socket) { + this.#handler.onRequestUpgrade?.(controller, statusCode, headers, socket) + } + + onResponseStart ( + controller, + statusCode, + headers, + statusMessage + ) { + assert(this.#callback != null) + + // https://www.rfc-editor.org/rfc/rfc9111.html#name-handling-a-validation-respo + // https://datatracker.ietf.org/doc/html/rfc5861#section-4 + this.#successful = statusCode === 304 || + (this.#allowErrorStatusCodes && statusCode >= 500 && statusCode <= 504) + this.#callback(this.#successful, this.#context) + this.#callback = null + + if (this.#successful) { + return true + } + + this.#handler.onRequestStart?.(controller, this.#context) + this.#handler.onResponseStart?.( + controller, + statusCode, + headers, + statusMessage + ) + } + + onResponseData (controller, chunk) { + if (this.#successful) { + return + } + + return this.#handler.onResponseData?.(controller, chunk) + } + + onResponseEnd (controller, trailers) { + if (this.#successful) { + return + } + + this.#handler.onResponseEnd?.(controller, trailers) + } + + onResponseError (controller, err) { + if (this.#successful) { + return + } + + if (this.#callback) { + this.#callback(false) + this.#callback = null + } + + if (typeof this.#handler.onResponseError === 'function') { + this.#handler.onResponseError(controller, err) + } else { + throw err + } + } +} + +module.exports = CacheRevalidationHandler diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/handler/decorator-handler.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/handler/decorator-handler.js new file mode 100644 index 0000000000000000000000000000000000000000..50fbb0cf89280d1a973fec63ba9e51a3dfe921a3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/handler/decorator-handler.js @@ -0,0 +1,67 @@ +'use strict' + +const assert = require('node:assert') +const WrapHandler = require('./wrap-handler') + +/** + * @deprecated + */ +module.exports = class DecoratorHandler { + #handler + #onCompleteCalled = false + #onErrorCalled = false + #onResponseStartCalled = false + + constructor (handler) { + if (typeof handler !== 'object' || handler === null) { + throw new TypeError('handler must be an object') + } + this.#handler = WrapHandler.wrap(handler) + } + + onRequestStart (...args) { + this.#handler.onRequestStart?.(...args) + } + + onRequestUpgrade (...args) { + assert(!this.#onCompleteCalled) + assert(!this.#onErrorCalled) + + return this.#handler.onRequestUpgrade?.(...args) + } + + onResponseStart (...args) { + assert(!this.#onCompleteCalled) + assert(!this.#onErrorCalled) + assert(!this.#onResponseStartCalled) + + this.#onResponseStartCalled = true + + return this.#handler.onResponseStart?.(...args) + } + + onResponseData (...args) { + assert(!this.#onCompleteCalled) + assert(!this.#onErrorCalled) + + return this.#handler.onResponseData?.(...args) + } + + onResponseEnd (...args) { + assert(!this.#onCompleteCalled) + assert(!this.#onErrorCalled) + + this.#onCompleteCalled = true + return this.#handler.onResponseEnd?.(...args) + } + + onResponseError (...args) { + this.#onErrorCalled = true + return this.#handler.onResponseError?.(...args) + } + + /** + * @deprecated + */ + onBodySent () {} +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/handler/redirect-handler.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/handler/redirect-handler.js new file mode 100644 index 0000000000000000000000000000000000000000..dd0f47170ae154635bbcdacb219d2957ff3cae27 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/handler/redirect-handler.js @@ -0,0 +1,237 @@ +'use strict' + +const util = require('../core/util') +const { kBodyUsed } = require('../core/symbols') +const assert = require('node:assert') +const { InvalidArgumentError } = require('../core/errors') +const EE = require('node:events') + +const redirectableStatusCodes = [300, 301, 302, 303, 307, 308] + +const kBody = Symbol('body') + +const noop = () => {} + +class BodyAsyncIterable { + constructor (body) { + this[kBody] = body + this[kBodyUsed] = false + } + + async * [Symbol.asyncIterator] () { + assert(!this[kBodyUsed], 'disturbed') + this[kBodyUsed] = true + yield * this[kBody] + } +} + +class RedirectHandler { + static buildDispatch (dispatcher, maxRedirections) { + if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { + throw new InvalidArgumentError('maxRedirections must be a positive number') + } + + const dispatch = dispatcher.dispatch.bind(dispatcher) + return (opts, originalHandler) => dispatch(opts, new RedirectHandler(dispatch, maxRedirections, opts, originalHandler)) + } + + constructor (dispatch, maxRedirections, opts, handler) { + if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { + throw new InvalidArgumentError('maxRedirections must be a positive number') + } + + this.dispatch = dispatch + this.location = null + const { maxRedirections: _, ...cleanOpts } = opts + this.opts = cleanOpts // opts must be a copy, exclude maxRedirections + this.maxRedirections = maxRedirections + this.handler = handler + this.history = [] + + if (util.isStream(this.opts.body)) { + // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp + // so that it can be dispatched again? + // TODO (fix): Do we need 100-expect support to provide a way to do this properly? + if (util.bodyLength(this.opts.body) === 0) { + this.opts.body + .on('data', function () { + assert(false) + }) + } + + if (typeof this.opts.body.readableDidRead !== 'boolean') { + this.opts.body[kBodyUsed] = false + EE.prototype.on.call(this.opts.body, 'data', function () { + this[kBodyUsed] = true + }) + } + } else if (this.opts.body && typeof this.opts.body.pipeTo === 'function') { + // TODO (fix): We can't access ReadableStream internal state + // to determine whether or not it has been disturbed. This is just + // a workaround. + this.opts.body = new BodyAsyncIterable(this.opts.body) + } else if ( + this.opts.body && + typeof this.opts.body !== 'string' && + !ArrayBuffer.isView(this.opts.body) && + util.isIterable(this.opts.body) && + !util.isFormDataLike(this.opts.body) + ) { + // TODO: Should we allow re-using iterable if !this.opts.idempotent + // or through some other flag? + this.opts.body = new BodyAsyncIterable(this.opts.body) + } + } + + onRequestStart (controller, context) { + this.handler.onRequestStart?.(controller, { ...context, history: this.history }) + } + + onRequestUpgrade (controller, statusCode, headers, socket) { + this.handler.onRequestUpgrade?.(controller, statusCode, headers, socket) + } + + onResponseStart (controller, statusCode, headers, statusMessage) { + if (this.opts.throwOnMaxRedirect && this.history.length >= this.maxRedirections) { + throw new Error('max redirects') + } + + // https://tools.ietf.org/html/rfc7231#section-6.4.2 + // https://fetch.spec.whatwg.org/#http-redirect-fetch + // In case of HTTP 301 or 302 with POST, change the method to GET + if ((statusCode === 301 || statusCode === 302) && this.opts.method === 'POST') { + this.opts.method = 'GET' + if (util.isStream(this.opts.body)) { + util.destroy(this.opts.body.on('error', noop)) + } + this.opts.body = null + } + + // https://tools.ietf.org/html/rfc7231#section-6.4.4 + // In case of HTTP 303, always replace method to be either HEAD or GET + if (statusCode === 303 && this.opts.method !== 'HEAD') { + this.opts.method = 'GET' + if (util.isStream(this.opts.body)) { + util.destroy(this.opts.body.on('error', noop)) + } + this.opts.body = null + } + + this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body) || redirectableStatusCodes.indexOf(statusCode) === -1 + ? null + : headers.location + + if (this.opts.origin) { + this.history.push(new URL(this.opts.path, this.opts.origin)) + } + + if (!this.location) { + this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage) + return + } + + const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin))) + const path = search ? `${pathname}${search}` : pathname + + // Check for redirect loops by seeing if we've already visited this URL in our history + // This catches the case where Client/Pool try to handle cross-origin redirects but fail + // and keep redirecting to the same URL in an infinite loop + const redirectUrlString = `${origin}${path}` + for (const historyUrl of this.history) { + if (historyUrl.toString() === redirectUrlString) { + throw new InvalidArgumentError(`Redirect loop detected. Cannot redirect to ${origin}. This typically happens when using a Client or Pool with cross-origin redirects. Use an Agent for cross-origin redirects.`) + } + } + + // Remove headers referring to the original URL. + // By default it is Host only, unless it's a 303 (see below), which removes also all Content-* headers. + // https://tools.ietf.org/html/rfc7231#section-6.4 + this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin) + this.opts.path = path + this.opts.origin = origin + this.opts.query = null + } + + onResponseData (controller, chunk) { + if (this.location) { + /* + https://tools.ietf.org/html/rfc7231#section-6.4 + + TLDR: undici always ignores 3xx response bodies. + + Redirection is used to serve the requested resource from another URL, so it assumes that + no body is generated (and thus can be ignored). Even though generating a body is not prohibited. + + For status 301, 302, 303, 307 and 308 (the latter from RFC 7238), the specs mention that the body usually + (which means it's optional and not mandated) contain just an hyperlink to the value of + the Location response header, so the body can be ignored safely. + + For status 300, which is "Multiple Choices", the spec mentions both generating a Location + response header AND a response body with the other possible location to follow. + Since the spec explicitly chooses not to specify a format for such body and leave it to + servers and browsers implementors, we ignore the body as there is no specified way to eventually parse it. + */ + } else { + this.handler.onResponseData?.(controller, chunk) + } + } + + onResponseEnd (controller, trailers) { + if (this.location) { + /* + https://tools.ietf.org/html/rfc7231#section-6.4 + + TLDR: undici always ignores 3xx response trailers as they are not expected in case of redirections + and neither are useful if present. + + See comment on onData method above for more detailed information. + */ + this.dispatch(this.opts, this) + } else { + this.handler.onResponseEnd(controller, trailers) + } + } + + onResponseError (controller, error) { + this.handler.onResponseError?.(controller, error) + } +} + +// https://tools.ietf.org/html/rfc7231#section-6.4.4 +function shouldRemoveHeader (header, removeContent, unknownOrigin) { + if (header.length === 4) { + return util.headerNameToString(header) === 'host' + } + if (removeContent && util.headerNameToString(header).startsWith('content-')) { + return true + } + if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) { + const name = util.headerNameToString(header) + return name === 'authorization' || name === 'cookie' || name === 'proxy-authorization' + } + return false +} + +// https://tools.ietf.org/html/rfc7231#section-6.4 +function cleanRequestHeaders (headers, removeContent, unknownOrigin) { + const ret = [] + if (Array.isArray(headers)) { + for (let i = 0; i < headers.length; i += 2) { + if (!shouldRemoveHeader(headers[i], removeContent, unknownOrigin)) { + ret.push(headers[i], headers[i + 1]) + } + } + } else if (headers && typeof headers === 'object') { + const entries = typeof headers[Symbol.iterator] === 'function' ? headers : Object.entries(headers) + for (const [key, value] of entries) { + if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) { + ret.push(key, value) + } + } + } else { + assert(headers == null, 'headers must be an object or an array') + } + return ret +} + +module.exports = RedirectHandler diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/handler/retry-handler.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/handler/retry-handler.js new file mode 100644 index 0000000000000000000000000000000000000000..0d4b2affdcaba47ae48cb4706d5edc62890f7581 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/handler/retry-handler.js @@ -0,0 +1,396 @@ +'use strict' +const assert = require('node:assert') + +const { kRetryHandlerDefaultRetry } = require('../core/symbols') +const { RequestRetryError } = require('../core/errors') +const WrapHandler = require('./wrap-handler') +const { + isDisturbed, + parseRangeHeader, + wrapRequestBody +} = require('../core/util') + +function calculateRetryAfterHeader (retryAfter) { + const retryTime = new Date(retryAfter).getTime() + return isNaN(retryTime) ? 0 : retryTime - Date.now() +} + +class RetryHandler { + constructor (opts, { dispatch, handler }) { + const { retryOptions, ...dispatchOpts } = opts + const { + // Retry scoped + retry: retryFn, + maxRetries, + maxTimeout, + minTimeout, + timeoutFactor, + // Response scoped + methods, + errorCodes, + retryAfter, + statusCodes, + throwOnError + } = retryOptions ?? {} + + this.error = null + this.dispatch = dispatch + this.handler = WrapHandler.wrap(handler) + this.opts = { ...dispatchOpts, body: wrapRequestBody(opts.body) } + this.retryOpts = { + throwOnError: throwOnError ?? true, + retry: retryFn ?? RetryHandler[kRetryHandlerDefaultRetry], + retryAfter: retryAfter ?? true, + maxTimeout: maxTimeout ?? 30 * 1000, // 30s, + minTimeout: minTimeout ?? 500, // .5s + timeoutFactor: timeoutFactor ?? 2, + maxRetries: maxRetries ?? 5, + // What errors we should retry + methods: methods ?? ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'], + // Indicates which errors to retry + statusCodes: statusCodes ?? [500, 502, 503, 504, 429], + // List of errors to retry + errorCodes: errorCodes ?? [ + 'ECONNRESET', + 'ECONNREFUSED', + 'ENOTFOUND', + 'ENETDOWN', + 'ENETUNREACH', + 'EHOSTDOWN', + 'EHOSTUNREACH', + 'EPIPE', + 'UND_ERR_SOCKET' + ] + } + + this.retryCount = 0 + this.retryCountCheckpoint = 0 + this.headersSent = false + this.start = 0 + this.end = null + this.etag = null + } + + onResponseStartWithRetry (controller, statusCode, headers, statusMessage, err) { + if (this.retryOpts.throwOnError) { + // Preserve old behavior for status codes that are not eligible for retry + if (this.retryOpts.statusCodes.includes(statusCode) === false) { + this.headersSent = true + this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage) + } else { + this.error = err + } + + return + } + + if (isDisturbed(this.opts.body)) { + this.headersSent = true + this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage) + return + } + + function shouldRetry (passedErr) { + if (passedErr) { + this.headersSent = true + + this.headersSent = true + this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage) + controller.resume() + return + } + + this.error = err + controller.resume() + } + + controller.pause() + this.retryOpts.retry( + err, + { + state: { counter: this.retryCount }, + opts: { retryOptions: this.retryOpts, ...this.opts } + }, + shouldRetry.bind(this) + ) + } + + onRequestStart (controller, context) { + if (!this.headersSent) { + this.handler.onRequestStart?.(controller, context) + } + } + + onRequestUpgrade (controller, statusCode, headers, socket) { + this.handler.onRequestUpgrade?.(controller, statusCode, headers, socket) + } + + static [kRetryHandlerDefaultRetry] (err, { state, opts }, cb) { + const { statusCode, code, headers } = err + const { method, retryOptions } = opts + const { + maxRetries, + minTimeout, + maxTimeout, + timeoutFactor, + statusCodes, + errorCodes, + methods + } = retryOptions + const { counter } = state + + // Any code that is not a Undici's originated and allowed to retry + if (code && code !== 'UND_ERR_REQ_RETRY' && !errorCodes.includes(code)) { + cb(err) + return + } + + // If a set of method are provided and the current method is not in the list + if (Array.isArray(methods) && !methods.includes(method)) { + cb(err) + return + } + + // If a set of status code are provided and the current status code is not in the list + if ( + statusCode != null && + Array.isArray(statusCodes) && + !statusCodes.includes(statusCode) + ) { + cb(err) + return + } + + // If we reached the max number of retries + if (counter > maxRetries) { + cb(err) + return + } + + let retryAfterHeader = headers?.['retry-after'] + if (retryAfterHeader) { + retryAfterHeader = Number(retryAfterHeader) + retryAfterHeader = Number.isNaN(retryAfterHeader) + ? calculateRetryAfterHeader(headers['retry-after']) + : retryAfterHeader * 1e3 // Retry-After is in seconds + } + + const retryTimeout = + retryAfterHeader > 0 + ? Math.min(retryAfterHeader, maxTimeout) + : Math.min(minTimeout * timeoutFactor ** (counter - 1), maxTimeout) + + setTimeout(() => cb(null), retryTimeout) + } + + onResponseStart (controller, statusCode, headers, statusMessage) { + this.error = null + this.retryCount += 1 + + if (statusCode >= 300) { + const err = new RequestRetryError('Request failed', statusCode, { + headers, + data: { + count: this.retryCount + } + }) + + this.onResponseStartWithRetry(controller, statusCode, headers, statusMessage, err) + return + } + + // Checkpoint for resume from where we left it + if (this.headersSent) { + // Only Partial Content 206 supposed to provide Content-Range, + // any other status code that partially consumed the payload + // should not be retried because it would result in downstream + // wrongly concatenate multiple responses. + if (statusCode !== 206 && (this.start > 0 || statusCode !== 200)) { + throw new RequestRetryError('server does not support the range header and the payload was partially consumed', statusCode, { + headers, + data: { count: this.retryCount } + }) + } + + const contentRange = parseRangeHeader(headers['content-range']) + // If no content range + if (!contentRange) { + // We always throw here as we want to indicate that we entred unexpected path + throw new RequestRetryError('Content-Range mismatch', statusCode, { + headers, + data: { count: this.retryCount } + }) + } + + // Let's start with a weak etag check + if (this.etag != null && this.etag !== headers.etag) { + // We always throw here as we want to indicate that we entred unexpected path + throw new RequestRetryError('ETag mismatch', statusCode, { + headers, + data: { count: this.retryCount } + }) + } + + const { start, size, end = size ? size - 1 : null } = contentRange + + assert(this.start === start, 'content-range mismatch') + assert(this.end == null || this.end === end, 'content-range mismatch') + + return + } + + if (this.end == null) { + if (statusCode === 206) { + // First time we receive 206 + const range = parseRangeHeader(headers['content-range']) + + if (range == null) { + this.headersSent = true + this.handler.onResponseStart?.( + controller, + statusCode, + headers, + statusMessage + ) + return + } + + const { start, size, end = size ? size - 1 : null } = range + assert( + start != null && Number.isFinite(start), + 'content-range mismatch' + ) + assert(end != null && Number.isFinite(end), 'invalid content-length') + + this.start = start + this.end = end + } + + // We make our best to checkpoint the body for further range headers + if (this.end == null) { + const contentLength = headers['content-length'] + this.end = contentLength != null ? Number(contentLength) - 1 : null + } + + assert(Number.isFinite(this.start)) + assert( + this.end == null || Number.isFinite(this.end), + 'invalid content-length' + ) + + this.resume = true + this.etag = headers.etag != null ? headers.etag : null + + // Weak etags are not useful for comparison nor cache + // for instance not safe to assume if the response is byte-per-byte + // equal + if ( + this.etag != null && + this.etag[0] === 'W' && + this.etag[1] === '/' + ) { + this.etag = null + } + + this.headersSent = true + this.handler.onResponseStart?.( + controller, + statusCode, + headers, + statusMessage + ) + } else { + throw new RequestRetryError('Request failed', statusCode, { + headers, + data: { count: this.retryCount } + }) + } + } + + onResponseData (controller, chunk) { + if (this.error) { + return + } + + this.start += chunk.length + + this.handler.onResponseData?.(controller, chunk) + } + + onResponseEnd (controller, trailers) { + if (this.error && this.retryOpts.throwOnError) { + throw this.error + } + + if (!this.error) { + this.retryCount = 0 + return this.handler.onResponseEnd?.(controller, trailers) + } + + this.retry(controller) + } + + retry (controller) { + if (this.start !== 0) { + const headers = { range: `bytes=${this.start}-${this.end ?? ''}` } + + // Weak etag check - weak etags will make comparison algorithms never match + if (this.etag != null) { + headers['if-match'] = this.etag + } + + this.opts = { + ...this.opts, + headers: { + ...this.opts.headers, + ...headers + } + } + } + + try { + this.retryCountCheckpoint = this.retryCount + this.dispatch(this.opts, this) + } catch (err) { + this.handler.onResponseError?.(controller, err) + } + } + + onResponseError (controller, err) { + if (controller?.aborted || isDisturbed(this.opts.body)) { + this.handler.onResponseError?.(controller, err) + return + } + + function shouldRetry (returnedErr) { + if (!returnedErr) { + this.retry(controller) + return + } + + this.handler?.onResponseError?.(controller, returnedErr) + } + + // We reconcile in case of a mix between network errors + // and server error response + if (this.retryCount - this.retryCountCheckpoint > 0) { + // We count the difference between the last checkpoint and the current retry count + this.retryCount = + this.retryCountCheckpoint + + (this.retryCount - this.retryCountCheckpoint) + } else { + this.retryCount += 1 + } + + this.retryOpts.retry( + err, + { + state: { counter: this.retryCount }, + opts: { retryOptions: this.retryOpts, ...this.opts } + }, + shouldRetry.bind(this) + ) + } +} + +module.exports = RetryHandler diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/handler/unwrap-handler.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/handler/unwrap-handler.js new file mode 100644 index 0000000000000000000000000000000000000000..865593a327bdb6ec5f8f0bc863a68514cbfaae13 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/handler/unwrap-handler.js @@ -0,0 +1,96 @@ +'use strict' + +const { parseHeaders } = require('../core/util') +const { InvalidArgumentError } = require('../core/errors') + +const kResume = Symbol('resume') + +class UnwrapController { + #paused = false + #reason = null + #aborted = false + #abort + + [kResume] = null + + constructor (abort) { + this.#abort = abort + } + + pause () { + this.#paused = true + } + + resume () { + if (this.#paused) { + this.#paused = false + this[kResume]?.() + } + } + + abort (reason) { + if (!this.#aborted) { + this.#aborted = true + this.#reason = reason + this.#abort(reason) + } + } + + get aborted () { + return this.#aborted + } + + get reason () { + return this.#reason + } + + get paused () { + return this.#paused + } +} + +module.exports = class UnwrapHandler { + #handler + #controller + + constructor (handler) { + this.#handler = handler + } + + static unwrap (handler) { + // TODO (fix): More checks... + return !handler.onRequestStart ? handler : new UnwrapHandler(handler) + } + + onConnect (abort, context) { + this.#controller = new UnwrapController(abort) + this.#handler.onRequestStart?.(this.#controller, context) + } + + onUpgrade (statusCode, rawHeaders, socket) { + this.#handler.onRequestUpgrade?.(this.#controller, statusCode, parseHeaders(rawHeaders), socket) + } + + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + this.#controller[kResume] = resume + this.#handler.onResponseStart?.(this.#controller, statusCode, parseHeaders(rawHeaders), statusMessage) + return !this.#controller.paused + } + + onData (data) { + this.#handler.onResponseData?.(this.#controller, data) + return !this.#controller.paused + } + + onComplete (rawTrailers) { + this.#handler.onResponseEnd?.(this.#controller, parseHeaders(rawTrailers)) + } + + onError (err) { + if (!this.#handler.onResponseError) { + throw new InvalidArgumentError('invalid onError method') + } + + this.#handler.onResponseError?.(this.#controller, err) + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/handler/wrap-handler.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/handler/wrap-handler.js new file mode 100644 index 0000000000000000000000000000000000000000..47caa5fa68ba0d300a17ac9d38fbba7ca627dde5 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/handler/wrap-handler.js @@ -0,0 +1,95 @@ +'use strict' + +const { InvalidArgumentError } = require('../core/errors') + +module.exports = class WrapHandler { + #handler + + constructor (handler) { + this.#handler = handler + } + + static wrap (handler) { + // TODO (fix): More checks... + return handler.onRequestStart ? handler : new WrapHandler(handler) + } + + // Unwrap Interface + + onConnect (abort, context) { + return this.#handler.onConnect?.(abort, context) + } + + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + return this.#handler.onHeaders?.(statusCode, rawHeaders, resume, statusMessage) + } + + onUpgrade (statusCode, rawHeaders, socket) { + return this.#handler.onUpgrade?.(statusCode, rawHeaders, socket) + } + + onData (data) { + return this.#handler.onData?.(data) + } + + onComplete (trailers) { + return this.#handler.onComplete?.(trailers) + } + + onError (err) { + if (!this.#handler.onError) { + throw err + } + + return this.#handler.onError?.(err) + } + + // Wrap Interface + + onRequestStart (controller, context) { + this.#handler.onConnect?.((reason) => controller.abort(reason), context) + } + + onRequestUpgrade (controller, statusCode, headers, socket) { + const rawHeaders = [] + for (const [key, val] of Object.entries(headers)) { + rawHeaders.push(Buffer.from(key), Array.isArray(val) ? val.map(v => Buffer.from(v)) : Buffer.from(val)) + } + + this.#handler.onUpgrade?.(statusCode, rawHeaders, socket) + } + + onResponseStart (controller, statusCode, headers, statusMessage) { + const rawHeaders = [] + for (const [key, val] of Object.entries(headers)) { + rawHeaders.push(Buffer.from(key), Array.isArray(val) ? val.map(v => Buffer.from(v)) : Buffer.from(val)) + } + + if (this.#handler.onHeaders?.(statusCode, rawHeaders, () => controller.resume(), statusMessage) === false) { + controller.pause() + } + } + + onResponseData (controller, data) { + if (this.#handler.onData?.(data) === false) { + controller.pause() + } + } + + onResponseEnd (controller, trailers) { + const rawTrailers = [] + for (const [key, val] of Object.entries(trailers)) { + rawTrailers.push(Buffer.from(key), Array.isArray(val) ? val.map(v => Buffer.from(v)) : Buffer.from(val)) + } + + this.#handler.onComplete?.(rawTrailers) + } + + onResponseError (controller, err) { + if (!this.#handler.onError) { + throw new InvalidArgumentError('invalid onError method') + } + + this.#handler.onError?.(err) + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/interceptor/cache.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/interceptor/cache.js new file mode 100644 index 0000000000000000000000000000000000000000..6565baf0a51014e1e43474ad7bac12b5bb95a434 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/interceptor/cache.js @@ -0,0 +1,372 @@ +'use strict' + +const assert = require('node:assert') +const { Readable } = require('node:stream') +const util = require('../core/util') +const CacheHandler = require('../handler/cache-handler') +const MemoryCacheStore = require('../cache/memory-cache-store') +const CacheRevalidationHandler = require('../handler/cache-revalidation-handler') +const { assertCacheStore, assertCacheMethods, makeCacheKey, normalizeHeaders, parseCacheControlHeader } = require('../util/cache.js') +const { AbortError } = require('../core/errors.js') + +/** + * @typedef {(options: import('../../types/dispatcher.d.ts').default.DispatchOptions, handler: import('../../types/dispatcher.d.ts').default.DispatchHandler) => void} DispatchFn + */ + +/** + * @param {import('../../types/cache-interceptor.d.ts').default.GetResult} result + * @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives | undefined} cacheControlDirectives + * @returns {boolean} + */ +function needsRevalidation (result, cacheControlDirectives) { + if (cacheControlDirectives?.['no-cache']) { + // Always revalidate requests with the no-cache request directive + return true + } + + if (result.cacheControlDirectives?.['no-cache'] && !Array.isArray(result.cacheControlDirectives['no-cache'])) { + // Always revalidate requests with unqualified no-cache response directive + return true + } + + const now = Date.now() + if (now > result.staleAt) { + // Response is stale + if (cacheControlDirectives?.['max-stale']) { + // There's a threshold where we can serve stale responses, let's see if + // we're in it + // https://www.rfc-editor.org/rfc/rfc9111.html#name-max-stale + const gracePeriod = result.staleAt + (cacheControlDirectives['max-stale'] * 1000) + return now > gracePeriod + } + + return true + } + + if (cacheControlDirectives?.['min-fresh']) { + // https://www.rfc-editor.org/rfc/rfc9111.html#section-5.2.1.3 + + // At this point, staleAt is always > now + const timeLeftTillStale = result.staleAt - now + const threshold = cacheControlDirectives['min-fresh'] * 1000 + + return timeLeftTillStale <= threshold + } + + return false +} + +/** + * @param {DispatchFn} dispatch + * @param {import('../../types/cache-interceptor.d.ts').default.CacheHandlerOptions} globalOpts + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} cacheKey + * @param {import('../../types/dispatcher.d.ts').default.DispatchHandler} handler + * @param {import('../../types/dispatcher.d.ts').default.RequestOptions} opts + * @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives | undefined} reqCacheControl + */ +function handleUncachedResponse ( + dispatch, + globalOpts, + cacheKey, + handler, + opts, + reqCacheControl +) { + if (reqCacheControl?.['only-if-cached']) { + let aborted = false + try { + if (typeof handler.onConnect === 'function') { + handler.onConnect(() => { + aborted = true + }) + + if (aborted) { + return + } + } + + if (typeof handler.onHeaders === 'function') { + handler.onHeaders(504, [], () => {}, 'Gateway Timeout') + if (aborted) { + return + } + } + + if (typeof handler.onComplete === 'function') { + handler.onComplete([]) + } + } catch (err) { + if (typeof handler.onError === 'function') { + handler.onError(err) + } + } + + return true + } + + return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler)) +} + +/** + * @param {import('../../types/dispatcher.d.ts').default.DispatchHandler} handler + * @param {import('../../types/dispatcher.d.ts').default.RequestOptions} opts + * @param {import('../../types/cache-interceptor.d.ts').default.GetResult} result + * @param {number} age + * @param {any} context + * @param {boolean} isStale + */ +function sendCachedValue (handler, opts, result, age, context, isStale) { + // TODO (perf): Readable.from path can be optimized... + const stream = util.isStream(result.body) + ? result.body + : Readable.from(result.body ?? []) + + assert(!stream.destroyed, 'stream should not be destroyed') + assert(!stream.readableDidRead, 'stream should not be readableDidRead') + + const controller = { + resume () { + stream.resume() + }, + pause () { + stream.pause() + }, + get paused () { + return stream.isPaused() + }, + get aborted () { + return stream.destroyed + }, + get reason () { + return stream.errored + }, + abort (reason) { + stream.destroy(reason ?? new AbortError()) + } + } + + stream + .on('error', function (err) { + if (!this.readableEnded) { + if (typeof handler.onResponseError === 'function') { + handler.onResponseError(controller, err) + } else { + throw err + } + } + }) + .on('close', function () { + if (!this.errored) { + handler.onResponseEnd?.(controller, {}) + } + }) + + handler.onRequestStart?.(controller, context) + + if (stream.destroyed) { + return + } + + // Add the age header + // https://www.rfc-editor.org/rfc/rfc9111.html#name-age + const headers = { ...result.headers, age: String(age) } + + if (isStale) { + // Add warning header + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Warning + headers.warning = '110 - "response is stale"' + } + + handler.onResponseStart?.(controller, result.statusCode, headers, result.statusMessage) + + if (opts.method === 'HEAD') { + stream.destroy() + } else { + stream.on('data', function (chunk) { + handler.onResponseData?.(controller, chunk) + }) + } +} + +/** + * @param {DispatchFn} dispatch + * @param {import('../../types/cache-interceptor.d.ts').default.CacheHandlerOptions} globalOpts + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} cacheKey + * @param {import('../../types/dispatcher.d.ts').default.DispatchHandler} handler + * @param {import('../../types/dispatcher.d.ts').default.RequestOptions} opts + * @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives | undefined} reqCacheControl + * @param {import('../../types/cache-interceptor.d.ts').default.GetResult | undefined} result + */ +function handleResult ( + dispatch, + globalOpts, + cacheKey, + handler, + opts, + reqCacheControl, + result +) { + if (!result) { + return handleUncachedResponse(dispatch, globalOpts, cacheKey, handler, opts, reqCacheControl) + } + + const now = Date.now() + if (now > result.deleteAt) { + // Response is expired, cache store shouldn't have given this to us + return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler)) + } + + const age = Math.round((now - result.cachedAt) / 1000) + if (reqCacheControl?.['max-age'] && age >= reqCacheControl['max-age']) { + // Response is considered expired for this specific request + // https://www.rfc-editor.org/rfc/rfc9111.html#section-5.2.1.1 + return dispatch(opts, handler) + } + + // Check if the response is stale + if (needsRevalidation(result, reqCacheControl)) { + if (util.isStream(opts.body) && util.bodyLength(opts.body) !== 0) { + // If body is a stream we can't revalidate... + // TODO (fix): This could be less strict... + return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler)) + } + + let withinStaleIfErrorThreshold = false + const staleIfErrorExpiry = result.cacheControlDirectives['stale-if-error'] ?? reqCacheControl?.['stale-if-error'] + if (staleIfErrorExpiry) { + withinStaleIfErrorThreshold = now < (result.staleAt + (staleIfErrorExpiry * 1000)) + } + + let headers = { + ...opts.headers, + 'if-modified-since': new Date(result.cachedAt).toUTCString() + } + + if (result.etag) { + headers['if-none-match'] = result.etag + } + + if (result.vary) { + headers = { + ...headers, + ...result.vary + } + } + + // We need to revalidate the response + return dispatch( + { + ...opts, + headers + }, + new CacheRevalidationHandler( + (success, context) => { + if (success) { + sendCachedValue(handler, opts, result, age, context, true) + } else if (util.isStream(result.body)) { + result.body.on('error', () => {}).destroy() + } + }, + new CacheHandler(globalOpts, cacheKey, handler), + withinStaleIfErrorThreshold + ) + ) + } + + // Dump request body. + if (util.isStream(opts.body)) { + opts.body.on('error', () => {}).destroy() + } + + sendCachedValue(handler, opts, result, age, null, false) +} + +/** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheOptions} [opts] + * @returns {import('../../types/dispatcher.d.ts').default.DispatcherComposeInterceptor} + */ +module.exports = (opts = {}) => { + const { + store = new MemoryCacheStore(), + methods = ['GET'], + cacheByDefault = undefined, + type = 'shared' + } = opts + + if (typeof opts !== 'object' || opts === null) { + throw new TypeError(`expected type of opts to be an Object, got ${opts === null ? 'null' : typeof opts}`) + } + + assertCacheStore(store, 'opts.store') + assertCacheMethods(methods, 'opts.methods') + + if (typeof cacheByDefault !== 'undefined' && typeof cacheByDefault !== 'number') { + throw new TypeError(`expected opts.cacheByDefault to be number or undefined, got ${typeof cacheByDefault}`) + } + + if (typeof type !== 'undefined' && type !== 'shared' && type !== 'private') { + throw new TypeError(`expected opts.type to be shared, private, or undefined, got ${typeof type}`) + } + + const globalOpts = { + store, + methods, + cacheByDefault, + type + } + + const safeMethodsToNotCache = util.safeHTTPMethods.filter(method => methods.includes(method) === false) + + return dispatch => { + return (opts, handler) => { + if (!opts.origin || safeMethodsToNotCache.includes(opts.method)) { + // Not a method we want to cache or we don't have the origin, skip + return dispatch(opts, handler) + } + + opts = { + ...opts, + headers: normalizeHeaders(opts) + } + + const reqCacheControl = opts.headers?.['cache-control'] + ? parseCacheControlHeader(opts.headers['cache-control']) + : undefined + + if (reqCacheControl?.['no-store']) { + return dispatch(opts, handler) + } + + /** + * @type {import('../../types/cache-interceptor.d.ts').default.CacheKey} + */ + const cacheKey = makeCacheKey(opts) + const result = store.get(cacheKey) + + if (result && typeof result.then === 'function') { + result.then(result => { + handleResult(dispatch, + globalOpts, + cacheKey, + handler, + opts, + reqCacheControl, + result + ) + }) + } else { + handleResult( + dispatch, + globalOpts, + cacheKey, + handler, + opts, + reqCacheControl, + result + ) + } + + return true + } + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/interceptor/decompress.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/interceptor/decompress.js new file mode 100644 index 0000000000000000000000000000000000000000..847aefdbf62b5f6b5b8cf2e734be073d2a459887 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/interceptor/decompress.js @@ -0,0 +1,253 @@ +'use strict' + +const { createInflate, createGunzip, createBrotliDecompress, createZstdDecompress } = require('node:zlib') +const { pipeline } = require('node:stream') +const DecoratorHandler = require('../handler/decorator-handler') + +/** @typedef {import('node:stream').Transform} Transform */ +/** @typedef {import('node:stream').Transform} Controller */ +/** @typedef {Transform&import('node:zlib').Zlib} DecompressorStream */ + +/** @type {Record DecompressorStream>} */ +const supportedEncodings = { + gzip: createGunzip, + 'x-gzip': createGunzip, + br: createBrotliDecompress, + deflate: createInflate, + compress: createInflate, + 'x-compress': createInflate, + ...(createZstdDecompress ? { zstd: createZstdDecompress } : {}) +} + +const defaultSkipStatusCodes = /** @type {const} */ ([204, 304]) + +let warningEmitted = /** @type {boolean} */ (false) + +/** + * @typedef {Object} DecompressHandlerOptions + * @property {number[]|Readonly} [skipStatusCodes=[204, 304]] - List of status codes to skip decompression for + * @property {boolean} [skipErrorResponses] - Whether to skip decompression for error responses (status codes >= 400) + */ + +class DecompressHandler extends DecoratorHandler { + /** @type {Transform[]} */ + #decompressors = [] + /** @type {NodeJS.WritableStream&NodeJS.ReadableStream|null} */ + #pipelineStream + /** @type {Readonly} */ + #skipStatusCodes + /** @type {boolean} */ + #skipErrorResponses + + constructor (handler, { skipStatusCodes = defaultSkipStatusCodes, skipErrorResponses = true } = {}) { + super(handler) + this.#skipStatusCodes = skipStatusCodes + this.#skipErrorResponses = skipErrorResponses + } + + /** + * Determines if decompression should be skipped based on encoding and status code + * @param {string} contentEncoding - Content-Encoding header value + * @param {number} statusCode - HTTP status code of the response + * @returns {boolean} - True if decompression should be skipped + */ + #shouldSkipDecompression (contentEncoding, statusCode) { + if (!contentEncoding || statusCode < 200) return true + if (this.#skipStatusCodes.includes(statusCode)) return true + if (this.#skipErrorResponses && statusCode >= 400) return true + return false + } + + /** + * Creates a chain of decompressors for multiple content encodings + * + * @param {string} encodings - Comma-separated list of content encodings + * @returns {Array} - Array of decompressor streams + */ + #createDecompressionChain (encodings) { + const parts = encodings.split(',') + + /** @type {DecompressorStream[]} */ + const decompressors = [] + + for (let i = parts.length - 1; i >= 0; i--) { + const encoding = parts[i].trim() + if (!encoding) continue + + if (!supportedEncodings[encoding]) { + decompressors.length = 0 // Clear if unsupported encoding + return decompressors // Unsupported encoding + } + + decompressors.push(supportedEncodings[encoding]()) + } + + return decompressors + } + + /** + * Sets up event handlers for a decompressor stream using readable events + * @param {DecompressorStream} decompressor - The decompressor stream + * @param {Controller} controller - The controller to coordinate with + * @returns {void} + */ + #setupDecompressorEvents (decompressor, controller) { + decompressor.on('readable', () => { + let chunk + while ((chunk = decompressor.read()) !== null) { + const result = super.onResponseData(controller, chunk) + if (result === false) { + break + } + } + }) + + decompressor.on('error', (error) => { + super.onResponseError(controller, error) + }) + } + + /** + * Sets up event handling for a single decompressor + * @param {Controller} controller - The controller to handle events + * @returns {void} + */ + #setupSingleDecompressor (controller) { + const decompressor = this.#decompressors[0] + this.#setupDecompressorEvents(decompressor, controller) + + decompressor.on('end', () => { + super.onResponseEnd(controller, {}) + }) + } + + /** + * Sets up event handling for multiple chained decompressors using pipeline + * @param {Controller} controller - The controller to handle events + * @returns {void} + */ + #setupMultipleDecompressors (controller) { + const lastDecompressor = this.#decompressors[this.#decompressors.length - 1] + this.#setupDecompressorEvents(lastDecompressor, controller) + + this.#pipelineStream = pipeline(this.#decompressors, (err) => { + if (err) { + super.onResponseError(controller, err) + return + } + super.onResponseEnd(controller, {}) + }) + } + + /** + * Cleans up decompressor references to prevent memory leaks + * @returns {void} + */ + #cleanupDecompressors () { + this.#decompressors.length = 0 + this.#pipelineStream = null + } + + /** + * @param {Controller} controller + * @param {number} statusCode + * @param {Record} headers + * @param {string} statusMessage + * @returns {void} + */ + onResponseStart (controller, statusCode, headers, statusMessage) { + const contentEncoding = headers['content-encoding'] + + // If content encoding is not supported or status code is in skip list + if (this.#shouldSkipDecompression(contentEncoding, statusCode)) { + return super.onResponseStart(controller, statusCode, headers, statusMessage) + } + + const decompressors = this.#createDecompressionChain(contentEncoding.toLowerCase()) + + if (decompressors.length === 0) { + this.#cleanupDecompressors() + return super.onResponseStart(controller, statusCode, headers, statusMessage) + } + + this.#decompressors = decompressors + + // Remove compression headers since we're decompressing + const { 'content-encoding': _, 'content-length': __, ...newHeaders } = headers + + if (this.#decompressors.length === 1) { + this.#setupSingleDecompressor(controller) + } else { + this.#setupMultipleDecompressors(controller) + } + + super.onResponseStart(controller, statusCode, newHeaders, statusMessage) + } + + /** + * @param {Controller} controller + * @param {Buffer} chunk + * @returns {void} + */ + onResponseData (controller, chunk) { + if (this.#decompressors.length > 0) { + this.#decompressors[0].write(chunk) + return + } + super.onResponseData(controller, chunk) + } + + /** + * @param {Controller} controller + * @param {Record | undefined} trailers + * @returns {void} + */ + onResponseEnd (controller, trailers) { + if (this.#decompressors.length > 0) { + this.#decompressors[0].end() + this.#cleanupDecompressors() + return + } + super.onResponseEnd(controller, trailers) + } + + /** + * @param {Controller} controller + * @param {Error} err + * @returns {void} + */ + onResponseError (controller, err) { + if (this.#decompressors.length > 0) { + for (const decompressor of this.#decompressors) { + decompressor.destroy(err) + } + this.#cleanupDecompressors() + } + super.onResponseError(controller, err) + } +} + +/** + * Creates a decompression interceptor for HTTP responses + * @param {DecompressHandlerOptions} [options] - Options for the interceptor + * @returns {Function} - Interceptor function + */ +function createDecompressInterceptor (options = {}) { + // Emit experimental warning only once + if (!warningEmitted) { + process.emitWarning( + 'DecompressInterceptor is experimental and subject to change', + 'ExperimentalWarning' + ) + warningEmitted = true + } + + return (dispatch) => { + return (opts, handler) => { + const decompressHandler = new DecompressHandler(handler, options) + return dispatch(opts, decompressHandler) + } + } +} + +module.exports = createDecompressInterceptor diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/interceptor/dns.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/interceptor/dns.js new file mode 100644 index 0000000000000000000000000000000000000000..3828760714350f4e1733853f16a2c0d751d3389d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/interceptor/dns.js @@ -0,0 +1,432 @@ +'use strict' +const { isIP } = require('node:net') +const { lookup } = require('node:dns') +const DecoratorHandler = require('../handler/decorator-handler') +const { InvalidArgumentError, InformationalError } = require('../core/errors') +const maxInt = Math.pow(2, 31) - 1 + +class DNSInstance { + #maxTTL = 0 + #maxItems = 0 + #records = new Map() + dualStack = true + affinity = null + lookup = null + pick = null + + constructor (opts) { + this.#maxTTL = opts.maxTTL + this.#maxItems = opts.maxItems + this.dualStack = opts.dualStack + this.affinity = opts.affinity + this.lookup = opts.lookup ?? this.#defaultLookup + this.pick = opts.pick ?? this.#defaultPick + } + + get full () { + return this.#records.size === this.#maxItems + } + + runLookup (origin, opts, cb) { + const ips = this.#records.get(origin.hostname) + + // If full, we just return the origin + if (ips == null && this.full) { + cb(null, origin) + return + } + + const newOpts = { + affinity: this.affinity, + dualStack: this.dualStack, + lookup: this.lookup, + pick: this.pick, + ...opts.dns, + maxTTL: this.#maxTTL, + maxItems: this.#maxItems + } + + // If no IPs we lookup + if (ips == null) { + this.lookup(origin, newOpts, (err, addresses) => { + if (err || addresses == null || addresses.length === 0) { + cb(err ?? new InformationalError('No DNS entries found')) + return + } + + this.setRecords(origin, addresses) + const records = this.#records.get(origin.hostname) + + const ip = this.pick( + origin, + records, + newOpts.affinity + ) + + let port + if (typeof ip.port === 'number') { + port = `:${ip.port}` + } else if (origin.port !== '') { + port = `:${origin.port}` + } else { + port = '' + } + + cb( + null, + new URL(`${origin.protocol}//${ + ip.family === 6 ? `[${ip.address}]` : ip.address + }${port}`) + ) + }) + } else { + // If there's IPs we pick + const ip = this.pick( + origin, + ips, + newOpts.affinity + ) + + // If no IPs we lookup - deleting old records + if (ip == null) { + this.#records.delete(origin.hostname) + this.runLookup(origin, opts, cb) + return + } + + let port + if (typeof ip.port === 'number') { + port = `:${ip.port}` + } else if (origin.port !== '') { + port = `:${origin.port}` + } else { + port = '' + } + + cb( + null, + new URL(`${origin.protocol}//${ + ip.family === 6 ? `[${ip.address}]` : ip.address + }${port}`) + ) + } + } + + #defaultLookup (origin, opts, cb) { + lookup( + origin.hostname, + { + all: true, + family: this.dualStack === false ? this.affinity : 0, + order: 'ipv4first' + }, + (err, addresses) => { + if (err) { + return cb(err) + } + + const results = new Map() + + for (const addr of addresses) { + // On linux we found duplicates, we attempt to remove them with + // the latest record + results.set(`${addr.address}:${addr.family}`, addr) + } + + cb(null, results.values()) + } + ) + } + + #defaultPick (origin, hostnameRecords, affinity) { + let ip = null + const { records, offset } = hostnameRecords + + let family + if (this.dualStack) { + if (affinity == null) { + // Balance between ip families + if (offset == null || offset === maxInt) { + hostnameRecords.offset = 0 + affinity = 4 + } else { + hostnameRecords.offset++ + affinity = (hostnameRecords.offset & 1) === 1 ? 6 : 4 + } + } + + if (records[affinity] != null && records[affinity].ips.length > 0) { + family = records[affinity] + } else { + family = records[affinity === 4 ? 6 : 4] + } + } else { + family = records[affinity] + } + + // If no IPs we return null + if (family == null || family.ips.length === 0) { + return ip + } + + if (family.offset == null || family.offset === maxInt) { + family.offset = 0 + } else { + family.offset++ + } + + const position = family.offset % family.ips.length + ip = family.ips[position] ?? null + + if (ip == null) { + return ip + } + + if (Date.now() - ip.timestamp > ip.ttl) { // record TTL is already in ms + // We delete expired records + // It is possible that they have different TTL, so we manage them individually + family.ips.splice(position, 1) + return this.pick(origin, hostnameRecords, affinity) + } + + return ip + } + + pickFamily (origin, ipFamily) { + const records = this.#records.get(origin.hostname)?.records + if (!records) { + return null + } + + const family = records[ipFamily] + if (!family) { + return null + } + + if (family.offset == null || family.offset === maxInt) { + family.offset = 0 + } else { + family.offset++ + } + + const position = family.offset % family.ips.length + const ip = family.ips[position] ?? null + if (ip == null) { + return ip + } + + if (Date.now() - ip.timestamp > ip.ttl) { // record TTL is already in ms + // We delete expired records + // It is possible that they have different TTL, so we manage them individually + family.ips.splice(position, 1) + } + + return ip + } + + setRecords (origin, addresses) { + const timestamp = Date.now() + const records = { records: { 4: null, 6: null } } + for (const record of addresses) { + record.timestamp = timestamp + if (typeof record.ttl === 'number') { + // The record TTL is expected to be in ms + record.ttl = Math.min(record.ttl, this.#maxTTL) + } else { + record.ttl = this.#maxTTL + } + + const familyRecords = records.records[record.family] ?? { ips: [] } + + familyRecords.ips.push(record) + records.records[record.family] = familyRecords + } + + this.#records.set(origin.hostname, records) + } + + deleteRecords (origin) { + this.#records.delete(origin.hostname) + } + + getHandler (meta, opts) { + return new DNSDispatchHandler(this, meta, opts) + } +} + +class DNSDispatchHandler extends DecoratorHandler { + #state = null + #opts = null + #dispatch = null + #origin = null + #controller = null + #newOrigin = null + #firstTry = true + + constructor (state, { origin, handler, dispatch, newOrigin }, opts) { + super(handler) + this.#origin = origin + this.#newOrigin = newOrigin + this.#opts = { ...opts } + this.#state = state + this.#dispatch = dispatch + } + + onResponseError (controller, err) { + switch (err.code) { + case 'ETIMEDOUT': + case 'ECONNREFUSED': { + if (this.#state.dualStack) { + if (!this.#firstTry) { + super.onResponseError(controller, err) + return + } + this.#firstTry = false + + // Pick an ip address from the other family + const otherFamily = this.#newOrigin.hostname[0] === '[' ? 4 : 6 + const ip = this.#state.pickFamily(this.#origin, otherFamily) + if (ip == null) { + super.onResponseError(controller, err) + return + } + + let port + if (typeof ip.port === 'number') { + port = `:${ip.port}` + } else if (this.#origin.port !== '') { + port = `:${this.#origin.port}` + } else { + port = '' + } + + const dispatchOpts = { + ...this.#opts, + origin: `${this.#origin.protocol}//${ + ip.family === 6 ? `[${ip.address}]` : ip.address + }${port}` + } + this.#dispatch(dispatchOpts, this) + return + } + + // if dual-stack disabled, we error out + super.onResponseError(controller, err) + break + } + case 'ENOTFOUND': + this.#state.deleteRecords(this.#origin) + super.onResponseError(controller, err) + break + default: + super.onResponseError(controller, err) + break + } + } +} + +module.exports = interceptorOpts => { + if ( + interceptorOpts?.maxTTL != null && + (typeof interceptorOpts?.maxTTL !== 'number' || interceptorOpts?.maxTTL < 0) + ) { + throw new InvalidArgumentError('Invalid maxTTL. Must be a positive number') + } + + if ( + interceptorOpts?.maxItems != null && + (typeof interceptorOpts?.maxItems !== 'number' || + interceptorOpts?.maxItems < 1) + ) { + throw new InvalidArgumentError( + 'Invalid maxItems. Must be a positive number and greater than zero' + ) + } + + if ( + interceptorOpts?.affinity != null && + interceptorOpts?.affinity !== 4 && + interceptorOpts?.affinity !== 6 + ) { + throw new InvalidArgumentError('Invalid affinity. Must be either 4 or 6') + } + + if ( + interceptorOpts?.dualStack != null && + typeof interceptorOpts?.dualStack !== 'boolean' + ) { + throw new InvalidArgumentError('Invalid dualStack. Must be a boolean') + } + + if ( + interceptorOpts?.lookup != null && + typeof interceptorOpts?.lookup !== 'function' + ) { + throw new InvalidArgumentError('Invalid lookup. Must be a function') + } + + if ( + interceptorOpts?.pick != null && + typeof interceptorOpts?.pick !== 'function' + ) { + throw new InvalidArgumentError('Invalid pick. Must be a function') + } + + const dualStack = interceptorOpts?.dualStack ?? true + let affinity + if (dualStack) { + affinity = interceptorOpts?.affinity ?? null + } else { + affinity = interceptorOpts?.affinity ?? 4 + } + + const opts = { + maxTTL: interceptorOpts?.maxTTL ?? 10e3, // Expressed in ms + lookup: interceptorOpts?.lookup ?? null, + pick: interceptorOpts?.pick ?? null, + dualStack, + affinity, + maxItems: interceptorOpts?.maxItems ?? Infinity + } + + const instance = new DNSInstance(opts) + + return dispatch => { + return function dnsInterceptor (origDispatchOpts, handler) { + const origin = + origDispatchOpts.origin.constructor === URL + ? origDispatchOpts.origin + : new URL(origDispatchOpts.origin) + + if (isIP(origin.hostname) !== 0) { + return dispatch(origDispatchOpts, handler) + } + + instance.runLookup(origin, origDispatchOpts, (err, newOrigin) => { + if (err) { + return handler.onResponseError(null, err) + } + + const dispatchOpts = { + ...origDispatchOpts, + servername: origin.hostname, // For SNI on TLS + origin: newOrigin.origin, + headers: { + host: origin.host, + ...origDispatchOpts.headers + } + } + + dispatch( + dispatchOpts, + instance.getHandler( + { origin, dispatch, handler, newOrigin }, + origDispatchOpts + ) + ) + }) + + return true + } + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/interceptor/dump.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/interceptor/dump.js new file mode 100644 index 0000000000000000000000000000000000000000..4810a09f38242492cebd0178a7f2b2b35004b846 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/interceptor/dump.js @@ -0,0 +1,112 @@ +'use strict' + +const { InvalidArgumentError, RequestAbortedError } = require('../core/errors') +const DecoratorHandler = require('../handler/decorator-handler') + +class DumpHandler extends DecoratorHandler { + #maxSize = 1024 * 1024 + #dumped = false + #size = 0 + #controller = null + aborted = false + reason = false + + constructor ({ maxSize, signal }, handler) { + if (maxSize != null && (!Number.isFinite(maxSize) || maxSize < 1)) { + throw new InvalidArgumentError('maxSize must be a number greater than 0') + } + + super(handler) + + this.#maxSize = maxSize ?? this.#maxSize + // this.#handler = handler + } + + #abort (reason) { + this.aborted = true + this.reason = reason + } + + onRequestStart (controller, context) { + controller.abort = this.#abort.bind(this) + this.#controller = controller + + return super.onRequestStart(controller, context) + } + + onResponseStart (controller, statusCode, headers, statusMessage) { + const contentLength = headers['content-length'] + + if (contentLength != null && contentLength > this.#maxSize) { + throw new RequestAbortedError( + `Response size (${contentLength}) larger than maxSize (${ + this.#maxSize + })` + ) + } + + if (this.aborted === true) { + return true + } + + return super.onResponseStart(controller, statusCode, headers, statusMessage) + } + + onResponseError (controller, err) { + if (this.#dumped) { + return + } + + // On network errors before connect, controller will be null + err = this.#controller?.reason ?? err + + super.onResponseError(controller, err) + } + + onResponseData (controller, chunk) { + this.#size = this.#size + chunk.length + + if (this.#size >= this.#maxSize) { + this.#dumped = true + + if (this.aborted === true) { + super.onResponseError(controller, this.reason) + } else { + super.onResponseEnd(controller, {}) + } + } + + return true + } + + onResponseEnd (controller, trailers) { + if (this.#dumped) { + return + } + + if (this.#controller.aborted === true) { + super.onResponseError(controller, this.reason) + return + } + + super.onResponseEnd(controller, trailers) + } +} + +function createDumpInterceptor ( + { maxSize: defaultMaxSize } = { + maxSize: 1024 * 1024 + } +) { + return dispatch => { + return function Intercept (opts, handler) { + const { dumpMaxSize = defaultMaxSize } = opts + + const dumpHandler = new DumpHandler({ maxSize: dumpMaxSize, signal: opts.signal }, handler) + + return dispatch(opts, dumpHandler) + } + } +} + +module.exports = createDumpInterceptor diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/interceptor/redirect.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/interceptor/redirect.js new file mode 100644 index 0000000000000000000000000000000000000000..b7df180433e39e2d046dc542626d720d9decbc40 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/interceptor/redirect.js @@ -0,0 +1,21 @@ +'use strict' + +const RedirectHandler = require('../handler/redirect-handler') + +function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections } = {}) { + return (dispatch) => { + return function Intercept (opts, handler) { + const { maxRedirections = defaultMaxRedirections, ...rest } = opts + + if (maxRedirections == null || maxRedirections === 0) { + return dispatch(opts, handler) + } + + const dispatchOpts = { ...rest } // Stop sub dispatcher from also redirecting. + const redirectHandler = new RedirectHandler(dispatch, maxRedirections, dispatchOpts, handler) + return dispatch(dispatchOpts, redirectHandler) + } + } +} + +module.exports = createRedirectInterceptor diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/interceptor/response-error.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/interceptor/response-error.js new file mode 100644 index 0000000000000000000000000000000000000000..a8105aa1437feeec76d5d21c74af9ab7028232f6 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/interceptor/response-error.js @@ -0,0 +1,95 @@ +'use strict' + +// const { parseHeaders } = require('../core/util') +const DecoratorHandler = require('../handler/decorator-handler') +const { ResponseError } = require('../core/errors') + +class ResponseErrorHandler extends DecoratorHandler { + #statusCode + #contentType + #decoder + #headers + #body + + constructor (_opts, { handler }) { + super(handler) + } + + #checkContentType (contentType) { + return (this.#contentType ?? '').indexOf(contentType) === 0 + } + + onRequestStart (controller, context) { + this.#statusCode = 0 + this.#contentType = null + this.#decoder = null + this.#headers = null + this.#body = '' + + return super.onRequestStart(controller, context) + } + + onResponseStart (controller, statusCode, headers, statusMessage) { + this.#statusCode = statusCode + this.#headers = headers + this.#contentType = headers['content-type'] + + if (this.#statusCode < 400) { + return super.onResponseStart(controller, statusCode, headers, statusMessage) + } + + if (this.#checkContentType('application/json') || this.#checkContentType('text/plain')) { + this.#decoder = new TextDecoder('utf-8') + } + } + + onResponseData (controller, chunk) { + if (this.#statusCode < 400) { + return super.onResponseData(controller, chunk) + } + + this.#body += this.#decoder?.decode(chunk, { stream: true }) ?? '' + } + + onResponseEnd (controller, trailers) { + if (this.#statusCode >= 400) { + this.#body += this.#decoder?.decode(undefined, { stream: false }) ?? '' + + if (this.#checkContentType('application/json')) { + try { + this.#body = JSON.parse(this.#body) + } catch { + // Do nothing... + } + } + + let err + const stackTraceLimit = Error.stackTraceLimit + Error.stackTraceLimit = 0 + try { + err = new ResponseError('Response Error', this.#statusCode, { + body: this.#body, + headers: this.#headers + }) + } finally { + Error.stackTraceLimit = stackTraceLimit + } + + super.onResponseError(controller, err) + } else { + super.onResponseEnd(controller, trailers) + } + } + + onResponseError (controller, err) { + super.onResponseError(controller, err) + } +} + +module.exports = () => { + return (dispatch) => { + return function Intercept (opts, handler) { + return dispatch(opts, new ResponseErrorHandler(opts, { handler })) + } + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/interceptor/retry.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/interceptor/retry.js new file mode 100644 index 0000000000000000000000000000000000000000..1c16fd845a9a96f0df04307e476ba48b951c5373 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/interceptor/retry.js @@ -0,0 +1,19 @@ +'use strict' +const RetryHandler = require('../handler/retry-handler') + +module.exports = globalOpts => { + return dispatch => { + return function retryInterceptor (opts, handler) { + return dispatch( + opts, + new RetryHandler( + { ...opts, retryOptions: { ...globalOpts, ...opts.retryOptions } }, + { + handler, + dispatch + } + ) + ) + } + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/llhttp/.gitkeep b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/llhttp/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/llhttp/constants.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/llhttp/constants.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..def2436cc4e1088dbce67450e08f27fbd2957f7e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/llhttp/constants.d.ts @@ -0,0 +1,195 @@ +export type IntDict = Record; +export declare const ERROR: IntDict; +export declare const TYPE: IntDict; +export declare const FLAGS: IntDict; +export declare const LENIENT_FLAGS: IntDict; +export declare const METHODS: IntDict; +export declare const STATUSES: IntDict; +export declare const FINISH: IntDict; +export declare const HEADER_STATE: IntDict; +export declare const METHODS_HTTP: number[]; +export declare const METHODS_ICE: number[]; +export declare const METHODS_RTSP: number[]; +export declare const METHOD_MAP: IntDict; +export declare const H_METHOD_MAP: { + [k: string]: number; +}; +export declare const STATUSES_HTTP: number[]; +export type CharList = (string | number)[]; +export declare const ALPHA: CharList; +export declare const NUM_MAP: { + 0: number; + 1: number; + 2: number; + 3: number; + 4: number; + 5: number; + 6: number; + 7: number; + 8: number; + 9: number; +}; +export declare const HEX_MAP: { + 0: number; + 1: number; + 2: number; + 3: number; + 4: number; + 5: number; + 6: number; + 7: number; + 8: number; + 9: number; + A: number; + B: number; + C: number; + D: number; + E: number; + F: number; + a: number; + b: number; + c: number; + d: number; + e: number; + f: number; +}; +export declare const NUM: CharList; +export declare const ALPHANUM: CharList; +export declare const MARK: CharList; +export declare const USERINFO_CHARS: CharList; +export declare const URL_CHAR: CharList; +export declare const HEX: CharList; +export declare const TOKEN: CharList; +export declare const HEADER_CHARS: CharList; +export declare const CONNECTION_TOKEN_CHARS: CharList; +export declare const QUOTED_STRING: CharList; +export declare const HTAB_SP_VCHAR_OBS_TEXT: CharList; +export declare const MAJOR: { + 0: number; + 1: number; + 2: number; + 3: number; + 4: number; + 5: number; + 6: number; + 7: number; + 8: number; + 9: number; +}; +export declare const MINOR: { + 0: number; + 1: number; + 2: number; + 3: number; + 4: number; + 5: number; + 6: number; + 7: number; + 8: number; + 9: number; +}; +export declare const SPECIAL_HEADERS: { + connection: number; + 'content-length': number; + 'proxy-connection': number; + 'transfer-encoding': number; + upgrade: number; +}; +declare const _default: { + ERROR: IntDict; + TYPE: IntDict; + FLAGS: IntDict; + LENIENT_FLAGS: IntDict; + METHODS: IntDict; + STATUSES: IntDict; + FINISH: IntDict; + HEADER_STATE: IntDict; + ALPHA: CharList; + NUM_MAP: { + 0: number; + 1: number; + 2: number; + 3: number; + 4: number; + 5: number; + 6: number; + 7: number; + 8: number; + 9: number; + }; + HEX_MAP: { + 0: number; + 1: number; + 2: number; + 3: number; + 4: number; + 5: number; + 6: number; + 7: number; + 8: number; + 9: number; + A: number; + B: number; + C: number; + D: number; + E: number; + F: number; + a: number; + b: number; + c: number; + d: number; + e: number; + f: number; + }; + NUM: CharList; + ALPHANUM: CharList; + MARK: CharList; + USERINFO_CHARS: CharList; + URL_CHAR: CharList; + HEX: CharList; + TOKEN: CharList; + HEADER_CHARS: CharList; + CONNECTION_TOKEN_CHARS: CharList; + QUOTED_STRING: CharList; + HTAB_SP_VCHAR_OBS_TEXT: CharList; + MAJOR: { + 0: number; + 1: number; + 2: number; + 3: number; + 4: number; + 5: number; + 6: number; + 7: number; + 8: number; + 9: number; + }; + MINOR: { + 0: number; + 1: number; + 2: number; + 3: number; + 4: number; + 5: number; + 6: number; + 7: number; + 8: number; + 9: number; + }; + SPECIAL_HEADERS: { + connection: number; + 'content-length': number; + 'proxy-connection': number; + 'transfer-encoding': number; + upgrade: number; + }; + METHODS_HTTP: number[]; + METHODS_ICE: number[]; + METHODS_RTSP: number[]; + METHOD_MAP: IntDict; + H_METHOD_MAP: { + [k: string]: number; + }; + STATUSES_HTTP: number[]; +}; +export default _default; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/llhttp/constants.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/llhttp/constants.js new file mode 100644 index 0000000000000000000000000000000000000000..8b88dfdf62c17b265d7a053abd20167f6c413b26 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/llhttp/constants.js @@ -0,0 +1,531 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SPECIAL_HEADERS = exports.MINOR = exports.MAJOR = exports.HTAB_SP_VCHAR_OBS_TEXT = exports.QUOTED_STRING = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.HEX = exports.URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.STATUSES_HTTP = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.HEADER_STATE = exports.FINISH = exports.STATUSES = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0; +const utils_1 = require("./utils"); +// Emums +exports.ERROR = { + OK: 0, + INTERNAL: 1, + STRICT: 2, + CR_EXPECTED: 25, + LF_EXPECTED: 3, + UNEXPECTED_CONTENT_LENGTH: 4, + UNEXPECTED_SPACE: 30, + CLOSED_CONNECTION: 5, + INVALID_METHOD: 6, + INVALID_URL: 7, + INVALID_CONSTANT: 8, + INVALID_VERSION: 9, + INVALID_HEADER_TOKEN: 10, + INVALID_CONTENT_LENGTH: 11, + INVALID_CHUNK_SIZE: 12, + INVALID_STATUS: 13, + INVALID_EOF_STATE: 14, + INVALID_TRANSFER_ENCODING: 15, + CB_MESSAGE_BEGIN: 16, + CB_HEADERS_COMPLETE: 17, + CB_MESSAGE_COMPLETE: 18, + CB_CHUNK_HEADER: 19, + CB_CHUNK_COMPLETE: 20, + PAUSED: 21, + PAUSED_UPGRADE: 22, + PAUSED_H2_UPGRADE: 23, + USER: 24, + CB_URL_COMPLETE: 26, + CB_STATUS_COMPLETE: 27, + CB_METHOD_COMPLETE: 32, + CB_VERSION_COMPLETE: 33, + CB_HEADER_FIELD_COMPLETE: 28, + CB_HEADER_VALUE_COMPLETE: 29, + CB_CHUNK_EXTENSION_NAME_COMPLETE: 34, + CB_CHUNK_EXTENSION_VALUE_COMPLETE: 35, + CB_RESET: 31, + CB_PROTOCOL_COMPLETE: 38, +}; +exports.TYPE = { + BOTH: 0, // default + REQUEST: 1, + RESPONSE: 2, +}; +exports.FLAGS = { + CONNECTION_KEEP_ALIVE: 1 << 0, + CONNECTION_CLOSE: 1 << 1, + CONNECTION_UPGRADE: 1 << 2, + CHUNKED: 1 << 3, + UPGRADE: 1 << 4, + CONTENT_LENGTH: 1 << 5, + SKIPBODY: 1 << 6, + TRAILING: 1 << 7, + // 1 << 8 is unused + TRANSFER_ENCODING: 1 << 9, +}; +exports.LENIENT_FLAGS = { + HEADERS: 1 << 0, + CHUNKED_LENGTH: 1 << 1, + KEEP_ALIVE: 1 << 2, + TRANSFER_ENCODING: 1 << 3, + VERSION: 1 << 4, + DATA_AFTER_CLOSE: 1 << 5, + OPTIONAL_LF_AFTER_CR: 1 << 6, + OPTIONAL_CRLF_AFTER_CHUNK: 1 << 7, + OPTIONAL_CR_BEFORE_LF: 1 << 8, + SPACES_AFTER_CHUNK_SIZE: 1 << 9, +}; +exports.METHODS = { + 'DELETE': 0, + 'GET': 1, + 'HEAD': 2, + 'POST': 3, + 'PUT': 4, + /* pathological */ + 'CONNECT': 5, + 'OPTIONS': 6, + 'TRACE': 7, + /* WebDAV */ + 'COPY': 8, + 'LOCK': 9, + 'MKCOL': 10, + 'MOVE': 11, + 'PROPFIND': 12, + 'PROPPATCH': 13, + 'SEARCH': 14, + 'UNLOCK': 15, + 'BIND': 16, + 'REBIND': 17, + 'UNBIND': 18, + 'ACL': 19, + /* subversion */ + 'REPORT': 20, + 'MKACTIVITY': 21, + 'CHECKOUT': 22, + 'MERGE': 23, + /* upnp */ + 'M-SEARCH': 24, + 'NOTIFY': 25, + 'SUBSCRIBE': 26, + 'UNSUBSCRIBE': 27, + /* RFC-5789 */ + 'PATCH': 28, + 'PURGE': 29, + /* CalDAV */ + 'MKCALENDAR': 30, + /* RFC-2068, section 19.6.1.2 */ + 'LINK': 31, + 'UNLINK': 32, + /* icecast */ + 'SOURCE': 33, + /* RFC-7540, section 11.6 */ + 'PRI': 34, + /* RFC-2326 RTSP */ + 'DESCRIBE': 35, + 'ANNOUNCE': 36, + 'SETUP': 37, + 'PLAY': 38, + 'PAUSE': 39, + 'TEARDOWN': 40, + 'GET_PARAMETER': 41, + 'SET_PARAMETER': 42, + 'REDIRECT': 43, + 'RECORD': 44, + /* RAOP */ + 'FLUSH': 45, + /* DRAFT https://www.ietf.org/archive/id/draft-ietf-httpbis-safe-method-w-body-02.html */ + 'QUERY': 46, +}; +exports.STATUSES = { + CONTINUE: 100, + SWITCHING_PROTOCOLS: 101, + PROCESSING: 102, + EARLY_HINTS: 103, + RESPONSE_IS_STALE: 110, // Unofficial + REVALIDATION_FAILED: 111, // Unofficial + DISCONNECTED_OPERATION: 112, // Unofficial + HEURISTIC_EXPIRATION: 113, // Unofficial + MISCELLANEOUS_WARNING: 199, // Unofficial + OK: 200, + CREATED: 201, + ACCEPTED: 202, + NON_AUTHORITATIVE_INFORMATION: 203, + NO_CONTENT: 204, + RESET_CONTENT: 205, + PARTIAL_CONTENT: 206, + MULTI_STATUS: 207, + ALREADY_REPORTED: 208, + TRANSFORMATION_APPLIED: 214, // Unofficial + IM_USED: 226, + MISCELLANEOUS_PERSISTENT_WARNING: 299, // Unofficial + MULTIPLE_CHOICES: 300, + MOVED_PERMANENTLY: 301, + FOUND: 302, + SEE_OTHER: 303, + NOT_MODIFIED: 304, + USE_PROXY: 305, + SWITCH_PROXY: 306, // No longer used + TEMPORARY_REDIRECT: 307, + PERMANENT_REDIRECT: 308, + BAD_REQUEST: 400, + UNAUTHORIZED: 401, + PAYMENT_REQUIRED: 402, + FORBIDDEN: 403, + NOT_FOUND: 404, + METHOD_NOT_ALLOWED: 405, + NOT_ACCEPTABLE: 406, + PROXY_AUTHENTICATION_REQUIRED: 407, + REQUEST_TIMEOUT: 408, + CONFLICT: 409, + GONE: 410, + LENGTH_REQUIRED: 411, + PRECONDITION_FAILED: 412, + PAYLOAD_TOO_LARGE: 413, + URI_TOO_LONG: 414, + UNSUPPORTED_MEDIA_TYPE: 415, + RANGE_NOT_SATISFIABLE: 416, + EXPECTATION_FAILED: 417, + IM_A_TEAPOT: 418, + PAGE_EXPIRED: 419, // Unofficial + ENHANCE_YOUR_CALM: 420, // Unofficial + MISDIRECTED_REQUEST: 421, + UNPROCESSABLE_ENTITY: 422, + LOCKED: 423, + FAILED_DEPENDENCY: 424, + TOO_EARLY: 425, + UPGRADE_REQUIRED: 426, + PRECONDITION_REQUIRED: 428, + TOO_MANY_REQUESTS: 429, + REQUEST_HEADER_FIELDS_TOO_LARGE_UNOFFICIAL: 430, // Unofficial + REQUEST_HEADER_FIELDS_TOO_LARGE: 431, + LOGIN_TIMEOUT: 440, // Unofficial + NO_RESPONSE: 444, // Unofficial + RETRY_WITH: 449, // Unofficial + BLOCKED_BY_PARENTAL_CONTROL: 450, // Unofficial + UNAVAILABLE_FOR_LEGAL_REASONS: 451, + CLIENT_CLOSED_LOAD_BALANCED_REQUEST: 460, // Unofficial + INVALID_X_FORWARDED_FOR: 463, // Unofficial + REQUEST_HEADER_TOO_LARGE: 494, // Unofficial + SSL_CERTIFICATE_ERROR: 495, // Unofficial + SSL_CERTIFICATE_REQUIRED: 496, // Unofficial + HTTP_REQUEST_SENT_TO_HTTPS_PORT: 497, // Unofficial + INVALID_TOKEN: 498, // Unofficial + CLIENT_CLOSED_REQUEST: 499, // Unofficial + INTERNAL_SERVER_ERROR: 500, + NOT_IMPLEMENTED: 501, + BAD_GATEWAY: 502, + SERVICE_UNAVAILABLE: 503, + GATEWAY_TIMEOUT: 504, + HTTP_VERSION_NOT_SUPPORTED: 505, + VARIANT_ALSO_NEGOTIATES: 506, + INSUFFICIENT_STORAGE: 507, + LOOP_DETECTED: 508, + BANDWIDTH_LIMIT_EXCEEDED: 509, + NOT_EXTENDED: 510, + NETWORK_AUTHENTICATION_REQUIRED: 511, + WEB_SERVER_UNKNOWN_ERROR: 520, // Unofficial + WEB_SERVER_IS_DOWN: 521, // Unofficial + CONNECTION_TIMEOUT: 522, // Unofficial + ORIGIN_IS_UNREACHABLE: 523, // Unofficial + TIMEOUT_OCCURED: 524, // Unofficial + SSL_HANDSHAKE_FAILED: 525, // Unofficial + INVALID_SSL_CERTIFICATE: 526, // Unofficial + RAILGUN_ERROR: 527, // Unofficial + SITE_IS_OVERLOADED: 529, // Unofficial + SITE_IS_FROZEN: 530, // Unofficial + IDENTITY_PROVIDER_AUTHENTICATION_ERROR: 561, // Unofficial + NETWORK_READ_TIMEOUT: 598, // Unofficial + NETWORK_CONNECT_TIMEOUT: 599, // Unofficial +}; +exports.FINISH = { + SAFE: 0, + SAFE_WITH_CB: 1, + UNSAFE: 2, +}; +exports.HEADER_STATE = { + GENERAL: 0, + CONNECTION: 1, + CONTENT_LENGTH: 2, + TRANSFER_ENCODING: 3, + UPGRADE: 4, + CONNECTION_KEEP_ALIVE: 5, + CONNECTION_CLOSE: 6, + CONNECTION_UPGRADE: 7, + TRANSFER_ENCODING_CHUNKED: 8, +}; +// C headers +exports.METHODS_HTTP = [ + exports.METHODS.DELETE, + exports.METHODS.GET, + exports.METHODS.HEAD, + exports.METHODS.POST, + exports.METHODS.PUT, + exports.METHODS.CONNECT, + exports.METHODS.OPTIONS, + exports.METHODS.TRACE, + exports.METHODS.COPY, + exports.METHODS.LOCK, + exports.METHODS.MKCOL, + exports.METHODS.MOVE, + exports.METHODS.PROPFIND, + exports.METHODS.PROPPATCH, + exports.METHODS.SEARCH, + exports.METHODS.UNLOCK, + exports.METHODS.BIND, + exports.METHODS.REBIND, + exports.METHODS.UNBIND, + exports.METHODS.ACL, + exports.METHODS.REPORT, + exports.METHODS.MKACTIVITY, + exports.METHODS.CHECKOUT, + exports.METHODS.MERGE, + exports.METHODS['M-SEARCH'], + exports.METHODS.NOTIFY, + exports.METHODS.SUBSCRIBE, + exports.METHODS.UNSUBSCRIBE, + exports.METHODS.PATCH, + exports.METHODS.PURGE, + exports.METHODS.MKCALENDAR, + exports.METHODS.LINK, + exports.METHODS.UNLINK, + exports.METHODS.PRI, + // TODO(indutny): should we allow it with HTTP? + exports.METHODS.SOURCE, + exports.METHODS.QUERY, +]; +exports.METHODS_ICE = [ + exports.METHODS.SOURCE, +]; +exports.METHODS_RTSP = [ + exports.METHODS.OPTIONS, + exports.METHODS.DESCRIBE, + exports.METHODS.ANNOUNCE, + exports.METHODS.SETUP, + exports.METHODS.PLAY, + exports.METHODS.PAUSE, + exports.METHODS.TEARDOWN, + exports.METHODS.GET_PARAMETER, + exports.METHODS.SET_PARAMETER, + exports.METHODS.REDIRECT, + exports.METHODS.RECORD, + exports.METHODS.FLUSH, + // For AirPlay + exports.METHODS.GET, + exports.METHODS.POST, +]; +exports.METHOD_MAP = (0, utils_1.enumToMap)(exports.METHODS); +exports.H_METHOD_MAP = Object.fromEntries(Object.entries(exports.METHODS).filter(([k]) => k.startsWith('H'))); +exports.STATUSES_HTTP = [ + exports.STATUSES.CONTINUE, + exports.STATUSES.SWITCHING_PROTOCOLS, + exports.STATUSES.PROCESSING, + exports.STATUSES.EARLY_HINTS, + exports.STATUSES.RESPONSE_IS_STALE, + exports.STATUSES.REVALIDATION_FAILED, + exports.STATUSES.DISCONNECTED_OPERATION, + exports.STATUSES.HEURISTIC_EXPIRATION, + exports.STATUSES.MISCELLANEOUS_WARNING, + exports.STATUSES.OK, + exports.STATUSES.CREATED, + exports.STATUSES.ACCEPTED, + exports.STATUSES.NON_AUTHORITATIVE_INFORMATION, + exports.STATUSES.NO_CONTENT, + exports.STATUSES.RESET_CONTENT, + exports.STATUSES.PARTIAL_CONTENT, + exports.STATUSES.MULTI_STATUS, + exports.STATUSES.ALREADY_REPORTED, + exports.STATUSES.TRANSFORMATION_APPLIED, + exports.STATUSES.IM_USED, + exports.STATUSES.MISCELLANEOUS_PERSISTENT_WARNING, + exports.STATUSES.MULTIPLE_CHOICES, + exports.STATUSES.MOVED_PERMANENTLY, + exports.STATUSES.FOUND, + exports.STATUSES.SEE_OTHER, + exports.STATUSES.NOT_MODIFIED, + exports.STATUSES.USE_PROXY, + exports.STATUSES.SWITCH_PROXY, + exports.STATUSES.TEMPORARY_REDIRECT, + exports.STATUSES.PERMANENT_REDIRECT, + exports.STATUSES.BAD_REQUEST, + exports.STATUSES.UNAUTHORIZED, + exports.STATUSES.PAYMENT_REQUIRED, + exports.STATUSES.FORBIDDEN, + exports.STATUSES.NOT_FOUND, + exports.STATUSES.METHOD_NOT_ALLOWED, + exports.STATUSES.NOT_ACCEPTABLE, + exports.STATUSES.PROXY_AUTHENTICATION_REQUIRED, + exports.STATUSES.REQUEST_TIMEOUT, + exports.STATUSES.CONFLICT, + exports.STATUSES.GONE, + exports.STATUSES.LENGTH_REQUIRED, + exports.STATUSES.PRECONDITION_FAILED, + exports.STATUSES.PAYLOAD_TOO_LARGE, + exports.STATUSES.URI_TOO_LONG, + exports.STATUSES.UNSUPPORTED_MEDIA_TYPE, + exports.STATUSES.RANGE_NOT_SATISFIABLE, + exports.STATUSES.EXPECTATION_FAILED, + exports.STATUSES.IM_A_TEAPOT, + exports.STATUSES.PAGE_EXPIRED, + exports.STATUSES.ENHANCE_YOUR_CALM, + exports.STATUSES.MISDIRECTED_REQUEST, + exports.STATUSES.UNPROCESSABLE_ENTITY, + exports.STATUSES.LOCKED, + exports.STATUSES.FAILED_DEPENDENCY, + exports.STATUSES.TOO_EARLY, + exports.STATUSES.UPGRADE_REQUIRED, + exports.STATUSES.PRECONDITION_REQUIRED, + exports.STATUSES.TOO_MANY_REQUESTS, + exports.STATUSES.REQUEST_HEADER_FIELDS_TOO_LARGE_UNOFFICIAL, + exports.STATUSES.REQUEST_HEADER_FIELDS_TOO_LARGE, + exports.STATUSES.LOGIN_TIMEOUT, + exports.STATUSES.NO_RESPONSE, + exports.STATUSES.RETRY_WITH, + exports.STATUSES.BLOCKED_BY_PARENTAL_CONTROL, + exports.STATUSES.UNAVAILABLE_FOR_LEGAL_REASONS, + exports.STATUSES.CLIENT_CLOSED_LOAD_BALANCED_REQUEST, + exports.STATUSES.INVALID_X_FORWARDED_FOR, + exports.STATUSES.REQUEST_HEADER_TOO_LARGE, + exports.STATUSES.SSL_CERTIFICATE_ERROR, + exports.STATUSES.SSL_CERTIFICATE_REQUIRED, + exports.STATUSES.HTTP_REQUEST_SENT_TO_HTTPS_PORT, + exports.STATUSES.INVALID_TOKEN, + exports.STATUSES.CLIENT_CLOSED_REQUEST, + exports.STATUSES.INTERNAL_SERVER_ERROR, + exports.STATUSES.NOT_IMPLEMENTED, + exports.STATUSES.BAD_GATEWAY, + exports.STATUSES.SERVICE_UNAVAILABLE, + exports.STATUSES.GATEWAY_TIMEOUT, + exports.STATUSES.HTTP_VERSION_NOT_SUPPORTED, + exports.STATUSES.VARIANT_ALSO_NEGOTIATES, + exports.STATUSES.INSUFFICIENT_STORAGE, + exports.STATUSES.LOOP_DETECTED, + exports.STATUSES.BANDWIDTH_LIMIT_EXCEEDED, + exports.STATUSES.NOT_EXTENDED, + exports.STATUSES.NETWORK_AUTHENTICATION_REQUIRED, + exports.STATUSES.WEB_SERVER_UNKNOWN_ERROR, + exports.STATUSES.WEB_SERVER_IS_DOWN, + exports.STATUSES.CONNECTION_TIMEOUT, + exports.STATUSES.ORIGIN_IS_UNREACHABLE, + exports.STATUSES.TIMEOUT_OCCURED, + exports.STATUSES.SSL_HANDSHAKE_FAILED, + exports.STATUSES.INVALID_SSL_CERTIFICATE, + exports.STATUSES.RAILGUN_ERROR, + exports.STATUSES.SITE_IS_OVERLOADED, + exports.STATUSES.SITE_IS_FROZEN, + exports.STATUSES.IDENTITY_PROVIDER_AUTHENTICATION_ERROR, + exports.STATUSES.NETWORK_READ_TIMEOUT, + exports.STATUSES.NETWORK_CONNECT_TIMEOUT, +]; +exports.ALPHA = []; +for (let i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++) { + // Upper case + exports.ALPHA.push(String.fromCharCode(i)); + // Lower case + exports.ALPHA.push(String.fromCharCode(i + 0x20)); +} +exports.NUM_MAP = { + 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, + 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, +}; +exports.HEX_MAP = { + 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, + 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, + A: 0XA, B: 0XB, C: 0XC, D: 0XD, E: 0XE, F: 0XF, + a: 0xa, b: 0xb, c: 0xc, d: 0xd, e: 0xe, f: 0xf, +}; +exports.NUM = [ + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', +]; +exports.ALPHANUM = exports.ALPHA.concat(exports.NUM); +exports.MARK = ['-', '_', '.', '!', '~', '*', '\'', '(', ')']; +exports.USERINFO_CHARS = exports.ALPHANUM + .concat(exports.MARK) + .concat(['%', ';', ':', '&', '=', '+', '$', ',']); +// TODO(indutny): use RFC +exports.URL_CHAR = [ + '!', '"', '$', '%', '&', '\'', + '(', ')', '*', '+', ',', '-', '.', '/', + ':', ';', '<', '=', '>', + '@', '[', '\\', ']', '^', '_', + '`', + '{', '|', '}', '~', +].concat(exports.ALPHANUM); +exports.HEX = exports.NUM.concat(['a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F']); +/* Tokens as defined by rfc 2616. Also lowercases them. + * token = 1* + * separators = "(" | ")" | "<" | ">" | "@" + * | "," | ";" | ":" | "\" | <"> + * | "/" | "[" | "]" | "?" | "=" + * | "{" | "}" | SP | HT + */ +exports.TOKEN = [ + '!', '#', '$', '%', '&', '\'', + '*', '+', '-', '.', + '^', '_', '`', + '|', '~', +].concat(exports.ALPHANUM); +/* + * Verify that a char is a valid visible (printable) US-ASCII + * character or %x80-FF + */ +exports.HEADER_CHARS = ['\t']; +for (let i = 32; i <= 255; i++) { + if (i !== 127) { + exports.HEADER_CHARS.push(i); + } +} +// ',' = \x44 +exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS.filter((c) => c !== 44); +exports.QUOTED_STRING = ['\t', ' ']; +for (let i = 0x21; i <= 0xff; i++) { + if (i !== 0x22 && i !== 0x5c) { // All characters in ASCII except \ and " + exports.QUOTED_STRING.push(i); + } +} +exports.HTAB_SP_VCHAR_OBS_TEXT = ['\t', ' ']; +// VCHAR: https://tools.ietf.org/html/rfc5234#appendix-B.1 +for (let i = 0x21; i <= 0x7E; i++) { + exports.HTAB_SP_VCHAR_OBS_TEXT.push(i); +} +// OBS_TEXT: https://datatracker.ietf.org/doc/html/rfc9110#name-collected-abnf +for (let i = 0x80; i <= 0xff; i++) { + exports.HTAB_SP_VCHAR_OBS_TEXT.push(i); +} +exports.MAJOR = exports.NUM_MAP; +exports.MINOR = exports.MAJOR; +exports.SPECIAL_HEADERS = { + 'connection': exports.HEADER_STATE.CONNECTION, + 'content-length': exports.HEADER_STATE.CONTENT_LENGTH, + 'proxy-connection': exports.HEADER_STATE.CONNECTION, + 'transfer-encoding': exports.HEADER_STATE.TRANSFER_ENCODING, + 'upgrade': exports.HEADER_STATE.UPGRADE, +}; +exports.default = { + ERROR: exports.ERROR, + TYPE: exports.TYPE, + FLAGS: exports.FLAGS, + LENIENT_FLAGS: exports.LENIENT_FLAGS, + METHODS: exports.METHODS, + STATUSES: exports.STATUSES, + FINISH: exports.FINISH, + HEADER_STATE: exports.HEADER_STATE, + ALPHA: exports.ALPHA, + NUM_MAP: exports.NUM_MAP, + HEX_MAP: exports.HEX_MAP, + NUM: exports.NUM, + ALPHANUM: exports.ALPHANUM, + MARK: exports.MARK, + USERINFO_CHARS: exports.USERINFO_CHARS, + URL_CHAR: exports.URL_CHAR, + HEX: exports.HEX, + TOKEN: exports.TOKEN, + HEADER_CHARS: exports.HEADER_CHARS, + CONNECTION_TOKEN_CHARS: exports.CONNECTION_TOKEN_CHARS, + QUOTED_STRING: exports.QUOTED_STRING, + HTAB_SP_VCHAR_OBS_TEXT: exports.HTAB_SP_VCHAR_OBS_TEXT, + MAJOR: exports.MAJOR, + MINOR: exports.MINOR, + SPECIAL_HEADERS: exports.SPECIAL_HEADERS, + METHODS_HTTP: exports.METHODS_HTTP, + METHODS_ICE: exports.METHODS_ICE, + METHODS_RTSP: exports.METHODS_RTSP, + METHOD_MAP: exports.METHOD_MAP, + H_METHOD_MAP: exports.H_METHOD_MAP, + STATUSES_HTTP: exports.STATUSES_HTTP, +}; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/llhttp/llhttp-wasm.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/llhttp/llhttp-wasm.js new file mode 100644 index 0000000000000000000000000000000000000000..8e898063575c199a0f29616d6038f5ae75c1aa42 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/llhttp/llhttp-wasm.js @@ -0,0 +1,15 @@ +'use strict' + +const { Buffer } = require('node:buffer') + +const wasmBase64 = 'AGFzbQEAAAABJwdgAX8Bf2ADf39/AX9gAn9/AGABfwBgBH9/f38Bf2AAAGADf39/AAL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ogAjYCACACIAA2AhgLIAEgBGogBDYCACABIARBAXI2AgQgAUHY1QAoAgBHDQBBzNUAIAQ2AgAMAQsgBEH/AU0EQCAEQXhxQezVAGohAAJ/QcTVACgCACICQQEgBEEDdnQiA3FFBEBBxNUAIAIgA3I2AgAgAAwBCyAAKAIICyICIAE2AgwgACABNgIIIAEgADYCDCABIAI2AggMAQtBHyECIARB////B00EQCAEQSYgBEEIdmciAGt2QQFxIABBAXRrQT5qIQILIAEgAjYCHCABQgA3AhAgAkECdEH01wBqIQACQEHI1QAoAgAiA0EBIAJ0IgdxRQRAIAAgATYCAEHI1QAgAyAHcjYCACABIAA2AhggASABNgIIIAEgATYCDAwBCyAEQRkgAkEBdmtBACACQR9HG3QhAiAAKAIAIQACQANAIAAiAygCBEF4cSAERg0BIAJBHXYhACACQQF0IQIgAyAAQQRxakEQaiIHKAIAIgANAAsgByABNgIAIAEgAzYCGCABIAE2AgwgASABNgIIDAELIAMoAggiACABNgIMIAMgATYCCCABQQA2AhggASADNgIMIAEgADYCCAtB5NUAQeTVACgCAEEBayIAQX8gABs2AgALCwcAIAAtACgLBwAgAC0AKgsHACAALQArCwcAIAAtACkLBwAgAC8BNAsHACAALQAwC0ABBH8gACgCGCEBIAAvAS4hAiAALQAoIQMgACgCOCEEIAAQOCAAIAQ2AjggACADOgAoIAAgAjsBLiAAIAE2AhgL5YUCAgd/A34gASACaiEEAkAgACIDKAIMIgANACADKAIEBEAgAyABNgIECyMAQRBrIgkkAAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJA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IQEMHQsgA0EZNgIcIAMgADYCDCADIAFBAWo2AhQM9gILIAMoAgQhAEEAIQIgA0EANgIEIAMgACABEDQiAEUEQCABQQFqIQEM7wILIANBGjYCHCADIAA2AgwgAyABQQFqNgIUDPUCCyAAQRVGDR9BACECIANBADYCHCADIAE2AhQgA0HQDzYCECADQSI2AgwM9AILIAMoAgQhACADQQA2AgQgAyAAIAEQMyIARQRAIAFBAWohAQwbCyADQRw2AhwgAyAANgIMIAMgAUEBajYCFEEAIQIM8wILIAMoAgQhACADQQA2AgQgAyAAIAEQMyIARQRAIAFBAWohAQzrAgsgA0EdNgIcIAMgADYCDCADIAFBAWo2AhRBACECDPICCyAAQTtHDQEgAUEBaiEBC0EmIQIM1wILQQAhAiADQQA2AhwgAyABNgIUIANBnxU2AhAgA0EMNgIMDO8CCyABIARHBEADQCABLQAAQSBHDYQCIAQgAUEBaiIBRw0AC0EsIQIM7wILQSwhAgzuAgsgASAERgRAQTQhAgzuAgsCQAJAA0ACQCABLQAAQQprDgQCAAADAAsgBCABQQFqIgFHDQALQTQhAgzvAgsgAygCBCEAIANBADYCBCADIAAgARAxIgBFDZ8CIANBMjYCHCADIAE2AhQgAyAANgIMQQAhAgzuAgsgAygCBCEAIANBADYCBCADIAAgARAxIgBFBEAgAUEBaiEBDJ8CCyADQTI2AhwgAyAANgIMIAMgAUEBajYCFEEAIQIM7QILIAEgBEcEQAJAA0AgAS0AAEEwayIAQf8BcUEKTwRAQTohAgzXAgsgAykDICILQpmz5syZs+bMGVYNASADIAtCCn4iCjcDICAKIACtQv8BgyILQn+FVg0BIAMgCiALfDcDICAEIAFBAWoiAUcNAAtBwAAhAgzuAgsgAygCBCEAIANBADYCBCADIAAgAUEBaiIBEDEiAA0XDOICC0HAACECDOwCCyABIARGBEBByQAhAgzsAgsCQANAAkAgAS0AAEEJaw4YAAKiAqICqQKiAqICogKiAqICogKiAqICogKiAqICogKiAqICogKiAqICogIAogILIAQgAUEBaiIBRw0AC0HJACECDOwCCyABQQFqIQEgA0Evai0AAEEBcQ2lAiADQQA2AhwgAyABNgIUIANBlxA2AhAgA0EKNgIMQQAhAgzrAgsgASAERwRAA0AgAS0AAEEgRw0VIAQgAUEBaiIBRw0AC0H4ACECDOsCC0H4ACECDOoCCyADQQI6ACgMOAtBACECIANBADYCHCADQb8LNgIQIANBAjYCDCADIAFBAWo2AhQM6AILQQAhAgzOAgtBDSECDM0CC0ETIQIMzAILQRUhAgzLAgtBFiECDMoCC0EYIQIMyQILQRkhAgzIAgtBGiECDMcCC0EbIQIMxgILQRwhAgzFAgtBHSECDMQCC0EeIQIMwwILQR8hAgzCAgtBICECDMECC0EiIQIMwAILQSMhAgy/AgtBJSECDL4CC0HlACECDL0CCyADQT02AhwgAyABNgIUIAMgADYCDEEAIQIM1QILIANBGzYCHCADIAE2AhQgA0GkHDYCECADQRU2AgxBACECDNQCCyADQSA2AhwgAyABNgIUIANBmBo2AhAgA0EVNgIMQQAhAgzTAgsgA0ETNgIcIAMgATYCFCADQZgaNgIQIANBFTYCDEEAIQIM0gILIANBCzYCHCADIAE2AhQgA0GYGjYCECADQRU2AgxBACECDNECCyADQRA2AhwgAyABNgIUIANBmBo2AhAgA0EVNgIMQQAhAgzQAgsgA0EgNgIcIAMgATYCFCADQaQcNgIQIANBFTYCDEEAIQIMzwILIANBCzYCHCADIAE2AhQgA0GkHDYCECADQRU2AgxBACECDM4CCyADQQw2AhwgAyABNgIUIANBpBw2AhAgA0EVNgIMQQAhAgzNAgtBACECIANBADYCHCADIAE2AhQgA0HdDjYCECADQRI2AgwMzAILAkADQAJAIAEtAABBCmsOBAACAgACCyAEIAFBAWoiAUcNAAtB/QEhAgzMAgsCQAJAIAMtADZBAUcNAEEAIQACQCADKAI4IgJFDQAgAigCYCICRQ0AIAMgAhEAACEACyAARQ0AIABBFUcNASADQfwBNgIcIAMgATYCFCADQdwZNgIQIANBFTYCDEEAIQIMzQILQdwBIQIMswILIANBADYCHCADIAE2AhQgA0H5CzYCECADQR82AgxBACECDMsCCwJAAkAgAy0AKEEBaw4CBAEAC0HbASECDLICC0HUASECDLECCyADQQI6ADFBACEAAkAgAygCOCICRQ0AIAIoAgAiAkUNACADIAIRAAAhAAsgAEUEQEHdASECDLECCyAAQRVHBEAgA0EANgIcIAMgATYCFCADQbQMNgIQIANBEDYCDEEAIQIMygILIANB+wE2AhwgAyABNgIUIANBgRo2AhAgA0EVNgIMQQAhAgzJAgsgASAERgRAQfoBIQIMyQILIAEtAABByABGDQEgA0EBOgAoC0HAASECDK4CC0HaASECDK0CCyABIARHBEAgA0EMNgIIIAMgATYCBEHZASECDK0CC0H5ASECDMUCCyABIARGBEBB+AEhAgzFAgsgAS0AAEHIAEcNBCABQQFqIQFB2AEhAgyrAgsgASAERgRAQfcBIQIMxAILAkACQCABLQAAQcUAaw4QAAUFBQUFBQUFBQUFBQUFAQULIAFBAWohAUHWASECDKsCCyABQQFqIQFB1wEhAgyqAgtB9gEhAiABIARGDcICIAMoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQbrVAGotAABHDQMgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADMMCCyADKAIEIQAgA0IANwMAIAMgACAGQQFqIgEQLiIARQRAQeMBIQIMqgILIANB9QE2AhwgAyABNgIUIAMgADYCDEEAIQIMwgILQfQBIQIgASAERg3BAiADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEG41QBqLQAARw0CIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzCAgsgA0GBBDsBKCADKAIEIQAgA0IANwMAIAMgACAGQQFqIgEQLiIADQMMAgsgA0EANgIAC0EAIQIgA0EANgIcIAMgATYCFCADQeUfNgIQIANBCDYCDAy/AgtB1QEhAgylAgsgA0HzATYCHCADIAE2AhQgAyAANgIMQQAhAgy9AgtBACEAAkAgAygCOCICRQ0AIAIoAkAiAkUNACADIAIRAAAhAAsgAEUNbiAAQRVHBEAgA0EANgIcIAMgATYCFCADQYIPNgIQIANBIDYCDEEAIQIMvQILIANBjwE2AhwgAyABNgIUIANB7Bs2AhAgA0EVNgIMQQAhAgy8AgsgASAERwRAIANBDTYCCCADIAE2AgRB0wEhAgyjAgtB8gEhAgy7AgsgASAERgRAQfEBIQIMuwILAkACQAJAIAEtAABByABrDgsAAQgICAgICAgIAggLIAFBAWohAUHQASECDKMCCyABQQFqIQFB0QEhAgyiAgsgAUEBaiEBQdIBIQIMoQILQfABIQIgASAERg25AiADKAIAIgAgBCABa2ohBiABIABrQQJqIQUDQCABLQAAIABBtdUAai0AAEcNBCAAQQJGDQMgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAY2AgAMuQILQe8BIQIgASAERg24AiADKAIAIgAgBCABa2ohBiABIABrQQFqIQUDQCABLQAAIABBs9UAai0AAEcNAyAAQQFGDQIgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAY2AgAMuAILQe4BIQIgASAERg23AiADKAIAIgAgBCABa2ohBiABIABrQQJqIQUDQCABLQAAIABBsNUAai0AAEcNAiAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAY2AgAMtwILIAMoAgQhACADQgA3AwAgAyAAIAVBAWoiARArIgBFDQIgA0HsATYCHCADIAE2AhQgAyAANgIMQQAhAgy2AgsgA0EANgIACyADKAIEIQAgA0EANgIEIAMgACABECsiAEUNnAIgA0HtATYCHCADIAE2AhQgAyAANgIMQQAhAgy0AgtBzwEhAgyaAgtBACEAAkAgAygCOCICRQ0AIAIoAjQiAkUNACADIAIRAAAhAAsCQCAABEAgAEEVRg0BIANBADYCHCADIAE2AhQgA0HqDTYCECADQSY2AgxBACECDLQCC0HOASECDJoCCyADQesBNgIcIAMgATYCFCADQYAbNgIQIANBFTYCDEEAIQIMsgILIAEgBEYEQEHrASECDLICCyABLQAAQS9GBEAgAUEBaiEBDAELIANBADYCHCADIAE2AhQgA0GyODYCECADQQg2AgxBACECDLECC0HNASECDJcCCyABIARHBEAgA0EONgIIIAMgATYCBEHMASECDJcCC0HqASECDK8CCyABIARGBEBB6QEhAgyvAgsgAS0AAEEwayIAQf8BcUEKSQRAIAMgADoAKiABQQFqIQFBywEhAgyWAgsgAygCBCEAIANBADYCBCADIAAgARAvIgBFDZcCIANB6AE2AhwgAyABNgIUIAMgADYCDEEAIQIMrgILIAEgBEYEQEHnASECDK4CCwJAIAEtAABBLkYEQCABQQFqIQEMAQsgAygCBCEAIANBADYCBCADIAAgARAvIgBFDZgCIANB5gE2AhwgAyABNgIUIAMgADYCDEEAIQIMrgILQcoBIQIMlAILIAEgBEYEQEHlASECDK0CC0EAIQBBASEFQQEhB0EAIQICQAJAAkACQAJAAn8CQAJAAkACQAJAAkACQCABLQAAQTBrDgoKCQABAgMEBQYICwtBAgwGC0EDDAULQQQMBAtBBQwDC0EGDAILQQcMAQtBCAshAkEAIQVBACEHDAILQQkhAkEBIQBBACEFQQAhBwwBC0EAIQVBASECCyADIAI6ACsgAUEBaiEBAkACQCADLQAuQRBxDQACQAJAAkAgAy0AKg4DAQACBAsgB0UNAwwCCyAADQEMAgsgBUUNAQsgAygCBCEAIANBADYCBCADIAAgARAvIgBFDQIgA0HiATYCHCADIAE2AhQgAyAANgIMQQAhAgyvAgsgAygCBCEAIANBADYCBCADIAAgARAvIgBFDZoCIANB4wE2AhwgAyABNgIUIAMgADYCDEEAIQIMrgILIAMoAgQhACADQQA2AgQgAyAAIAEQLyIARQ2YAiADQeQBNgIcIAMgATYCFCADIAA2AgwMrQILQckBIQIMkwILQQAhAAJAIAMoAjgiAkUNACACKAJEIgJFDQAgAyACEQAAIQALAkAgAARAIABBFUYNASADQQA2AhwgAyABNgIUIANBpA02AhAgA0EhNgIMQQAhAgytAgtByAEhAgyTAgsgA0HhATYCHCADIAE2AhQgA0HQGjYCECADQRU2AgxBACECDKsCCyABIARGBEBB4QEhAgyrAgsCQCABLQAAQSBGBEAgA0EAOwE0IAFBAWohAQwBCyADQQA2AhwgAyABNgIUIANBmRE2AhAgA0EJNgIMQQAhA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gARAtIgBFBEAgAUEBaiEBDAQLIANB2gE2AhwgAyAANgIMIAMgAUEBajYCFEEAIQIMpQILIAMoAgQhACADQQA2AgQgAyAAIAEQLSIADQEgAUEBagshAUHBASECDIoCCyADQdkBNgIcIAMgADYCDCADIAFBAWo2AhRBACECDKICC0HCASECDIgCCyADQS9qLQAAQQFxDQEgA0EANgIcIAMgATYCFCADQeQcNgIQIANBGTYCDEEAIQIMoAILIAEgBEYEQEHZASECDKACCwJAAkACQCABLQAAQQprDgQBAgIAAgsgAUEBaiEBDAILIAFBAWohAQwBCyADLQAuQcAAcUUNAQtBACEAAkAgAygCOCICRQ0AIAIoAjwiAkUNACADIAIRAAAhAAsgAEUNoAEgAEEVRgRAIANB2QA2AhwgAyABNgIUIANBtxo2AhAgA0EVNgIMQQAhAgyfAgsgA0EANgIcIAMgATYCFCADQYANNgIQIANBGzYCDEEAIQIMngILIANBADYCHCADIAE2AhQgA0HcKDYCECADQQI2AgxBACECDJ0CCyABIARHBEAgA0EMNgIIIAMgATYCBEG/ASECDIQCC0HYASECDJwCCyABIARGBEBB1wEhAgycAgsCQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAEtAABBwQBrDhUAAQIDWgQFBlpaWgcICQoLDA0ODxBaCyABQQFqIQFB+wAhAgySAgsgAUEBaiEBQfwAIQIMkQILIAFBAWohAUGBASECDJACCyABQQFqIQFBhQEhAgyPAgsgAUEBaiEBQYYBIQIMjgILIAFBAWohAUGJASECDI0CCyABQQFqIQFBigEhAgyMAgsgAUEBaiEBQY0BIQIMiwILIAFBAWohAUGWASECDIoCCyABQQFqIQFBlwEhAgyJAgsgAUEBaiEBQZgBIQIMiAILIAFBAWohAUGlASECDIcCCyABQQFqIQFBpgEhAgyGAgsgAUEBaiEBQawBIQIMhQILIAFBAWohAUG0ASECDIQCCyABQQFqIQFBtwEhAgyDAgsgAUEBaiEBQb4BIQIMggILIAEgBEYEQEHWASECDJsCCyABLQAAQc4ARw1IIAFBAWohA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raiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQejUAGotAABHDSUgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADPkBCyADQQA2AgAgBkEBaiEBQSYMJQsgASAERgRAQbMBIQIM+AELAkACQCABLQAAQdQAaw4CAAEnCyABQQFqIQFBmQEhAgzfAQsgAUEBaiEBQZoBIQIM3gELQbIBIQIgASAERg32ASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHm1ABqLQAARw0jIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAz3AQsgA0EANgIAIAZBAWohAUEnDCMLQbEBIQIgASAERg31ASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHk1ABqLQAARw0iIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAz2AQsgA0EANgIAIAZBAWohAUEcDCILQbABIQIgASAERg30ASADKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEHe1ABqLQAARw0hIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAz1AQsgA0EANgIAIAZBAWohAUEGDCELQa8BIQIgASAERg3zASADKAIAIgAgBCABa2ohBSABIABrQQRqIQYCQANAIAEtAAAgAEHZ1ABqLQAARw0gIABBBEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAz0AQsgA0EANgIAIAZBAWohAUEZDCALIAEgBEYEQEGuASECDPMBCwJAAkACQAJAIAEtAABBLWsOIwAkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJAEkJCQkJAIkJCQDJAsgAUEBaiEBQY4BIQIM3AELIAFBAWohAUGPASECDNsBCyABQQFqIQFBlAEhAgzaAQsgAUEBaiEBQZUBIQIM2QELQa0BIQIgASAERg3xASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHX1ABqLQAARw0eIABBAUYNASAAQQFqIQAgBCABQQFqIg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BRw0ACyADIAU2AgAM6QELIANBADYCACAGQQFqIQFBCQwVC0GjASECIAEgBEYN5wEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABBpNUAai0AAEcNFCAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM6AELIANBADYCACAGQQFqIQFBHwwUC0GiASECIAEgBEYN5gEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBvtQAai0AAEcNEyAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM5wELIANBADYCACAGQQFqIQFBAgwTC0GhASECIAEgBEYN5QEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGA0AgAS0AACAAQbzUAGotAABHDREgAEEBRg0CIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADOUBCyABIARGBEBBoAEhAgzlAQtBASABLQAAQd8ARw0RGiABQQFqIQFBhwEhAgzLAQsgA0EANgIAIAZBAWohAUGIASECDMoBC0GfASECIAEgBEYN4gEgAygCACIAIAQgAWtqIQUgASAAa0EIaiEGAkADQCABLQAAIABBhNUAai0AAEcNDyAAQQhGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM4wELIANBADYCACAGQQFqIQFBKQwPC0GeASECIAEgBEYN4QEgAygCACIAIAQgAWtqIQUgASAAa0EDaiEGAkADQCABLQAAIABBuNQAai0AAEcNDiAAQQNGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM4gELIANBADYCACAGQQFqIQFBLQwOCyABIARGBEBBnQEhAgzhAQsgAS0AAEHFAEcNDiABQQFqIQFBhAEhAgzHAQsgASAERgRAQZwBIQIM4AELAkACQCABLQAAQcwAaw4IAA8PDw8PDwEPCyABQQFqIQFBggEhAgzHAQsgAUEBaiEBQYMBIQIMxgELQZsBIQIgASAERg3eASADKAIAIgAgBCABa2ohBSABIABrQQRqIQYCQANAIAEtAAAgAEGz1ABqLQAARw0LIAB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EEFRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADNYBCyADQQA2AgAgBkEBaiEBQSQMAgsgA0EANgIADAILIAEgBEYEQEGRASECDNQBCyABLQAAQcwARw0BIAFBAWohAUETCzoAKSADKAIEIQAgA0EANgIEIAMgACABEC4iAA0CDAELQQAhAiADQQA2AhwgAyABNgIUIANB/h82AhAgA0EGNgIMDNEBC0H4ACECDLcBCyADQZABNgIcIAMgATYCFCADIAA2AgxBACECDM8BC0EAIQACQCADKAI4IgJFDQAgAigCQCICRQ0AIAMgAhEAACEACyAARQ0AIABBFUYNASADQQA2AhwgAyABNgIUIANBgg82AhAgA0EgNgIMQQAhAgzOAQtB9wAhAgy0AQsgA0GPATYCHCADIAE2AhQgA0HsGzYCECADQRU2AgxBACECDMwBCyABIARGBEBBjwEhAgzMAQsCQCABLQAAQSBGBEAgAUEBaiEBDAELIANBADYCHCADIAE2AhQgA0GbHzYCECADQQY2AgxBACECDMwBC0ECIQIMsgELA0AgAS0AAEEgRw0CIAQgAUEBaiIBRw0AC0GOASECDMoBCyABIARGBEBBjQEhAgzKAQsCQCABLQAAQQlrDgRKAABKAAtB9QAhAgywAQsgAy0AKUEFRgRAQfYAIQIMsAELQfQAIQIMrwELIAEgBEYEQEGMASECDMgBCyADQRA2AgggAyABNgIEDAoLIAEgBEYEQEGLASECDMcBCwJAIAEtAABBCWsOBEcAAEcAC0HzACECDK0BCyABIARHBEAgA0EQNgIIIAMgATYCBEHxACECDK0BC0GKASECDMUBCwJAIAEgBEcEQANAIAEtAABBoNAAai0AACIAQQNHBEACQCAAQQFrDgJJAAQLQfAAIQIMrwELIAQgAUEBaiIBRw0AC0GIASECDMYBC0GIASECDMUBCyADQQA2AhwgAyABNgIUIANB2yA2AhAgA0EHNgIMQQAhAgzEAQsgASAERgRAQYkBIQIMxAELAkACQAJAIAEtAABBoNIAai0AAEEBaw4DRgIAAQtB8gAhAgysAQsgA0EANgIcIAMgATYCFCADQbQSNgIQIANBBzYCDE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DJwBC0HhACECDIIBCyADQfMANgIcIAMgATYCFCADQYAbNgIQIANBFTYCDEEAIQIMmgELIAMtACkiAEEja0ELSQ0JAkAgAEEGSw0AQQEgAHRBygBxRQ0ADAoLQQAhAiADQQA2AhwgAyABNgIUIANB7Qk2AhAgA0EINgIMDJkBC0HyACECIAEgBEYNmAEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABBs9UAai0AAEcNBSAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMmQELIAMoAgQhACADQgA3AwAgAyAAIAZBAWoiARArIgAEQCADQfEANgIcIAMgATYCFCADIAA2AgxBACECDJkBC0HfACECDH8LQQAhAAJAIAMoAjgiAkUNACACKAI0IgJFDQAgAyACEQAAIQALAkAgAARAIABBFUYNASADQQA2AhwgAyABNgIUIANB6g02AhAgA0EmNgIMQQAhAgyZAQtB3gAhAgx/CyADQfAANgIcIAMgATYCFCADQYAbNgIQIANBFTYCDEEAIQIMlwELIAMtAClBIUYNBiADQQA2AhwgAyABNgIUIANBkQo2AhAgA0EINgIMQQAhAgyWAQtB7wAhAiABIARGDZUBIAMoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQbDVAGotAABHDQIgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADJYBCyADKAIEIQAgA0IANwMAIAMgACAGQQFqIgEQKyIARQ0CIANB7QA2AhwgAyABNgIUIAMgADYCDEEAIQIMlQELIANBADYCAAsgAygCBCEAIANBADYCBCADIAAgARArIgBFDYABIANB7gA2AhwgAyABNgIUIAMgADYCDEEAIQIMkwELQdwAIQIMeQtBACEAAkAgAygCOCICRQ0AIAIoAjQiAkUNACADIAIRAAAhAAsCQCAABEAgAEEVRg0BIANBADYCHCADIAE2AhQgA0HqDTYCECADQSY2AgxBACECDJMBC0HbACECDHkLIANB7AA2AhwgAyABNgIUIANBgBs2AhAgA0EVNgIMQQAhAgyRAQsgAy0AKSIAQSNJDQAgAEEuRg0AIANBADYCHCADIAE2AhQgA0HJCTYCECADQQg2AgxBACECDJABC0HaACECDHYLIAEgBEYEQEHrACECDI8BCwJAIAEtAABBL0YEQCABQQFqIQEMAQsgA0EANgIcIAMgATYCFCADQbI4NgIQIANBCDYCDEEAIQIMjwELQdkAIQIMdQsgASAERwRAIANBDjYCCCADIAE2AgRB2AAhAgx1C0HqACECDI0BCyABIARGBEBB6QAhAgyNAQsgAS0AAEEwayIAQf8BcUEKSQRAIAMgADoAKiABQQFqIQFB1wAhAgx0CyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNeiADQegANgIcIAMgATYCFCADIAA2AgxBACECDIwBCyABIARGBEBB5wAhAgyMAQsCQCABLQAAQS5GBEAgAUEBaiEBDAELIAMoAgQhACADQQA2AgQgAyAAIAEQLyIARQ17IANB5gA2AhwgAyABNgIUIAMgADYCDEEAIQIMjAELQdYAIQIMcgsgASAERgRAQeUAIQIMiwELQQAhAEEBIQVBASEHQQAhAgJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAIAEtAABBMGsOCgoJAAECAwQFBggLC0ECDAYLQQMMBQtBBAwEC0EFDAMLQQYMAgtBBwwBC0EICyECQQAhBUEAIQcMAgtBCSECQQEhAEEAIQVBACEHDAELQQAhBUEBIQILIAMgAjoAKyABQQFqIQECQAJAIAMtAC5BEHENAAJAAkACQCADLQAqDgMBAAIECyAHRQ0DDAILIAANAQwCCyAFRQ0BCyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNAiADQeIANgIcIAMgATYCFCADIAA2AgxBACECDI0BCyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNfSADQeMANgIcIAMgATYCFCADIAA2AgxBACECDIwBCyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNeyADQeQANgIcIAMgATYCFCADIAA2AgwMiwELQdQAIQIMcQsgAy0AKUEiRg2GAUHTACECDHALQQAhAAJAIAMoAjgiAkUNACACKAJEIgJFDQAgAyACEQAAIQALIABFBEBB1QAhAgxwCyAAQRVHBEAgA0EANgIcIAMgATYCFCADQaQNNgIQIANBITYCDEEAIQIMiQELIANB4QA2AhwgAyABNgIUIANB0Bo2AhAgA0EVNgIMQQAhAgyIAQsgASAERgRAQeAAIQIMiAELAkACQAJAAkACQCABLQAAQQprDgQBBAQABAsgAUEBaiEBDAELIAFBAWohASADQS9qLQAAQQFxRQ0BC0HSACECDHALIANBADYCHCADIAE2AhQgA0G2ETYCECADQQk2AgxBACECDIgBCyADQQA2AhwgAyABNgIUIANBthE2AhAgA0EJNgIMQQAhAgyHAQsgASAERgRAQd8AIQIMhwELIAEtAABBCkYEQCABQQFqIQEMCQsgAy0ALkHAAHENCCADQQA2AhwgAyABNgIUIANBthE2AhAgA0ECNgIMQQAhAgyGAQsgASAERgRAQd0AIQIMhgELIAEtAAAiAkENRgRAIAFBAWohAUHQACECDG0LIAEhACACQQlrDgQFAQEFAQsgBCABIgBGBEBB3AAhAgyFAQsgAC0AAEEKRw0AIABBAWoMAgtBACECIANBADYCHCADIAA2AhQgA0HKLTYCECADQQc2AgwMgwELIAEgBEYEQEHbACECDIMBCwJAIAEtAABBCWsOBAMAAAMACyABQQFqCyEBQc4AIQIMaAsgASAERgRAQdoAIQIMgQELIAEtAABBCWsOBAABAQABC0EAIQIgA0EANgIcIANBmhI2AhAgA0EHNgIMIAMgAUEBajYCFAx/CyADQYASOwEqQQAhAAJAIAMoAjgiAkUNACACKAI4IgJFDQAgAyACEQAAIQALIABFDQAgAEEVRw0BIANB2QA2AhwgAyABNgIUIANB6ho2AhAgA0EVNgIMQQAhAgx+C0HNACECDGQLIANBADYCHCADIAE2AhQgA0HJDTYCECADQRo2AgxBACECDHwLIAEgBEYEQEHZACECDHwLIAEtAABBIEcNPSABQQFqIQEgAy0ALkEBcQ09IANBADYCHCADIAE2AhQgA0HCHDYCECADQR42AgxBACECDHsLIAEgBEYEQEHYACECDHsLAkACQAJAAkACQCABLQAAIgBBCmsOBAIDAwABCyABQQFqIQFBLCECDGULIABB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AALQAAIgVBIHIgBSAFQcEAa0H/AXFBGkkbQf8BcUcNASABQQNGBEBBBiEBDD0LIAFBAWohASAEIABBAWoiAEcNAAsgAyAGNgIADFcLIANBADYCACAAIQEMAwsCQANAIAEtAAAiAEEgRwRAIABBCmsOBAcEBAcCCyAEIAFBAWoiAUcNAAtBOCECDFYLIABBLEcNASABQQFqIQBBASEBAkACQAJAAkACQCADLQAsQQVrDgQDAQIEAAsgACEBDAQLQQIhAQwBC0EEIQELIANBAToALCADIAMvATIgAXI7ATIgACEBDAELIAMgAy8BMkEIcjsBMiAAIQELQT4hAgw7CyADQQA6ACwLQTkhAgw5CyABIARGBEBBNiECDFILAkACQAJAAkACQCABLQAAQQprDgQAAgIBAgsgAygCBCEAIANBADYCBCADIAAgARAxIgBFDQIgA0EzNgIcIAMgATYCFCADIAA2AgxBACECDFULIAMoAgQhACADQQA2AgQgAyAAIAEQMSIARQRAIAFBAWohAQwGCyADQTI2AhwgAyAANgIMIAMgAUEBajYCFEEAIQIMVAsgAy0ALkEBcQRAQd8BIQIMOwsgAygCBCEAIANBADYCBCADIAAgARAxIgANAQxJC0E0IQIMOQsgA0E1NgIcIAMgATYCFCADIAA2AgxBACECDFELQTUhAgw3CyADQS9qLQAAQQFxDQAgA0EANgIcIAMgATYCFCADQesWNgIQIANBGTYCDEEAIQIMTwtBMyECDDULIAEgBEYEQEEyIQIMTgsCQCABLQAAQQpGBEAgAUEBaiEBDAELIANBADYCHCADIAE2AhQgA0GSFzYCECADQQM2AgxBACECDE4LQTIhAgw0CyABIARGBEBBMSECDE0LAkAgAS0AACIAQQlGDQAgAEEgRg0AQQEhAgJAIAMtACxBBWsOBAYEBQANCyADIAMvATJBCHI7ATIMDAsgAy0ALkEBcUUNASADLQAsQQhHDQAgA0EAOgAsC0E9IQIMMgsgA0EANgIcIAMgATYCFCADQcIWNgIQIANBCjYCDEEAIQIMSgtBAiECDAELQQQhAgsgA0EBOgAsIAMgAy8BMiACcjsBMgwGCyABIARGBEBBMCECDEcLIAEtAABBCkYEQCABQQFqIQEMAQsgAy0ALkEBcQ0AIANBADYCHCADIAE2AhQgA0HcKDYCECADQQI2AgxBACECDEYLQTAhAgwsCyABQQFqIQFBMSECDCsLIAEgBEYEQEEvIQIMRAsgAS0AACIAQQlHIABBIEdxRQRAIAFBAWohASADLQAuQQFxDQEgA0EANgIcIAMgATYCFCADQZcQNgIQIANBCjYCDEEAIQIMRAtBASECAkACQAJAAkACQAJAIAMtACxBAmsOBwUEBAMBAgAECyADIAMvATJBCHI7ATIMAwtBAiECDAELQQQhAgsgA0EBOgAsIAMgAy8BMiACcjsBMgtBLyECDCsLIANBADYCHCADIAE2AhQgA0GEEzYCECADQQs2AgxBACECDEMLQeEBIQIMKQsgASAERgRAQS4hAgxCCyADQQA2AgQgA0ESNgIIIAMgASABEDEiAA0BC0EuIQIMJwsgA0EtNgIcIAMgATYCFCADIAA2AgxBACECDD8LQQAhAAJAIAMoAjgiAkUNACACKAJMIgJFDQAgAyACEQAAIQALIABFDQAgAEEVRw0BIANB2AA2AhwgAyABNgIUIANBsxs2AhAgA0EVNgIMQQAhAgw+C0HMACECDCQLIANBADYCHCADIAE2AhQgA0GzDjYCECADQR02AgxBACECDDwLIAEgBEYEQEHOACECDDwLIAEtAAAiAEEgRg0CIABBOkYNAQsgA0EAOgAsQQkhAgwhCyADKAIEIQAgA0EANgIEIAMgACABEDAiAA0BDAILIAMtAC5BAXEEQEHeASECDCALIAMoAgQhACADQQA2AgQgAyAAIAEQMCIARQ0CIANBKjYCHCADIAA2AgwgAyABQQFqNgIUQQAhAgw4CyADQcsANgIcIAMgADYCDCADIAFBAWo2AhRBACECDDcLIAFBAWohAUHAACECDB0LIAFBAWohAQwsCyABIARGBEBBKyECDDULAkAgAS0AAEEKRgRAIAFBAWohAQwBCyADLQAuQcAAcUUNBgsgAy0AMkGAAXEEQEEAIQACQCADKAI4IgJFDQAgAigCXCICRQ0AIAMgAhEAACEACyAARQ0SIABBFUYEQCADQQU2AhwgAy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ktDS1VCU0NSSUJFVFRQQ0VUU1BBRFRQLw==' + +let wasmBuffer + +Object.defineProperty(module, 'exports', { + get: () => { + return wasmBuffer + ? wasmBuffer + : (wasmBuffer = Buffer.from(wasmBase64, 'base64')) + } +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/llhttp/llhttp_simd-wasm.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/llhttp/llhttp_simd-wasm.js new file mode 100644 index 0000000000000000000000000000000000000000..4508cb14d0a9e9486e107e6ad976ad95af43ae3d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/llhttp/llhttp_simd-wasm.js @@ -0,0 +1,15 @@ +'use strict' + +const { Buffer } = require('node:buffer') + +const wasmBase64 = 'AGFzbQEAAAABJwdgAX8Bf2ADf39/AX9gAn9/AGABfwBgBH9/f38Bf2AAAGADf39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQAEA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAAzU0BQYAAAMAAAAAAAADAQMAAwMDAAACAAAAAAICAgICAgICAgIBAQEBAQEBAQEBAwAAAwAAAAQFAXABExMFAwEAAgYIAX8BQcDZBAsHxQcoBm1lbW9yeQIAC19pbml0aWFsaXplAAgZX19pbmRpcmVjdF9mdW5jdGlvbl90YWJsZQEAC2xsaHR0cF9pbml0AAkYbGxodHRwX3Nob3VsZF9rZWVwX2FsaXZlADcMbGxodHRwX2FsbG9jAAsGbWFsbG9jADkLbGxodHRwX2ZyZWUADARmcmVlAAwPbGxodHRwX2dldF90eXBlAA0VbGxodHRwX2dldF9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tACgLBwAgAC0AKgsHACAALQArCwcAIAAtACkLBwAgAC8BNAsHACAALQAwC0ABBH8gACgCGCEBIAAvAS4hAiAALQAoIQMgACgCOCEEIAAQOCAAIAQ2AjggACADOgAoIAAgAjsBLiAAIAE2AhgLhocCAwd/A34BeyABIAJqIQQCQCAAIgMoAgwiAA0AIAMoAgQEQCADIAE2AgQLIwBBEGsiCSQAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCADKAIcIgJBAmsO/AEB+QECAwQFBgcICQoLDA0ODxAREvgBE/cBFBX2ARYX9QEYGRobHB0eHyD9AfsBIfQBIiMkJSYnKCkqK/MBLC0uLzAxMvIB8QEzNPAB7wE1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk/6AVBRUlPuAe0BVOwBVesBVldYWVrqAVtcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AA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ECA0ACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAMCfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAn8CQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAwJ/AkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJ/AkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCACDuMBAAECAwQFBgcICQoLDA0ODx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EyNgIcIAMgATYCFCADIAA2AgxBACECDO4CCyADKAIEIQAgA0EANgIEIAMgACABEDEiAEUEQCABQQFqIQEMnwILIANBMjYCHCADIAA2AgwgAyABQQFqNgIUQQAhAgztAgsgASAERwRAAkADQCABLQAAQTBrIgBB/wFxQQpPBEBBOiECDNcCCyADKQMgIgtCmbPmzJmz5swZVg0BIAMgC0IKfiIKNwMgIAogAK1C/wGDIgtCf4VWDQEgAyAKIAt8NwMgIAQgAUEBaiIBRw0AC0HAACECDO4CCyADKAIEIQAgA0EANgIEIAMgACABQQFqIgEQMSIADRcM4gILQcAAIQIM7AILIAEgBEYEQEHJACECDOwCCwJAA0ACQCABLQAAQQlrDhgAAqICogKpAqICogKiAqICogKiAqICogKiAqICogKiAqICogKiAqICogKiAgCiAgsgBCABQQFqIgFHDQALQckAIQIM7AILIAFBAWohASADQS9qLQAAQQFxDaUCIANBADYCHCADIAE2AhQgA0GXEDYCECADQQo2AgxBACECDOsCCyABIARHBEADQCABLQAAQSBHDRUgBCABQQFqIgFHDQALQfgAIQIM6wILQfgAIQIM6gILIANBAjoAKAw4C0EAIQIgA0EANgIcIANBvws2AhAgA0ECNgIMIAMgAUEBajYCFAzoAgtBACECDM4CC0ENIQIMzQILQRMhAgzMAgtBFSECDMsCC0EWIQIMygILQRghAgzJAgtBGSECDMgCC0EaIQIMxwILQRshAgzGAgtBHCECDMUCC0EdIQIMxAILQR4hAgzDAgtBHyECDMICC0EgIQIMwQILQSIhAgzAAgtBIyECDL8CC0ElIQIMvgILQeUAIQIMvQILIANBPTYCHCADIAE2AhQgAyAANgIMQQAhAgzVAgsgA0EbNgIcIAMgATYCFCADQaQcNgIQIANBFTYCDEEAIQIM1AILIANBIDYCHCADIAE2AhQgA0GYGjYCECADQRU2AgxBACECDNMCCyADQRM2AhwgAyABNgIUIANBmBo2AhAgA0EVNgIMQQAhAgzSAgsgA0ELNgIcIAMgATYCFCADQZgaNgIQIANBFTYCDEEAIQIM0QILIANBEDYCHCADIAE2A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IAU2AgAMwwILIAMoAgQhACADQgA3AwAgAyAAIAZBAWoiARAuIgBFBEBB4wEhAgyqAgsgA0H1ATYCHCADIAE2AhQgAyAANgIMQQAhAgzCAgtB9AEhAiABIARGDcECIAMoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQbjVAGotAABHDQIgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADMICCyADQYEEOwEoIAMoAgQhACADQgA3AwAgAyAAIAZBAWoiARAuIgANAwwCCyADQQA2AgALQQAhAiADQQA2AhwgAyABNgIUIANB5R82AhAgA0EINgIMDL8CC0HVASECDKUCCyADQfMBNgIcIAMgATYCFCADIAA2AgxBACECDL0CC0EAIQACQCADKAI4IgJFDQAgAigCQCICRQ0AIAMgAhEAACEACyAARQ1uIABBFUcEQCADQQA2AhwgAyABNgIUIANBgg82AhAgA0EgNgIMQQAhAgy9AgsgA0GPATYCHCADIAE2AhQgA0HsGzYCECADQRU2AgxBACECDLwCCyABIARHBEAgA0ENNgIIIAMgATYCBEHTASECDKMCC0HyASECDLsCCyABIARGBEBB8QEhAgy7AgsCQAJAAkAgAS0AAEHIAGsOCwABCAgICAgICAgCCAsgAUEBaiEBQdABIQIMowILIAFBAWohAUHRASECDKICCyABQQFqIQFB0gEhAgyhAgtB8AEhAiABIARGDbkCIAMoAgAiACAEIAFraiEGIAEgAGtBAmohBQNAIAEtAAAgAEG11QBqLQAARw0EIABBAkYNAyAAQQFqIQAgBCABQQFqIgFHDQALIAMgBjYCAAy5AgtB7wEhAiABIARGDbgCIAMoAgAiACAEIAFraiEGIAEgAGtBAWohBQNAIAEtAAAgAEGz1QBqLQAARw0DIABBAUYNAiAAQQFqIQAgBCABQQFqIgFHDQALIAMgBjYCAAy4AgtB7gEhAiABIARGDbcCIAMoAgAiACAEIAFraiEGIAEgAGtBAmohBQNAIAEtAAAgAEGw1QBqLQAARw0CIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBjYCAAy3AgsgAygCBCEAIANCADcDACADIAAgBUEBaiIBECsiAEUNAiADQewBNgIcIAMgATYCFCADIAA2AgxBACECDLYCCyADQQA2AgALIAMoAgQhACADQQA2AgQgAyAAIAEQKyIARQ2cAiADQe0BNgIcIAMgATYCFCADIAA2AgxBACECDLQCC0HPASECDJoCC0EAIQACQCADKAI4IgJFDQAgAigCNCICRQ0AIAMgAhEAACEACwJAIAAEQCAAQRVGDQEgA0EANgIcIAMgATYCFCADQeoNNgIQIANBJjYCDEEAIQIMtAILQc4BIQIMmgILIANB6wE2AhwgAyABNgIUIANBgBs2AhAgA0EVNgIMQQAhAgyyAgsgASAERgRAQesBIQIMsgILIAEtAABBL0YEQCABQQFqIQEMAQsgA0EANgIcIAMgATYCFCADQbI4NgIQIANBCDYCDEEAIQIMsQILQc0BIQIMlwILIAEgBEcEQCADQQ42AgggAyABNgIEQcwBIQIMlwILQeoBIQIMrwILIAEgBEYEQEHpASECDK8CCyABLQAAQTBrIgBB/wFxQQpJBEAgAyAAOgAqIAFBAWohAUHLASECDJYCCyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNlwIgA0HoATYCHCADIAE2AhQgAyAANgIMQQAhAgyuAgsgASAERgRAQecBIQIMrgILAkAgAS0AAEEuRgRAIAFBAWohAQwBCyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNmAIgA0HmATYCHCADIAE2AhQgAyAANgIMQQAhAgyuAgtBygEhAgyUAgsgASAERgRAQeUBIQIMrQILQQAhAEEBIQVBASEHQQAhAgJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAIAEtAABBMGsOCgoJAAECAwQFBggLC0ECDAYLQQMMBQtBBAwEC0EFDAMLQQYMAgtBBwwBC0EICyECQQAhBUEAIQcMAgtBCSECQQEhAEEAIQVBACEHDAELQQAhBUEBIQILIAMgAjoAKyABQQFqIQECQAJAIAMtAC5BEHENAAJAAkACQCADLQAqDgMBAAIECyAHRQ0DDAILIAANAQwCCyAFRQ0BCyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNAiADQeIBNgIcIAMgATYCFCADIAA2AgxBACECDK8CCyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNmgIgA0HjATYCHCADIAE2AhQgAyAANgIMQQAhAgyuAgsgAygCBCEAIANBADYCBCADIAAgARAvIgBFDZgCIANB5AE2AhwgAyABNgIUIAMgADYCDAytAgtByQEhAgyTAgtBACEAAkAgAygCOCICRQ0AIAIoAkQiAkUNACADIAIRAAAhAAsCQCAABEAgAEEVRg0BIANBADYCHCADIAE2AhQgA0GkDTYCECADQSE2AgxBACECDK0CC0HIASECDJMCCyADQeEBNgIcIAMgATYCFCADQdAaNgIQIANBFTYCDEEAIQIMqwILIAEgBEYEQEHhASECDKsCCwJAIAEtAABBIEYEQCADQQA7ATQgAUEBaiEBDAELIANBADYCHCADIAE2AhQgA0GZETYCECADQQk2AgxBACECDKsCC0HHASECDJECCyABIARGBEBB4AEhAgyqAgsCQCABLQAAQTBrQf8BcSICQQpJBEAgAUEBaiEBAkAgAy8BNCIAQZkzSw0AIAMgAEEKbCIAOwE0IABB/v8DcSACQf//A3NLDQAgAyAAIAJqOwE0DAILQQAhAiADQQA2AhwgAyABNgIUIANBlR42AhAgA0ENNgIMDKsCCyADQQA2AhwgAyABNgIUIANBlR42AhAgA0ENNgIMQQAhAgyqAgtBxgEhAgyQAgsgASAERgRAQd8BIQIMqQILAkAgAS0AAEEwa0H/AXEiAkEKSQRAIAFBAWohAQJAIAMvATQiAEGZM0sNACADIABBCmwiADsBNCAAQf7/A3EgAkH//wNzSw0AIAMgACACajsBNAwCC0EAIQIgA0EANgIcIAMgATYCFCADQZUeNgIQIANBDTYCDAyqAgsgA0EANgIcIAMgATYCFCADQZUeNgIQIANBDTYCDEEAIQIMqQILQcUBIQIMjwILIAEgBEYEQEHeASECDKgCCwJAIAEtAABBMGtB/wFxIgJBCkkEQCABQQFqIQECQCADLwE0IgBBmTNLDQAgAyAAQQpsIgA7ATQgAEH+/wNxIAJB//8Dc0sNACADIAAgAmo7ATQMAgtBACECIANBADYCHCADIAE2AhQgA0GVHjYCECADQQ02AgwMqQILIANBADYCHCADIAE2AhQgA0GVHjYCECADQQ02AgxBACECDKgCC0HEASECDI4CCyABIARGBEBB3QEhAgynAgsCQAJAAkACQCABLQAAQQprDhcCAwMAAwMDAwMDAwMDAwMDAwMDAwMDAQMLIAFBAWoMBQsgAUEBaiEBQcMBIQIMjwILIAFBAWohASADQS9qLQAAQQFxDQggA0EANgIcIAMgATYCFCADQY0LNgIQIANBDTYCDEEAIQIMpwILIANBADYCHCADIAE2AhQgA0GNCzYCECADQQ02AgxBACECDKYCCyABIARHBEAgA0EPNgIIIAMgATYCBEEBIQIMjQILQdwBIQIMpQILAkACQANAAkAgAS0AAEEKaw4EAgAAAwALIAQgAUEBaiIBRw0AC0HbASECDKYCCyADKAIEIQAgA0EANgIEIAMgACABEC0iAEUEQCABQQFqIQEMBAsgA0HaATYCHCADIAA2AgwgAyABQQFqNgIUQQAhAgylAgsgAygCBCEAIANBADYCBCADIAAgARAtIgANASABQQFqCyEBQcEBIQIMigILIANB2QE2AhwgAyAANgIMIAMgAUEBajYCFEEAIQIMogILQcIBIQIMiAILIANBL2otAABBAXENASADQQA2AhwgAyABNgIUIANB5Bw2AhAgA0EZNgIMQQAhAgygAgsgASAERgRAQdkBIQIMoAILAkACQAJAIAEtAABBCmsOBAECAgACCyABQQFqIQEMAgsgAUEBaiEBDAELIAMtAC5BwABxRQ0BC0EAIQACQCADKAI4IgJFDQAgAigCPCICRQ0AIAMgAhEAACEACyAARQ2gASAAQRVGBEAgA0HZADYCHCADIAE2AhQgA0G3GjYCECADQRU2AgxBACECDJ8CCyADQQA2AhwgAyABNgIUIANBgA02AhAgA0EbNgIMQQAhAgyeAgsgA0EANgIcIAMgATYCFCADQdwoNgIQIANBAjYCDEEAIQIMnQILIAEgBEcEQCADQQw2AgggAyABNgIEQb8BIQIMhAILQdgBIQIMnAILIAEgBEYEQEHXASECDJwCCwJAAkACQAJAAkAC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sCQAJAIAEtAABBwQBrDhQAPT09PT09PT09PT09PT09PT09AT0LIAFBAWohAUGtASECDPUBCyABQQFqIQFBsAEhAgz0AQsgASAERgRAQcgBIQIMjQILAkACQCABLQAAQdUAaw4LADw8PDw8PDw8PAE8CyABQQFqIQFBrgEhAgz0AQsgAUEBaiEBQa8BIQIM8wELQccBIQIgASAERg2LAiADKAIAIgAgBCABa2ohBSABIABrQQhqIQYCQANAIAEtAAAgAEGE1QBqLQAARw04IABBCEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyMAgsgA0EANgIAIAZBAWohAUEqDDgLIAEgBEYEQEHGASECDIsCCyABLQAAQdAARw04IAFBAWohAUElDDcLQcUBIQIgASAERg2JAiADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEGB1QBqLQAARw02IABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyKAgsgA0EANgIAIAZBAWohAUEODDYLIAEgBEYEQEHEASECDIkCCyABLQAAQcUARw02IAFBAWohAUGrASECDO8BCyABIARGBEBBwwEhAgyIAgsCQAJAAkACQCABLQAAQcIAaw4PAAECOTk5OTk5OTk5OTkDOQsgAUEBaiEBQacBIQIM8QELIAFBAWohAUGoASECDPABCyABQQFqIQFBqQEhAgzvAQsgAUEBaiEBQaoBIQIM7gELQcIBIQIgASAERg2GAiADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEH+1ABqLQAARw0zIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyHAgsgA0EANgIAIAZBAWohAUEUDDMLQcEBIQIgASAERg2FAiADKAIAIgAgBCABa2ohBSABIABrQQRqIQYCQANAIAEtAAAgAEH51ABqLQAARw0yIABBBEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyGAgsgA0EANgIAIAZBAWohAUErDDILQcABIQIgASAERg2EAiADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEt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ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHH1ABqLQAARw0YIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzsAQsgA0EANgIAIAZBAWohAUEXDBgLQaYBIQIgASAERg3qASADKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEHB1ABqLQAARw0XIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzrAQsgA0EANgIAIAZBAWohAUEYDBcLIAEgBEYEQEGlASECDOoBCwJAAkAgAS0AAEHJAGsOBwAZGRkZGQEZCyABQQFqIQFBiwEhAgzRAQsgAUEBaiEBQYwBIQIM0AELQaQBIQIgASAERg3oASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEGm1QBqLQAARw0VIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzpAQsgA0EANgIAIAZBAWohAUEJDBULQaMBIQIgASAERg3nASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEGk1QBqLQAARw0UIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzoAQsgA0EANgIAIAZBAWohAUEfDBQLQaIBIQIgASAERg3mASADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEG+1ABqLQAARw0TIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAznAQsgA0EANgIAIAZBAWohAUECDBMLQaEBIQIgASAERg3lASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYDQCABLQAAIABBvNQAai0AAEcNESAAQQFGDQIgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM5QELIAEgBEYEQEGgASECDOUBC0EBIAEtAABB3wBHDREaIAFBAWohAUGHASECDMsBCyADQQA2AgAgBkEBaiEBQYgBIQIMygELQZ8BIQIgASAERg3iASADKAIAIgAgBCABa2ohBSABIABrQQhqIQYCQANAIAEtAAAgAEGE1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oAgAiACAEIAFraiEFIAEgAGtBBWohBgJAA0AgAS0AACAAQabUAGotAABHDQUgAEEFRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADNkBCyADQQA2AgAgBkEBaiEBQRYMBQtBlAEhAiABIARGDdcBIAMoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQaHVAGotAABHDQQgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADNgBCyADQQA2AgAgBkEBaiEBQRAMBAsgASAERgRAQZMBIQIM1wELAkACQCABLQAAQcMAaw4MAAYGBgYGBgYGBgYBBgsgAUEBaiEBQfkAIQIMvgELIAFBAWohAUH6ACECDL0BC0GSASECIAEgBEYN1QEgAygCACIAIAQgAWtqIQUgASAAa0EFaiEGAkADQCABLQAAIABBoNQAai0AAEcNAiAAQQVGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM1gELIANBADYCACAGQQFqIQFBJAwCCyADQQA2AgAMAgsgASAERgRAQZEBIQIM1AELIAEtAABBzABHDQEgAUEBaiEBQRMLOgApIAMoAgQhACADQQA2AgQgAyAAIAEQLiIADQIMAQtBACECIANBADYCHCADIAE2AhQgA0H+HzYCECADQQY2AgwM0QELQfgAIQIMtwELIANBkAE2AhwgAyABNgIUIAMgADYCDEEAIQIMzwELQQAhAAJAIAMoAjgiAkUNACACKAJAIgJFDQAgAyACEQAAIQALIABFDQAgAEEVRg0BIANBADYCHCADIAE2AhQgA0GCDzYCECADQSA2AgxBACECDM4BC0H3ACECDLQBCyADQY8BNgIcIAMgATYCFCADQewbNgIQIANBFTYCDEEAIQIMzAELIAEgBEYEQEGPASECDMwBCwJAIAEtAABBIEYEQCABQQFqIQEMAQsgA0EANgIcIAMgATYCFCADQZsfNgIQIANBBjYCDEEAIQIMzAELQQIhAgyyAQsDQCABLQAAQSBHDQIgBCABQQFqIgFHDQALQY4BIQIMygELIAEgBEYEQEGNASECDMoBCwJAIAEtAABBCWsOBEoAAEoAC0H1ACECDLABCyADLQApQQVGBEBB9gAhAgywAQtB9AAhAgyvAQsgASAERgRAQYwBIQIMyAELIANBEDYCCCADIAE2AgQMCgsgASAERgRAQYsBIQIMxwELAkAgAS0AAEEJaw4ERwAARwALQfMAIQIMrQELIAEgBEcEQCADQRA2AgggAyABNgIEQfEAIQIMrQELQYoBIQIMxQELAkAgASAERwRAA0AgAS0AAEGg0ABqLQAAIgBBA0cEQAJAIABBAWsOAkkABAtB8AAhAgyvAQsgBCABQQFqIgFHDQALQYgBIQIMxgELQYgBIQIMxQELIANBADYCHCADIAE2AhQgA0HbIDYCECADQQc2AgxBACECDMQBCyABIARGBEBBiQEhAgzEAQsCQAJAAkAgAS0AAEGg0gBqLQAAQQFrDgNGAgABC0HyACECDKwBCyADQQA2AhwgAyABNgIUIANBtBI2AhAgA0EHNgIMQQAhAgzEAQtB6gAhAgyqAQsgASAERwRAIAFBAWohAUHvACECDKoBC0GHASECDMIBCyAEIAEiAEYEQEGGASECDMIBCyAALQAAIgFBL0YEQCAAQQFqIQFB7gAhAgypAQsgAUEJayICQRdLDQEgACEBQQEgAnRBm4CABHENQQwBCyAEIAEiAEYEQEGFASECDMEBCyAALQAAQS9HDQAgAEEBaiEBDAMLQQAhAiADQQA2AhwgAyAANgIUIANB2yA2AhAgA0EHNgIMDL8BCwJAAkACQAJAAkADQCABLQAAQaDOAGotAAAiAEEFRwRAAkACQCAAQQFrDghHBQYHCAAEAQgLQesAIQIMrQELIAFBAWohAUHtACECDKwBCyAEIAFBAWoiAUcNAAtBhAEhAgzDAQsgAUEBagwUCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNHiADQdsANgIcIAMgATYCFCADIAA2AgxBACECDMEBCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNHiADQd0ANgIcIAMgATYCFCADIAA2AgxBACECDMABCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNHiADQfoANgIcIAMgATYCFCADIAA2AgxBACECDL8BCyADQQA2AhwgAyABNgIUIANB+Q82AhAgA0EHNgIMQQAhAgy+AQsgASAERgRAQYMBIQIMvgELAkAgAS0AAEGgzgBqLQAAQQFrDgg+BAUGAAgCAwcLIAFBAWohAQtBAyECDKMBCyABQQFqDA0LQQAhAiADQQA2AhwgA0HREjYCECADQQc2AgwgAyABQQFqNgIUDLoBCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNFiADQdsANgIcIAMgATYCFCADIAA2AgxBACECDLkBCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNFiADQd0ANgIcIAMgATYCFCADIAA2AgxBACECDLgBCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNFiADQfoANgIcIAMgATYCFCADIAA2AgxBACECDLcBCyADQQA2AhwgAyABNgIUIANB+Q82AhAgA0EHNgIMQQAhAgy2AQtB7AAhAgycAQsgASAERgRAQYIBIQIMtQELIAFBAWoMAgsgASAERgRAQYEBIQIMtAELIAFBAWoMAQsgASAERg0BIAFBAWoLIQFBBCECDJgBC0GAASECDLABCwNAIAEtAABBoMwAai0AACIAQQJHBEAgAEEBRwRAQekAIQIMmQELDDELIAQgAUEBaiIBRw0AC0H/ACECDK8BCyABIARGBEBB/gAhAgyvAQsCQCABLQAAQQlrDjcvAwYvBAYGBgYGBgYGBgYGBgYGBgYGBgUGBgIGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYABgsgAUEBagshAUEFIQIMlAELIAFBAWoMBgsgAygCBCEAIANBADYCBCADIAAgARAsIgBFDQggA0HbADYCHCADIAE2AhQgAyAANgIMQQAhAgyrAQsgAygCBCEAIANBADYCBCADIAAgARAsIgBFDQggA0HdADYCHCADIAE2AhQgAyAANgIMQQAhAgyqAQsgAygCBCEAIANBADYCBCADIAAgARAsIgBFDQggA0H6ADYCHCADIAE2AhQgAyAANgIMQQAhAgypAQsgA0EANgIcIAMgATYCFCADQY0UNgIQIANBBzYCDEEAIQIMqAELAkACQAJAAkADQCABLQAAQaDKAGotAAAiAEEFRwRAAkAgAEEBaw4GLgMEBQYABgtB6AAhAgyUAQsgBCABQQFqIgFHDQALQf0AIQIMqwELIAMoAgQhACADQQA2AgQgAyAAIAEQLCIARQ0HIANB2wA2AhwgAyABNgIUIAMgADYCDEEAIQIMqgELIAMoAgQhACADQQA2AgQgAyAAIAEQLCIARQ0HIANB3QA2AhwgAyABNgIUIAMgADYCDEEAIQIMqQELIAMoAgQhACADQQA2AgQgAyAAIAEQLCIARQ0HIANB+gA2AhwgAyABNgIUIAMgADYCDEEAIQIMqAELIANBADYCHCADIAE2AhQgA0HkCDYCECADQQc2AgxBACECDKcBCyABIARGDQEgAUEBagshAUEGIQIMjAELQfwAIQIMpAELAkACQAJAAkADQCABLQAAQaDIAGotAAAiAEEFRwRAIABBAWsOBCkCAwQFCyAEIAFBAWoiAUcNAAtB+wAhAgynAQsgAygCBCEAIANBADYCBCADIAAgARAsIgBFDQMgA0HbADYCHCADIAE2AhQgAyAANgIMQQAhAgymAQsgAygCBCEAIANBADYCBCADIAAgARAsIgBFDQMgA0HdADYCHCADIAE2AhQgAyAANgIMQQAhAgylAQsgAygCBCEAIANBADYCBCADIAAgARAsIgBFDQMgA0H6ADYCHCADIAE2AhQgAyAANgIMQQAhAgykAQsgA0EANgIcIAMgATYCFCADQbwKNgIQIANBBzYCDEEAIQIMowELQc8AIQIMiQELQdEAIQIMiAELQecAIQIMhwELIAEgBEYEQEH6ACECDKABCwJAIAEtAABBCWsOBCAAACAACyABQQFqIQFB5gAhAgyGAQsgASAERgRAQfkAIQIMnwELAkAgAS0AAEEJaw4EHwAAHwALQQAhAAJAIAMoAjgiAkUNACACKAI4IgJFDQAgAyACEQAAIQALIABFBEBB4gEhAgyGAQsgAEEVRwRAIANBADYCHCADIAE2AhQgA0HJDTYCECADQRo2AgxBACECDJ8BCyADQfgANgIcIAMgATYCFCADQeoaNgIQIANBFTYCDEEAIQIMngELIAEgBEcEQCADQQ02AgggAyABNgIEQeQAIQIMhQELQfcAIQIMnQELIAEgBEYEQEH2ACECDJ0BCwJAAkACQCABLQAAQcgAaw4LAAELCwsLCwsLCwILCyABQQFqIQFB3QAhAgyFAQsgAUEBaiEBQeAAIQIMhAELIAFBAWohAUHjACECDIMBC0H1ACECIAEgBEYNmwEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBtdUAai0AAEcNCCAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMnAELIAMoAgQhACADQgA3AwAgAyAAIAZBAWoiARArIgAEQCADQfQANgIcIAMgATYCFCADIAA2AgxBACECDJwBC0HiACECDIIBC0EAIQACQCADKAI4IgJFDQAgAigCNCICRQ0AIAMgAhEAACEACwJAIAAEQCAAQRVGDQEgA0EANgIcIAMgATYCFCADQeoNNgIQIANBJjYCDEEAIQIMnAELQeEAIQIMggELIANB8wA2AhwgAyABNgIUIANBgBs2AhAgA0EVNgIMQQAhAgyaAQsgAy0AKSIAQSNrQQtJDQkCQCAAQQZLDQBBASAAdEHKAHFFDQAMCgtBACECIANBADYCHCADIAE2AhQgA0HtCTYCECADQQg2AgwMmQELQfIAIQIgASAERg2YASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEGz1QBqLQAARw0FIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyZAQsgAygCBCEAIANCADcDACADIAAgBkEBaiIBECsiAARAIANB8QA2AhwgAyABNgIUIAMgADYCDEEAIQIMmQELQd8AIQIMfwtBACEAAkAgAygCOCICRQ0AIAIoAjQiAkUNACADIAIRAAAhAAsCQCAABEAgAEEVRg0BIANBADYCHCADIAE2AhQgA0HqDTYCECADQSY2AgxBACECDJkBC0HeACECDH8LIANB8AA2AhwgAyABNgIUIANBgBs2AhAgA0EVNgIMQQAhAgyXAQsgAy0AKUEhRg0GIANBADYCHCADIAE2AhQgA0GRCjYCECADQQg2AgxBACECDJYBC0HvACECIAEgBEYNlQEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBsN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ABIARGBEBBLiECDEILIANBADYCBCADQRI2AgggAyABIAEQMSIADQELQS4hAgwnCyADQS02AhwgAyABNgIUIAMgADYCDEEAIQIMPwtBACEAAkAgAygCOCICRQ0AIAIoAkwiAkUNACADIAIRAAAhAAsgAEUNACAAQRVHDQEgA0HYADYCHCADIAE2AhQgA0GzGzYCECADQRU2AgxBACECDD4LQcwAIQIMJAsgA0EANgIcIAMgATYCFCADQbMONgIQIANBHTYCDEEAIQIMPAsgASAERgRAQc4AIQIMPAsgAS0AACIAQSBGDQIgAEE6Rg0BCyADQQA6ACxBCSECDCELIAMoAgQhACADQQA2AgQgAyAAIAEQMCIADQEMAgsgAy0ALkEBcQRAQd4BIQIMIAsgAygCBCEAIANBADYCBCADIAAgARAwIgBFDQIgA0EqNgIcIAMgADYCDCADIAFBAWo2AhRBACECDDgLIANBywA2AhwgAyAANgIMIAMgAUEBajYCFEEAIQIMNwsgAUEBaiEBQcAAIQIMHQsgAUEBaiEBDCwLIAEgBEYEQEErIQIMNQsCQCABLQAAQQpGBEAgAUEBaiEBDAELIAMtAC5BwABxRQ0GCyADLQAyQYABcQRAQQAhAAJAIAMoAjgiAkUNACACKAJcIgJFDQAgAyACEQAAIQALIABFDRIgAEEVRgRAIANBBTYCHCADIAE2AhQgA0GbGzYCECADQRU2AgxBACECDDYLIANBADYCHCADIAE2AhQgA0GQDjYCECADQRQ2AgxBACECDDULIANBMmohAiADEDVBACEAAkAgAygCOCIGRQ0AIAYoAigiBkUNACADIAYRAAAhAAsgAA4WAgEABAQEBAQEBAQEBAQEBAQEBAQEAwQLIANBAToAMAsgAiACLwEAQcAAcjsBAAtBKyECDBgLIANBKTYCHCADIAE2AhQgA0GsGTYCECADQRU2AgxBACECDDALIANBADYCHCADIAE2AhQgA0HlCzYCECADQRE2AgxBACECDC8LIANBADYCHCADIAE2AhQgA0GlCzYCECADQQI2AgxBACECDC4LQQEhByADLwEyIgVBCHFFBEAgAykDIEIAUiEHCwJAIAMtADAEQEEBIQAgAy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AAkAgAS0AAEEKaw4EAAEBAAELIAFBAWohAQwBCyABQQFqIQEgAy0ALkEgcQ0AQQAhAiADQQA2AhwgAyABNgIUIANBoSE2AhAgA0EFNgIMDAILQQEhAiABIARHDQALCyAJQRBqJAAgAkUEQCADKAIMIQAMAQsgAyACNgIcQQAhACADKAIEIgFFDQAgAyABIAQgAygCCBEBACIBRQ0AIAMgBDYCFCADIAE2AgwgASEACyAAC74CAQJ/IABBADoAACAAQeQAaiIBQQFrQQA6AAAgAEEAOgACIABBADoAASABQQNrQQA6AAAgAUECa0EAOgAAIABBADoAAyABQQRrQQA6AABBACAAa0EDcSIBIABqIgBBADYCAEHkACABa0F8cSICIABqIgFBBGtBADYCAAJAIAJBCUkNACAAQQA2AgggAEEANgIEIAFBCGtBADYCACABQQxrQQA2AgAgAkEZSQ0AIABBADYCGCAAQQA2AhQgAEEANgIQIABBADYCDCABQRBrQQA2AgAgAUEUa0EANgIAIAFBGGtBADYCACABQRxrQQA2AgAgAiAAQQRxQRhyIgJrIgFBIEkNACAAIAJqIQADQCAAQgA3AxggAEIANwMQIABCADcDCCAAQgA3AwAgAEEgaiEAIAFBIGsiAUEfSw0ACwsLVgEBfwJAIAAoAgwNAAJAAkACQAJAIAAtADEOAwEAAwILIAAoAjgiAUUNACABKAIwIgFFDQAgACABEQAAIgENAwtBAA8LAAsgAEHKGTYCEEEOIQELIAELGgAgACgCDEUEQCAAQd4fNgIQIABBFTYCDAsLFAAgACgCDEEVRgRAIABBADYCDAsLFAAgACgCDEEWRgRAIABBADYCDAsLBwAgACgCDAsHACAAKAIQCwkAIAAgATYCEAsHACAAKAIUCysAAkAgAEEnTw0AQv//////CSAArYhCAYNQDQAgAEECdEHQOGooAgAPCwALFwAgAEEvTwRAAAsgAEECdEHsOWooAgALvwkBAX9B9C0hAQJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAk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FBQUAQanMAAsEAQAAAQBBwcwAC14CAgACAgICAgICAgICAgICAgICAgICAgICAgICAgIAAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAEGpzgALBQECAAEDAEHAzgALXwQFAAAFBQUFBQUFBQUFBQYFBQUFBQUFBQUFBQUABQAHCAUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQAFAAUABQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUAAAAFAEGp0AALBQEBAAEBAEHA0AALAQEAQdrQAAtBAgAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAQanSAAsFAQEAAQEAQcDSAAsBAQBBytIACwYCAAAAAAIAQeHSAAs6AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwBBoNQAC50BTk9VTkNFRUNLT1VUTkVDVEVURUNSSUJFTFVTSEVURUFEU0VBUkNIUkdFQ1RJVklUWUxFTkRBUlZFT1RJRllQVElPTlNDSFNFQVlTVEFUQ0hHRVVFUllPUkRJUkVDVE9SVFJDSFBBUkFNRVRFUlVSQ0VCU0NSSUJFQVJET1dOQUNFSU5ETktDS1VCU0NSSUJFVFRQQ0VUU1BBRFRQLw==' + +let wasmBuffer + +Object.defineProperty(module, 'exports', { + get: () => { + return wasmBuffer + ? wasmBuffer + : (wasmBuffer = Buffer.from(wasmBase64, 'base64')) + } +}) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/llhttp/utils.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/llhttp/utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..681b22b94292f01d04faf0368f57d6391f36b630 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/llhttp/utils.d.ts @@ -0,0 +1,2 @@ +import type { IntDict } from './constants'; +export declare function enumToMap(obj: IntDict, filter?: readonly number[], exceptions?: readonly number[]): IntDict; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/llhttp/utils.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/llhttp/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..95081ead593913a4d8df449c934570d3beee60a1 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/llhttp/utils.js @@ -0,0 +1,12 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.enumToMap = enumToMap; +function enumToMap(obj, filter = [], exceptions = []) { + const emptyFilter = (filter?.length ?? 0) === 0; + const emptyExceptions = (exceptions?.length ?? 0) === 0; + return Object.fromEntries(Object.entries(obj).filter(([, value]) => { + return (typeof value === 'number' && + (emptyFilter || filter.includes(value)) && + (emptyExceptions || !exceptions.includes(value))); + })); +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/mock/mock-agent.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/mock/mock-agent.js new file mode 100644 index 0000000000000000000000000000000000000000..3079b15ec8ceefa4a2e6c578e225c7d8fcca4646 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/mock/mock-agent.js @@ -0,0 +1,230 @@ +'use strict' + +const { kClients } = require('../core/symbols') +const Agent = require('../dispatcher/agent') +const { + kAgent, + kMockAgentSet, + kMockAgentGet, + kDispatches, + kIsMockActive, + kNetConnect, + kGetNetConnect, + kOptions, + kFactory, + kMockAgentRegisterCallHistory, + kMockAgentIsCallHistoryEnabled, + kMockAgentAddCallHistoryLog, + kMockAgentMockCallHistoryInstance, + kMockAgentAcceptsNonStandardSearchParameters, + kMockCallHistoryAddLog, + kIgnoreTrailingSlash +} = require('./mock-symbols') +const MockClient = require('./mock-client') +const MockPool = require('./mock-pool') +const { matchValue, normalizeSearchParams, buildAndValidateMockOptions } = require('./mock-utils') +const { InvalidArgumentError, UndiciError } = require('../core/errors') +const Dispatcher = require('../dispatcher/dispatcher') +const PendingInterceptorsFormatter = require('./pending-interceptors-formatter') +const { MockCallHistory } = require('./mock-call-history') + +class MockAgent extends Dispatcher { + constructor (opts) { + super(opts) + + const mockOptions = buildAndValidateMockOptions(opts) + + this[kNetConnect] = true + this[kIsMockActive] = true + this[kMockAgentIsCallHistoryEnabled] = mockOptions?.enableCallHistory ?? false + this[kMockAgentAcceptsNonStandardSearchParameters] = mockOptions?.acceptNonStandardSearchParameters ?? false + this[kIgnoreTrailingSlash] = mockOptions?.ignoreTrailingSlash ?? false + + // Instantiate Agent and encapsulate + if (opts?.agent && typeof opts.agent.dispatch !== 'function') { + throw new InvalidArgumentError('Argument opts.agent must implement Agent') + } + const agent = opts?.agent ? opts.agent : new Agent(opts) + this[kAgent] = agent + + this[kClients] = agent[kClients] + this[kOptions] = mockOptions + + if (this[kMockAgentIsCallHistoryEnabled]) { + this[kMockAgentRegisterCallHistory]() + } + } + + get (origin) { + const originKey = this[kIgnoreTrailingSlash] + ? origin.replace(/\/$/, '') + : origin + + let dispatcher = this[kMockAgentGet](originKey) + + if (!dispatcher) { + dispatcher = this[kFactory](originKey) + this[kMockAgentSet](originKey, dispatcher) + } + return dispatcher + } + + dispatch (opts, handler) { + // Call MockAgent.get to perform additional setup before dispatching as normal + this.get(opts.origin) + + this[kMockAgentAddCallHistoryLog](opts) + + const acceptNonStandardSearchParameters = this[kMockAgentAcceptsNonStandardSearchParameters] + + const dispatchOpts = { ...opts } + + if (acceptNonStandardSearchParameters && dispatchOpts.path) { + const [path, searchParams] = dispatchOpts.path.split('?') + const normalizedSearchParams = normalizeSearchParams(searchParams, acceptNonStandardSearchParameters) + dispatchOpts.path = `${path}?${normalizedSearchParams}` + } + + return this[kAgent].dispatch(dispatchOpts, handler) + } + + async close () { + this.clearCallHistory() + await this[kAgent].close() + this[kClients].clear() + } + + deactivate () { + this[kIsMockActive] = false + } + + activate () { + this[kIsMockActive] = true + } + + enableNetConnect (matcher) { + if (typeof matcher === 'string' || typeof matcher === 'function' || matcher instanceof RegExp) { + if (Array.isArray(this[kNetConnect])) { + this[kNetConnect].push(matcher) + } else { + this[kNetConnect] = [matcher] + } + } else if (typeof matcher === 'undefined') { + this[kNetConnect] = true + } else { + throw new InvalidArgumentError('Unsupported matcher. Must be one of String|Function|RegExp.') + } + } + + disableNetConnect () { + this[kNetConnect] = false + } + + enableCallHistory () { + this[kMockAgentIsCallHistoryEnabled] = true + + return this + } + + disableCallHistory () { + this[kMockAgentIsCallHistoryEnabled] = false + + return this + } + + getCallHistory () { + return this[kMockAgentMockCallHistoryInstance] + } + + clearCallHistory () { + if (this[kMockAgentMockCallHistoryInstance] !== undefined) { + this[kMockAgentMockCallHistoryInstance].clear() + } + } + + // This is required to bypass issues caused by using global symbols - see: + // https://github.com/nodejs/undici/issues/1447 + get isMockActive () { + return this[kIsMockActive] + } + + [kMockAgentRegisterCallHistory] () { + if (this[kMockAgentMockCallHistoryInstance] === undefined) { + this[kMockAgentMockCallHistoryInstance] = new MockCallHistory() + } + } + + [kMockAgentAddCallHistoryLog] (opts) { + if (this[kMockAgentIsCallHistoryEnabled]) { + // additional setup when enableCallHistory class method is used after mockAgent instantiation + this[kMockAgentRegisterCallHistory]() + + // add call history log on every call (intercepted or not) + this[kMockAgentMockCallHistoryInstance][kMockCallHistoryAddLog](opts) + } + } + + [kMockAgentSet] (origin, dispatcher) { + this[kClients].set(origin, { count: 0, dispatcher }) + } + + [kFactory] (origin) { + const mockOptions = Object.assign({ agent: this }, this[kOptions]) + return this[kOptions] && this[kOptions].connections === 1 + ? new MockClient(origin, mockOptions) + : new MockPool(origin, mockOptions) + } + + [kMockAgentGet] (origin) { + // First check if we can immediately find it + const result = this[kClients].get(origin) + if (result?.dispatcher) { + return result.dispatcher + } + + // If the origin is not a string create a dummy parent pool and return to user + if (typeof origin !== 'string') { + const dispatcher = this[kFactory]('http://localhost:9999') + this[kMockAgentSet](origin, dispatcher) + return dispatcher + } + + // If we match, create a pool and assign the same dispatches + for (const [keyMatcher, result] of Array.from(this[kClients])) { + if (result && typeof keyMatcher !== 'string' && matchValue(keyMatcher, origin)) { + const dispatcher = this[kFactory](origin) + this[kMockAgentSet](origin, dispatcher) + dispatcher[kDispatches] = result.dispatcher[kDispatches] + return dispatcher + } + } + } + + [kGetNetConnect] () { + return this[kNetConnect] + } + + pendingInterceptors () { + const mockAgentClients = this[kClients] + + return Array.from(mockAgentClients.entries()) + .flatMap(([origin, result]) => result.dispatcher[kDispatches].map(dispatch => ({ ...dispatch, origin }))) + .filter(({ pending }) => pending) + } + + assertNoPendingInterceptors ({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) { + const pending = this.pendingInterceptors() + + if (pending.length === 0) { + return + } + + throw new UndiciError( + pending.length === 1 + ? `1 interceptor is pending:\n\n${pendingInterceptorsFormatter.format(pending)}`.trim() + : `${pending.length} interceptors are pending:\n\n${pendingInterceptorsFormatter.format(pending)}`.trim() + ) + } +} + +module.exports = MockAgent diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/mock/mock-call-history.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/mock/mock-call-history.js new file mode 100644 index 0000000000000000000000000000000000000000..d4a92b2b24bc77c370a007df2a14c959f2b208de --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/mock/mock-call-history.js @@ -0,0 +1,248 @@ +'use strict' + +const { kMockCallHistoryAddLog } = require('./mock-symbols') +const { InvalidArgumentError } = require('../core/errors') + +function handleFilterCallsWithOptions (criteria, options, handler, store) { + switch (options.operator) { + case 'OR': + store.push(...handler(criteria)) + + return store + case 'AND': + return handler.call({ logs: store }, criteria) + default: + // guard -- should never happens because buildAndValidateFilterCallsOptions is called before + throw new InvalidArgumentError('options.operator must to be a case insensitive string equal to \'OR\' or \'AND\'') + } +} + +function buildAndValidateFilterCallsOptions (options = {}) { + const finalOptions = {} + + if ('operator' in options) { + if (typeof options.operator !== 'string' || (options.operator.toUpperCase() !== 'OR' && options.operator.toUpperCase() !== 'AND')) { + throw new InvalidArgumentError('options.operator must to be a case insensitive string equal to \'OR\' or \'AND\'') + } + + return { + ...finalOptions, + operator: options.operator.toUpperCase() + } + } + + return finalOptions +} + +function makeFilterCalls (parameterName) { + return (parameterValue) => { + if (typeof parameterValue === 'string' || parameterValue == null) { + return this.logs.filter((log) => { + return log[parameterName] === parameterValue + }) + } + if (parameterValue instanceof RegExp) { + return this.logs.filter((log) => { + return parameterValue.test(log[parameterName]) + }) + } + + throw new InvalidArgumentError(`${parameterName} parameter should be one of string, regexp, undefined or null`) + } +} +function computeUrlWithMaybeSearchParameters (requestInit) { + // path can contains query url parameters + // or query can contains query url parameters + try { + const url = new URL(requestInit.path, requestInit.origin) + + // requestInit.path contains query url parameters + // requestInit.query is then undefined + if (url.search.length !== 0) { + return url + } + + // requestInit.query can be populated here + url.search = new URLSearchParams(requestInit.query).toString() + + return url + } catch (error) { + throw new InvalidArgumentError('An error occurred when computing MockCallHistoryLog.url', { cause: error }) + } +} + +class MockCallHistoryLog { + constructor (requestInit = {}) { + this.body = requestInit.body + this.headers = requestInit.headers + this.method = requestInit.method + + const url = computeUrlWithMaybeSearchParameters(requestInit) + + this.fullUrl = url.toString() + this.origin = url.origin + this.path = url.pathname + this.searchParams = Object.fromEntries(url.searchParams) + this.protocol = url.protocol + this.host = url.host + this.port = url.port + this.hash = url.hash + } + + toMap () { + return new Map([ + ['protocol', this.protocol], + ['host', this.host], + ['port', this.port], + ['origin', this.origin], + ['path', this.path], + ['hash', this.hash], + ['searchParams', this.searchParams], + ['fullUrl', this.fullUrl], + ['method', this.method], + ['body', this.body], + ['headers', this.headers]] + ) + } + + toString () { + const options = { betweenKeyValueSeparator: '->', betweenPairSeparator: '|' } + let result = '' + + this.toMap().forEach((value, key) => { + if (typeof value === 'string' || value === undefined || value === null) { + result = `${result}${key}${options.betweenKeyValueSeparator}${value}${options.betweenPairSeparator}` + } + if ((typeof value === 'object' && value !== null) || Array.isArray(value)) { + result = `${result}${key}${options.betweenKeyValueSeparator}${JSON.stringify(value)}${options.betweenPairSeparator}` + } + // maybe miss something for non Record / Array headers and searchParams here + }) + + // delete last betweenPairSeparator + return result.slice(0, -1) + } +} + +class MockCallHistory { + logs = [] + + calls () { + return this.logs + } + + firstCall () { + return this.logs.at(0) + } + + lastCall () { + return this.logs.at(-1) + } + + nthCall (number) { + if (typeof number !== 'number') { + throw new InvalidArgumentError('nthCall must be called with a number') + } + if (!Number.isInteger(number)) { + throw new InvalidArgumentError('nthCall must be called with an integer') + } + if (Math.sign(number) !== 1) { + throw new InvalidArgumentError('nthCall must be called with a positive value. use firstCall or lastCall instead') + } + + // non zero based index. this is more human readable + return this.logs.at(number - 1) + } + + filterCalls (criteria, options) { + // perf + if (this.logs.length === 0) { + return this.logs + } + if (typeof criteria === 'function') { + return this.logs.filter(criteria) + } + if (criteria instanceof RegExp) { + return this.logs.filter((log) => { + return criteria.test(log.toString()) + }) + } + if (typeof criteria === 'object' && criteria !== null) { + // no criteria - returning all logs + if (Object.keys(criteria).length === 0) { + return this.logs + } + + const finalOptions = { operator: 'OR', ...buildAndValidateFilterCallsOptions(options) } + + let maybeDuplicatedLogsFiltered = [] + if ('protocol' in criteria) { + maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.protocol, finalOptions, this.filterCallsByProtocol, maybeDuplicatedLogsFiltered) + } + if ('host' in criteria) { + maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.host, finalOptions, this.filterCallsByHost, maybeDuplicatedLogsFiltered) + } + if ('port' in criteria) { + maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.port, finalOptions, this.filterCallsByPort, maybeDuplicatedLogsFiltered) + } + if ('origin' in criteria) { + maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.origin, finalOptions, this.filterCallsByOrigin, maybeDuplicatedLogsFiltered) + } + if ('path' in criteria) { + maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.path, finalOptions, this.filterCallsByPath, maybeDuplicatedLogsFiltered) + } + if ('hash' in criteria) { + maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.hash, finalOptions, this.filterCallsByHash, maybeDuplicatedLogsFiltered) + } + if ('fullUrl' in criteria) { + maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.fullUrl, finalOptions, this.filterCallsByFullUrl, maybeDuplicatedLogsFiltered) + } + if ('method' in criteria) { + maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.method, finalOptions, this.filterCallsByMethod, maybeDuplicatedLogsFiltered) + } + + const uniqLogsFiltered = [...new Set(maybeDuplicatedLogsFiltered)] + + return uniqLogsFiltered + } + + throw new InvalidArgumentError('criteria parameter should be one of function, regexp, or object') + } + + filterCallsByProtocol = makeFilterCalls.call(this, 'protocol') + + filterCallsByHost = makeFilterCalls.call(this, 'host') + + filterCallsByPort = makeFilterCalls.call(this, 'port') + + filterCallsByOrigin = makeFilterCalls.call(this, 'origin') + + filterCallsByPath = makeFilterCalls.call(this, 'path') + + filterCallsByHash = makeFilterCalls.call(this, 'hash') + + filterCallsByFullUrl = makeFilterCalls.call(this, 'fullUrl') + + filterCallsByMethod = makeFilterCalls.call(this, 'method') + + clear () { + this.logs = [] + } + + [kMockCallHistoryAddLog] (requestInit) { + const log = new MockCallHistoryLog(requestInit) + + this.logs.push(log) + + return log + } + + * [Symbol.iterator] () { + for (const log of this.calls()) { + yield log + } + } +} + +module.exports.MockCallHistory = MockCallHistory +module.exports.MockCallHistoryLog = MockCallHistoryLog diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/mock/mock-client.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/mock/mock-client.js new file mode 100644 index 0000000000000000000000000000000000000000..b3be7ab3b917c59a8cbe7d2ce33a25721e039f8e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/mock/mock-client.js @@ -0,0 +1,68 @@ +'use strict' + +const { promisify } = require('node:util') +const Client = require('../dispatcher/client') +const { buildMockDispatch } = require('./mock-utils') +const { + kDispatches, + kMockAgent, + kClose, + kOriginalClose, + kOrigin, + kOriginalDispatch, + kConnected, + kIgnoreTrailingSlash +} = require('./mock-symbols') +const { MockInterceptor } = require('./mock-interceptor') +const Symbols = require('../core/symbols') +const { InvalidArgumentError } = require('../core/errors') + +/** + * MockClient provides an API that extends the Client to influence the mockDispatches. + */ +class MockClient extends Client { + constructor (origin, opts) { + if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { + throw new InvalidArgumentError('Argument opts.agent must implement Agent') + } + + super(origin, opts) + + this[kMockAgent] = opts.agent + this[kOrigin] = origin + this[kIgnoreTrailingSlash] = opts.ignoreTrailingSlash ?? false + this[kDispatches] = [] + this[kConnected] = 1 + this[kOriginalDispatch] = this.dispatch + this[kOriginalClose] = this.close.bind(this) + + this.dispatch = buildMockDispatch.call(this) + this.close = this[kClose] + } + + get [Symbols.kConnected] () { + return this[kConnected] + } + + /** + * Sets up the base interceptor for mocking replies from undici. + */ + intercept (opts) { + return new MockInterceptor( + opts && { ignoreTrailingSlash: this[kIgnoreTrailingSlash], ...opts }, + this[kDispatches] + ) + } + + cleanMocks () { + this[kDispatches] = [] + } + + async [kClose] () { + await promisify(this[kOriginalClose])() + this[kConnected] = 0 + this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) + } +} + +module.exports = MockClient diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/mock/mock-errors.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/mock/mock-errors.js new file mode 100644 index 0000000000000000000000000000000000000000..ebdc786c56e7a01821fc8f15c07c49314891d9c3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/mock/mock-errors.js @@ -0,0 +1,19 @@ +'use strict' + +const { UndiciError } = require('../core/errors') + +/** + * The request does not match any registered mock dispatches. + */ +class MockNotMatchedError extends UndiciError { + constructor (message) { + super(message) + this.name = 'MockNotMatchedError' + this.message = message || 'The request does not match any registered mock dispatches' + this.code = 'UND_MOCK_ERR_MOCK_NOT_MATCHED' + } +} + +module.exports = { + MockNotMatchedError +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/mock/mock-interceptor.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/mock/mock-interceptor.js new file mode 100644 index 0000000000000000000000000000000000000000..1ea7aac486da93faed6283ca9e4476030ccfc977 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/mock/mock-interceptor.js @@ -0,0 +1,209 @@ +'use strict' + +const { getResponseData, buildKey, addMockDispatch } = require('./mock-utils') +const { + kDispatches, + kDispatchKey, + kDefaultHeaders, + kDefaultTrailers, + kContentLength, + kMockDispatch, + kIgnoreTrailingSlash +} = require('./mock-symbols') +const { InvalidArgumentError } = require('../core/errors') +const { serializePathWithQuery } = require('../core/util') + +/** + * Defines the scope API for an interceptor reply + */ +class MockScope { + constructor (mockDispatch) { + this[kMockDispatch] = mockDispatch + } + + /** + * Delay a reply by a set amount in ms. + */ + delay (waitInMs) { + if (typeof waitInMs !== 'number' || !Number.isInteger(waitInMs) || waitInMs <= 0) { + throw new InvalidArgumentError('waitInMs must be a valid integer > 0') + } + + this[kMockDispatch].delay = waitInMs + return this + } + + /** + * For a defined reply, never mark as consumed. + */ + persist () { + this[kMockDispatch].persist = true + return this + } + + /** + * Allow one to define a reply for a set amount of matching requests. + */ + times (repeatTimes) { + if (typeof repeatTimes !== 'number' || !Number.isInteger(repeatTimes) || repeatTimes <= 0) { + throw new InvalidArgumentError('repeatTimes must be a valid integer > 0') + } + + this[kMockDispatch].times = repeatTimes + return this + } +} + +/** + * Defines an interceptor for a Mock + */ +class MockInterceptor { + constructor (opts, mockDispatches) { + if (typeof opts !== 'object') { + throw new InvalidArgumentError('opts must be an object') + } + if (typeof opts.path === 'undefined') { + throw new InvalidArgumentError('opts.path must be defined') + } + if (typeof opts.method === 'undefined') { + opts.method = 'GET' + } + // See https://github.com/nodejs/undici/issues/1245 + // As per RFC 3986, clients are not supposed to send URI + // fragments to servers when they retrieve a document, + if (typeof opts.path === 'string') { + if (opts.query) { + opts.path = serializePathWithQuery(opts.path, opts.query) + } else { + // Matches https://github.com/nodejs/undici/blob/main/lib/web/fetch/index.js#L1811 + const parsedURL = new URL(opts.path, 'data://') + opts.path = parsedURL.pathname + parsedURL.search + } + } + if (typeof opts.method === 'string') { + opts.method = opts.method.toUpperCase() + } + + this[kDispatchKey] = buildKey(opts) + this[kDispatches] = mockDispatches + this[kIgnoreTrailingSlash] = opts.ignoreTrailingSlash ?? false + this[kDefaultHeaders] = {} + this[kDefaultTrailers] = {} + this[kContentLength] = false + } + + createMockScopeDispatchData ({ statusCode, data, responseOptions }) { + const responseData = getResponseData(data) + const contentLength = this[kContentLength] ? { 'content-length': responseData.length } : {} + const headers = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers } + const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers } + + return { statusCode, data, headers, trailers } + } + + validateReplyParameters (replyParameters) { + if (typeof replyParameters.statusCode === 'undefined') { + throw new InvalidArgumentError('statusCode must be defined') + } + if (typeof replyParameters.responseOptions !== 'object' || replyParameters.responseOptions === null) { + throw new InvalidArgumentError('responseOptions must be an object') + } + } + + /** + * Mock an undici request with a defined reply. + */ + reply (replyOptionsCallbackOrStatusCode) { + // Values of reply aren't available right now as they + // can only be available when the reply callback is invoked. + if (typeof replyOptionsCallbackOrStatusCode === 'function') { + // We'll first wrap the provided callback in another function, + // this function will properly resolve the data from the callback + // when invoked. + const wrappedDefaultsCallback = (opts) => { + // Our reply options callback contains the parameter for statusCode, data and options. + const resolvedData = replyOptionsCallbackOrStatusCode(opts) + + // Check if it is in the right format + if (typeof resolvedData !== 'object' || resolvedData === null) { + throw new InvalidArgumentError('reply options callback must return an object') + } + + const replyParameters = { data: '', responseOptions: {}, ...resolvedData } + this.validateReplyParameters(replyParameters) + // Since the values can be obtained immediately we return them + // from this higher order function that will be resolved later. + return { + ...this.createMockScopeDispatchData(replyParameters) + } + } + + // Add usual dispatch data, but this time set the data parameter to function that will eventually provide data. + const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback, { ignoreTrailingSlash: this[kIgnoreTrailingSlash] }) + return new MockScope(newMockDispatch) + } + + // We can have either one or three parameters, if we get here, + // we should have 1-3 parameters. So we spread the arguments of + // this function to obtain the parameters, since replyData will always + // just be the statusCode. + const replyParameters = { + statusCode: replyOptionsCallbackOrStatusCode, + data: arguments[1] === undefined ? '' : arguments[1], + responseOptions: arguments[2] === undefined ? {} : arguments[2] + } + this.validateReplyParameters(replyParameters) + + // Send in-already provided data like usual + const dispatchData = this.createMockScopeDispatchData(replyParameters) + const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData, { ignoreTrailingSlash: this[kIgnoreTrailingSlash] }) + return new MockScope(newMockDispatch) + } + + /** + * Mock an undici request with a defined error. + */ + replyWithError (error) { + if (typeof error === 'undefined') { + throw new InvalidArgumentError('error must be defined') + } + + const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error }, { ignoreTrailingSlash: this[kIgnoreTrailingSlash] }) + return new MockScope(newMockDispatch) + } + + /** + * Set default reply headers on the interceptor for subsequent replies + */ + defaultReplyHeaders (headers) { + if (typeof headers === 'undefined') { + throw new InvalidArgumentError('headers must be defined') + } + + this[kDefaultHeaders] = headers + return this + } + + /** + * Set default reply trailers on the interceptor for subsequent replies + */ + defaultReplyTrailers (trailers) { + if (typeof trailers === 'undefined') { + throw new InvalidArgumentError('trailers must be defined') + } + + this[kDefaultTrailers] = trailers + return this + } + + /** + * Set reply content length header for replies on the interceptor + */ + replyContentLength () { + this[kContentLength] = true + return this + } +} + +module.exports.MockInterceptor = MockInterceptor +module.exports.MockScope = MockScope diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/mock/mock-pool.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/mock/mock-pool.js new file mode 100644 index 0000000000000000000000000000000000000000..2121e3c99a308f0a7e0c7078d3e39658584fd6a5 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/mock/mock-pool.js @@ -0,0 +1,68 @@ +'use strict' + +const { promisify } = require('node:util') +const Pool = require('../dispatcher/pool') +const { buildMockDispatch } = require('./mock-utils') +const { + kDispatches, + kMockAgent, + kClose, + kOriginalClose, + kOrigin, + kOriginalDispatch, + kConnected, + kIgnoreTrailingSlash +} = require('./mock-symbols') +const { MockInterceptor } = require('./mock-interceptor') +const Symbols = require('../core/symbols') +const { InvalidArgumentError } = require('../core/errors') + +/** + * MockPool provides an API that extends the Pool to influence the mockDispatches. + */ +class MockPool extends Pool { + constructor (origin, opts) { + if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { + throw new InvalidArgumentError('Argument opts.agent must implement Agent') + } + + super(origin, opts) + + this[kMockAgent] = opts.agent + this[kOrigin] = origin + this[kIgnoreTrailingSlash] = opts.ignoreTrailingSlash ?? false + this[kDispatches] = [] + this[kConnected] = 1 + this[kOriginalDispatch] = this.dispatch + this[kOriginalClose] = this.close.bind(this) + + this.dispatch = buildMockDispatch.call(this) + this.close = this[kClose] + } + + get [Symbols.kConnected] () { + return this[kConnected] + } + + /** + * Sets up the base interceptor for mocking replies from undici. + */ + intercept (opts) { + return new MockInterceptor( + opts && { ignoreTrailingSlash: this[kIgnoreTrailingSlash], ...opts }, + this[kDispatches] + ) + } + + cleanMocks () { + this[kDispatches] = [] + } + + async [kClose] () { + await promisify(this[kOriginalClose])() + this[kConnected] = 0 + this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) + } +} + +module.exports = MockPool diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/mock/mock-symbols.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/mock/mock-symbols.js new file mode 100644 index 0000000000000000000000000000000000000000..940dbe6e3f8596a1e4d92120a5344435ce877d25 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/mock/mock-symbols.js @@ -0,0 +1,31 @@ +'use strict' + +module.exports = { + kAgent: Symbol('agent'), + kOptions: Symbol('options'), + kFactory: Symbol('factory'), + kDispatches: Symbol('dispatches'), + kDispatchKey: Symbol('dispatch key'), + kDefaultHeaders: Symbol('default headers'), + kDefaultTrailers: Symbol('default trailers'), + kContentLength: Symbol('content length'), + kMockAgent: Symbol('mock agent'), + kMockAgentSet: Symbol('mock agent set'), + kMockAgentGet: Symbol('mock agent get'), + kMockDispatch: Symbol('mock dispatch'), + kClose: Symbol('close'), + kOriginalClose: Symbol('original agent close'), + kOriginalDispatch: Symbol('original dispatch'), + kOrigin: Symbol('origin'), + kIsMockActive: Symbol('is mock active'), + kNetConnect: Symbol('net connect'), + kGetNetConnect: Symbol('get net connect'), + kConnected: Symbol('connected'), + kIgnoreTrailingSlash: Symbol('ignore trailing slash'), + kMockAgentMockCallHistoryInstance: Symbol('mock agent mock call history name'), + kMockAgentRegisterCallHistory: Symbol('mock agent register mock call history'), + kMockAgentAddCallHistoryLog: Symbol('mock agent add call history log'), + kMockAgentIsCallHistoryEnabled: Symbol('mock agent is call history enabled'), + kMockAgentAcceptsNonStandardSearchParameters: Symbol('mock agent accepts non standard search parameters'), + kMockCallHistoryAddLog: Symbol('mock call history add log') +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/mock/mock-utils.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/mock/mock-utils.js new file mode 100644 index 0000000000000000000000000000000000000000..822d45d153ff299bfa8badcf501c23318c70cd80 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/mock/mock-utils.js @@ -0,0 +1,433 @@ +'use strict' + +const { MockNotMatchedError } = require('./mock-errors') +const { + kDispatches, + kMockAgent, + kOriginalDispatch, + kOrigin, + kGetNetConnect +} = require('./mock-symbols') +const { serializePathWithQuery } = require('../core/util') +const { STATUS_CODES } = require('node:http') +const { + types: { + isPromise + } +} = require('node:util') +const { InvalidArgumentError } = require('../core/errors') + +function matchValue (match, value) { + if (typeof match === 'string') { + return match === value + } + if (match instanceof RegExp) { + return match.test(value) + } + if (typeof match === 'function') { + return match(value) === true + } + return false +} + +function lowerCaseEntries (headers) { + return Object.fromEntries( + Object.entries(headers).map(([headerName, headerValue]) => { + return [headerName.toLocaleLowerCase(), headerValue] + }) + ) +} + +/** + * @param {import('../../index').Headers|string[]|Record} headers + * @param {string} key + */ +function getHeaderByName (headers, key) { + if (Array.isArray(headers)) { + for (let i = 0; i < headers.length; i += 2) { + if (headers[i].toLocaleLowerCase() === key.toLocaleLowerCase()) { + return headers[i + 1] + } + } + + return undefined + } else if (typeof headers.get === 'function') { + return headers.get(key) + } else { + return lowerCaseEntries(headers)[key.toLocaleLowerCase()] + } +} + +/** @param {string[]} headers */ +function buildHeadersFromArray (headers) { // fetch HeadersList + const clone = headers.slice() + const entries = [] + for (let index = 0; index < clone.length; index += 2) { + entries.push([clone[index], clone[index + 1]]) + } + return Object.fromEntries(entries) +} + +function matchHeaders (mockDispatch, headers) { + if (typeof mockDispatch.headers === 'function') { + if (Array.isArray(headers)) { // fetch HeadersList + headers = buildHeadersFromArray(headers) + } + return mockDispatch.headers(headers ? lowerCaseEntries(headers) : {}) + } + if (typeof mockDispatch.headers === 'undefined') { + return true + } + if (typeof headers !== 'object' || typeof mockDispatch.headers !== 'object') { + return false + } + + for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch.headers)) { + const headerValue = getHeaderByName(headers, matchHeaderName) + + if (!matchValue(matchHeaderValue, headerValue)) { + return false + } + } + return true +} + +function normalizeSearchParams (query) { + if (typeof query !== 'string') { + return query + } + + const originalQp = new URLSearchParams(query) + const normalizedQp = new URLSearchParams() + + for (let [key, value] of originalQp.entries()) { + key = key.replace('[]', '') + + const valueRepresentsString = /^(['"]).*\1$/.test(value) + if (valueRepresentsString) { + normalizedQp.append(key, value) + continue + } + + if (value.includes(',')) { + const values = value.split(',') + for (const v of values) { + normalizedQp.append(key, v) + } + continue + } + + normalizedQp.append(key, value) + } + + return normalizedQp +} + +function safeUrl (path) { + if (typeof path !== 'string') { + return path + } + const pathSegments = path.split('?', 3) + if (pathSegments.length !== 2) { + return path + } + + const qp = new URLSearchParams(pathSegments.pop()) + qp.sort() + return [...pathSegments, qp.toString()].join('?') +} + +function matchKey (mockDispatch, { path, method, body, headers }) { + const pathMatch = matchValue(mockDispatch.path, path) + const methodMatch = matchValue(mockDispatch.method, method) + const bodyMatch = typeof mockDispatch.body !== 'undefined' ? matchValue(mockDispatch.body, body) : true + const headersMatch = matchHeaders(mockDispatch, headers) + return pathMatch && methodMatch && bodyMatch && headersMatch +} + +function getResponseData (data) { + if (Buffer.isBuffer(data)) { + return data + } else if (data instanceof Uint8Array) { + return data + } else if (data instanceof ArrayBuffer) { + return data + } else if (typeof data === 'object') { + return JSON.stringify(data) + } else if (data) { + return data.toString() + } else { + return '' + } +} + +function getMockDispatch (mockDispatches, key) { + const basePath = key.query ? serializePathWithQuery(key.path, key.query) : key.path + const resolvedPath = typeof basePath === 'string' ? safeUrl(basePath) : basePath + + const resolvedPathWithoutTrailingSlash = removeTrailingSlash(resolvedPath) + + // Match path + let matchedMockDispatches = mockDispatches + .filter(({ consumed }) => !consumed) + .filter(({ path, ignoreTrailingSlash }) => { + return ignoreTrailingSlash + ? matchValue(removeTrailingSlash(safeUrl(path)), resolvedPathWithoutTrailingSlash) + : matchValue(safeUrl(path), resolvedPath) + }) + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`) + } + + // Match method + matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue(method, key.method)) + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}' on path '${resolvedPath}'`) + } + + // Match body + matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== 'undefined' ? matchValue(body, key.body) : true) + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}' on path '${resolvedPath}'`) + } + + // Match headers + matchedMockDispatches = matchedMockDispatches.filter((mockDispatch) => matchHeaders(mockDispatch, key.headers)) + if (matchedMockDispatches.length === 0) { + const headers = typeof key.headers === 'object' ? JSON.stringify(key.headers) : key.headers + throw new MockNotMatchedError(`Mock dispatch not matched for headers '${headers}' on path '${resolvedPath}'`) + } + + return matchedMockDispatches[0] +} + +function addMockDispatch (mockDispatches, key, data, opts) { + const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false, ...opts } + const replyData = typeof data === 'function' ? { callback: data } : { ...data } + const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } } + mockDispatches.push(newMockDispatch) + return newMockDispatch +} + +function deleteMockDispatch (mockDispatches, key) { + const index = mockDispatches.findIndex(dispatch => { + if (!dispatch.consumed) { + return false + } + return matchKey(dispatch, key) + }) + if (index !== -1) { + mockDispatches.splice(index, 1) + } +} + +/** + * @param {string} path Path to remove trailing slash from + */ +function removeTrailingSlash (path) { + while (path.endsWith('/')) { + path = path.slice(0, -1) + } + + if (path.length === 0) { + path = '/' + } + + return path +} + +function buildKey (opts) { + const { path, method, body, headers, query } = opts + + return { + path, + method, + body, + headers, + query + } +} + +function generateKeyValues (data) { + const keys = Object.keys(data) + const result = [] + for (let i = 0; i < keys.length; ++i) { + const key = keys[i] + const value = data[key] + const name = Buffer.from(`${key}`) + if (Array.isArray(value)) { + for (let j = 0; j < value.length; ++j) { + result.push(name, Buffer.from(`${value[j]}`)) + } + } else { + result.push(name, Buffer.from(`${value}`)) + } + } + return result +} + +/** + * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status + * @param {number} statusCode + */ +function getStatusText (statusCode) { + return STATUS_CODES[statusCode] || 'unknown' +} + +async function getResponse (body) { + const buffers = [] + for await (const data of body) { + buffers.push(data) + } + return Buffer.concat(buffers).toString('utf8') +} + +/** + * Mock dispatch function used to simulate undici dispatches + */ +function mockDispatch (opts, handler) { + // Get mock dispatch from built key + const key = buildKey(opts) + const mockDispatch = getMockDispatch(this[kDispatches], key) + + mockDispatch.timesInvoked++ + + // Here's where we resolve a callback if a callback is present for the dispatch data. + if (mockDispatch.data.callback) { + mockDispatch.data = { ...mockDispatch.data, ...mockDispatch.data.callback(opts) } + } + + // Parse mockDispatch data + const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch + const { timesInvoked, times } = mockDispatch + + // If it's used up and not persistent, mark as consumed + mockDispatch.consumed = !persist && timesInvoked >= times + mockDispatch.pending = timesInvoked < times + + // If specified, trigger dispatch error + if (error !== null) { + deleteMockDispatch(this[kDispatches], key) + handler.onError(error) + return true + } + + // Handle the request with a delay if necessary + if (typeof delay === 'number' && delay > 0) { + setTimeout(() => { + handleReply(this[kDispatches]) + }, delay) + } else { + handleReply(this[kDispatches]) + } + + function handleReply (mockDispatches, _data = data) { + // fetch's HeadersList is a 1D string array + const optsHeaders = Array.isArray(opts.headers) + ? buildHeadersFromArray(opts.headers) + : opts.headers + const body = typeof _data === 'function' + ? _data({ ...opts, headers: optsHeaders }) + : _data + + // util.types.isPromise is likely needed for jest. + if (isPromise(body)) { + // If handleReply is asynchronous, throwing an error + // in the callback will reject the promise, rather than + // synchronously throw the error, which breaks some tests. + // Rather, we wait for the callback to resolve if it is a + // promise, and then re-run handleReply with the new body. + body.then((newData) => handleReply(mockDispatches, newData)) + return + } + + const responseData = getResponseData(body) + const responseHeaders = generateKeyValues(headers) + const responseTrailers = generateKeyValues(trailers) + + handler.onConnect?.(err => handler.onError(err), null) + handler.onHeaders?.(statusCode, responseHeaders, resume, getStatusText(statusCode)) + handler.onData?.(Buffer.from(responseData)) + handler.onComplete?.(responseTrailers) + deleteMockDispatch(mockDispatches, key) + } + + function resume () {} + + return true +} + +function buildMockDispatch () { + const agent = this[kMockAgent] + const origin = this[kOrigin] + const originalDispatch = this[kOriginalDispatch] + + return function dispatch (opts, handler) { + if (agent.isMockActive) { + try { + mockDispatch.call(this, opts, handler) + } catch (error) { + if (error instanceof MockNotMatchedError) { + const netConnect = agent[kGetNetConnect]() + if (netConnect === false) { + throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`) + } + if (checkNetConnect(netConnect, origin)) { + originalDispatch.call(this, opts, handler) + } else { + throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`) + } + } else { + throw error + } + } + } else { + originalDispatch.call(this, opts, handler) + } + } +} + +function checkNetConnect (netConnect, origin) { + const url = new URL(origin) + if (netConnect === true) { + return true + } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url.host))) { + return true + } + return false +} + +function buildAndValidateMockOptions (opts) { + if (opts) { + const { agent, ...mockOptions } = opts + + if ('enableCallHistory' in mockOptions && typeof mockOptions.enableCallHistory !== 'boolean') { + throw new InvalidArgumentError('options.enableCallHistory must to be a boolean') + } + + if ('acceptNonStandardSearchParameters' in mockOptions && typeof mockOptions.acceptNonStandardSearchParameters !== 'boolean') { + throw new InvalidArgumentError('options.acceptNonStandardSearchParameters must to be a boolean') + } + + return mockOptions + } +} + +module.exports = { + getResponseData, + getMockDispatch, + addMockDispatch, + deleteMockDispatch, + buildKey, + generateKeyValues, + matchValue, + getResponse, + getStatusText, + mockDispatch, + buildMockDispatch, + checkNetConnect, + buildAndValidateMockOptions, + getHeaderByName, + buildHeadersFromArray, + normalizeSearchParams +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/mock/pending-interceptors-formatter.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/mock/pending-interceptors-formatter.js new file mode 100644 index 0000000000000000000000000000000000000000..ccca951195aa6b37b8965943ef20e19ee9654302 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/mock/pending-interceptors-formatter.js @@ -0,0 +1,43 @@ +'use strict' + +const { Transform } = require('node:stream') +const { Console } = require('node:console') + +const PERSISTENT = process.versions.icu ? '✅' : 'Y ' +const NOT_PERSISTENT = process.versions.icu ? '❌' : 'N ' + +/** + * Gets the output of `console.table(…)` as a string. + */ +module.exports = class PendingInterceptorsFormatter { + constructor ({ disableColors } = {}) { + this.transform = new Transform({ + transform (chunk, _enc, cb) { + cb(null, chunk) + } + }) + + this.logger = new Console({ + stdout: this.transform, + inspectOptions: { + colors: !disableColors && !process.env.CI + } + }) + } + + format (pendingInterceptors) { + const withPrettyHeaders = pendingInterceptors.map( + ({ method, path, data: { statusCode }, persist, times, timesInvoked, origin }) => ({ + Method: method, + Origin: origin, + Path: path, + 'Status code': statusCode, + Persistent: persist ? PERSISTENT : NOT_PERSISTENT, + Invocations: timesInvoked, + Remaining: persist ? Infinity : times - timesInvoked + })) + + this.logger.table(withPrettyHeaders) + return this.transform.read().toString() + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/mock/snapshot-agent.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/mock/snapshot-agent.js new file mode 100644 index 0000000000000000000000000000000000000000..dbe53575f1d4e83dc793405d313dd4a7354e5d3f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/mock/snapshot-agent.js @@ -0,0 +1,347 @@ +'use strict' + +const Agent = require('../dispatcher/agent') +const MockAgent = require('./mock-agent') +const { SnapshotRecorder } = require('./snapshot-recorder') +const WrapHandler = require('../handler/wrap-handler') +const { InvalidArgumentError, UndiciError } = require('../core/errors') +const { validateSnapshotMode } = require('./snapshot-utils') + +const kSnapshotRecorder = Symbol('kSnapshotRecorder') +const kSnapshotMode = Symbol('kSnapshotMode') +const kSnapshotPath = Symbol('kSnapshotPath') +const kSnapshotLoaded = Symbol('kSnapshotLoaded') +const kRealAgent = Symbol('kRealAgent') + +// Static flag to ensure warning is only emitted once per process +let warningEmitted = false + +class SnapshotAgent extends MockAgent { + constructor (opts = {}) { + // Emit experimental warning only once + if (!warningEmitted) { + process.emitWarning( + 'SnapshotAgent is experimental and subject to change', + 'ExperimentalWarning' + ) + warningEmitted = true + } + + const { + mode = 'record', + snapshotPath = null, + ...mockAgentOpts + } = opts + + super(mockAgentOpts) + + validateSnapshotMode(mode) + + // Validate snapshotPath is provided when required + if ((mode === 'playback' || mode === 'update') && !snapshotPath) { + throw new InvalidArgumentError(`snapshotPath is required when mode is '${mode}'`) + } + + this[kSnapshotMode] = mode + this[kSnapshotPath] = snapshotPath + + this[kSnapshotRecorder] = new SnapshotRecorder({ + snapshotPath: this[kSnapshotPath], + mode: this[kSnapshotMode], + maxSnapshots: opts.maxSnapshots, + autoFlush: opts.autoFlush, + flushInterval: opts.flushInterval, + matchHeaders: opts.matchHeaders, + ignoreHeaders: opts.ignoreHeaders, + excludeHeaders: opts.excludeHeaders, + matchBody: opts.matchBody, + matchQuery: opts.matchQuery, + caseSensitive: opts.caseSensitive, + shouldRecord: opts.shouldRecord, + shouldPlayback: opts.shouldPlayback, + excludeUrls: opts.excludeUrls + }) + this[kSnapshotLoaded] = false + + // For recording/update mode, we need a real agent to make actual requests + if (this[kSnapshotMode] === 'record' || this[kSnapshotMode] === 'update') { + this[kRealAgent] = new Agent(opts) + } + + // Auto-load snapshots in playback/update mode + if ((this[kSnapshotMode] === 'playback' || this[kSnapshotMode] === 'update') && this[kSnapshotPath]) { + this.loadSnapshots().catch(() => { + // Ignore load errors - file might not exist yet + }) + } + } + + dispatch (opts, handler) { + handler = WrapHandler.wrap(handler) + const mode = this[kSnapshotMode] + + if (mode === 'playback' || mode === 'update') { + // Ensure snapshots are loaded + if (!this[kSnapshotLoaded]) { + // Need to load asynchronously, delegate to async version + return this.#asyncDispatch(opts, handler) + } + + // Try to find existing snapshot (synchronous) + const snapshot = this[kSnapshotRecorder].findSnapshot(opts) + + if (snapshot) { + // Use recorded response (synchronous) + return this.#replaySnapshot(snapshot, handler) + } else if (mode === 'update') { + // Make real request and record it (async required) + return this.#recordAndReplay(opts, handler) + } else { + // Playback mode but no snapshot found + const error = new UndiciError(`No snapshot found for ${opts.method || 'GET'} ${opts.path}`) + if (handler.onError) { + handler.onError(error) + return + } + throw error + } + } else if (mode === 'record') { + // Record mode - make real request and save response (async required) + return this.#recordAndReplay(opts, handler) + } + } + + /** + * Async version of dispatch for when we need to load snapshots first + */ + async #asyncDispatch (opts, handler) { + await this.loadSnapshots() + return this.dispatch(opts, handler) + } + + /** + * Records a real request and replays the response + */ + #recordAndReplay (opts, handler) { + const responseData = { + statusCode: null, + headers: {}, + trailers: {}, + body: [] + } + + const self = this // Capture 'this' context for use within nested handler callbacks + + const recordingHandler = { + onRequestStart (controller, context) { + return handler.onRequestStart(controller, { ...context, history: this.history }) + }, + + onRequestUpgrade (controller, statusCode, headers, socket) { + return handler.onRequestUpgrade(controller, statusCode, headers, socket) + }, + + onResponseStart (controller, statusCode, headers, statusMessage) { + responseData.statusCode = statusCode + responseData.headers = headers + return handler.onResponseStart(controller, statusCode, headers, statusMessage) + }, + + onResponseData (controller, chunk) { + responseData.body.push(chunk) + return handler.onResponseData(controller, chunk) + }, + + onResponseEnd (controller, trailers) { + responseData.trailers = trailers + + // Record the interaction using captured 'self' context (fire and forget) + const responseBody = Buffer.concat(responseData.body) + self[kSnapshotRecorder].record(opts, { + statusCode: responseData.statusCode, + headers: responseData.headers, + body: responseBody, + trailers: responseData.trailers + }).then(() => { + handler.onResponseEnd(controller, trailers) + }).catch((error) => { + handler.onResponseError(controller, error) + }) + } + } + + // Use composed agent if available (includes interceptors), otherwise use real agent + const agent = this[kRealAgent] + return agent.dispatch(opts, recordingHandler) + } + + /** + * Replays a recorded response + * + * @param {Object} snapshot - The recorded snapshot to replay. + * @param {Object} handler - The handler to call with the response data. + * @returns {void} + */ + #replaySnapshot (snapshot, handler) { + try { + const { response } = snapshot + + const controller = { + pause () { }, + resume () { }, + abort (reason) { + this.aborted = true + this.reason = reason + }, + + aborted: false, + paused: false + } + + handler.onRequestStart(controller) + + handler.onResponseStart(controller, response.statusCode, response.headers) + + // Body is always stored as base64 string + const body = Buffer.from(response.body, 'base64') + handler.onResponseData(controller, body) + + handler.onResponseEnd(controller, response.trailers) + } catch (error) { + handler.onError?.(error) + } + } + + /** + * Loads snapshots from file + * + * @param {string} [filePath] - Optional file path to load snapshots from. + * @returns {Promise} - Resolves when snapshots are loaded. + */ + async loadSnapshots (filePath) { + await this[kSnapshotRecorder].loadSnapshots(filePath || this[kSnapshotPath]) + this[kSnapshotLoaded] = true + + // In playback mode, set up MockAgent interceptors for all snapshots + if (this[kSnapshotMode] === 'playback') { + this.#setupMockInterceptors() + } + } + + /** + * Saves snapshots to file + * + * @param {string} [filePath] - Optional file path to save snapshots to. + * @returns {Promise} - Resolves when snapshots are saved. + */ + async saveSnapshots (filePath) { + return this[kSnapshotRecorder].saveSnapshots(filePath || this[kSnapshotPath]) + } + + /** + * Sets up MockAgent interceptors based on recorded snapshots. + * + * This method creates MockAgent interceptors for each recorded snapshot, + * allowing the SnapshotAgent to fall back to MockAgent's standard intercept + * mechanism in playback mode. Each interceptor is configured to persist + * (remain active for multiple requests) and responds with the recorded + * response data. + * + * Called automatically when loading snapshots in playback mode. + * + * @returns {void} + */ + #setupMockInterceptors () { + for (const snapshot of this[kSnapshotRecorder].getSnapshots()) { + const { request, responses, response } = snapshot + const url = new URL(request.url) + + const mockPool = this.get(url.origin) + + // Handle both new format (responses array) and legacy format (response object) + const responseData = responses ? responses[0] : response + if (!responseData) continue + + mockPool.intercept({ + path: url.pathname + url.search, + method: request.method, + headers: request.headers, + body: request.body + }).reply(responseData.statusCode, responseData.body, { + headers: responseData.headers, + trailers: responseData.trailers + }).persist() + } + } + + /** + * Gets the snapshot recorder + * @return {SnapshotRecorder} - The snapshot recorder instance + */ + getRecorder () { + return this[kSnapshotRecorder] + } + + /** + * Gets the current mode + * @return {import('./snapshot-utils').SnapshotMode} - The current snapshot mode + */ + getMode () { + return this[kSnapshotMode] + } + + /** + * Clears all snapshots + * @returns {void} + */ + clearSnapshots () { + this[kSnapshotRecorder].clear() + } + + /** + * Resets call counts for all snapshots (useful for test cleanup) + * @returns {void} + */ + resetCallCounts () { + this[kSnapshotRecorder].resetCallCounts() + } + + /** + * Deletes a specific snapshot by request options + * @param {import('./snapshot-recorder').SnapshotRequestOptions} requestOpts - Request options to identify the snapshot + * @return {Promise} - Returns true if the snapshot was deleted, false if not found + */ + deleteSnapshot (requestOpts) { + return this[kSnapshotRecorder].deleteSnapshot(requestOpts) + } + + /** + * Gets information about a specific snapshot + * @returns {import('./snapshot-recorder').SnapshotInfo|null} - Snapshot information or null if not found + */ + getSnapshotInfo (requestOpts) { + return this[kSnapshotRecorder].getSnapshotInfo(requestOpts) + } + + /** + * Replaces all snapshots with new data (full replacement) + * @param {Array<{hash: string; snapshot: import('./snapshot-recorder').SnapshotEntryshotEntry}>|Record} snapshotData - New snapshot data to replace existing snapshots + * @returns {void} + */ + replaceSnapshots (snapshotData) { + this[kSnapshotRecorder].replaceSnapshots(snapshotData) + } + + /** + * Closes the agent, saving snapshots and cleaning up resources. + * + * @returns {Promise} + */ + async close () { + await this[kSnapshotRecorder].close() + await this[kRealAgent]?.close() + await super.close() + } +} + +module.exports = SnapshotAgent diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/mock/snapshot-recorder.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/mock/snapshot-recorder.js new file mode 100644 index 0000000000000000000000000000000000000000..e810fe795072a7b193f6fa1d165a6af9bdd85028 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/mock/snapshot-recorder.js @@ -0,0 +1,580 @@ +'use strict' + +const { writeFile, readFile, mkdir } = require('node:fs/promises') +const { dirname, resolve } = require('node:path') +const { setTimeout, clearTimeout } = require('node:timers') +const { InvalidArgumentError, UndiciError } = require('../core/errors') +const { hashId, isUrlExcludedFactory, normalizeHeaders, createHeaderFilters } = require('./snapshot-utils') + +/** + * @typedef {Object} SnapshotRequestOptions + * @property {string} method - HTTP method (e.g. 'GET', 'POST', etc.) + * @property {string} path - Request path + * @property {string} origin - Request origin (base URL) + * @property {import('./snapshot-utils').Headers|import('./snapshot-utils').UndiciHeaders} headers - Request headers + * @property {import('./snapshot-utils').NormalizedHeaders} _normalizedHeaders - Request headers as a lowercase object + * @property {string|Buffer} [body] - Request body (optional) + */ + +/** + * @typedef {Object} SnapshotEntryRequest + * @property {string} method - HTTP method (e.g. 'GET', 'POST', etc.) + * @property {string} url - Full URL of the request + * @property {import('./snapshot-utils').NormalizedHeaders} headers - Normalized headers as a lowercase object + * @property {string|Buffer} [body] - Request body (optional) + */ + +/** + * @typedef {Object} SnapshotEntryResponse + * @property {number} statusCode - HTTP status code of the response + * @property {import('./snapshot-utils').NormalizedHeaders} headers - Normalized response headers as a lowercase object + * @property {string} body - Response body as a base64url encoded string + * @property {Object} [trailers] - Optional response trailers + */ + +/** + * @typedef {Object} SnapshotEntry + * @property {SnapshotEntryRequest} request - The request object + * @property {Array} responses - Array of response objects + * @property {number} callCount - Number of times this snapshot has been called + * @property {string} timestamp - ISO timestamp of when the snapshot was created + */ + +/** + * @typedef {Object} SnapshotRecorderMatchOptions + * @property {Array} [matchHeaders=[]] - Headers to match (empty array means match all headers) + * @property {Array} [ignoreHeaders=[]] - Headers to ignore for matching + * @property {Array} [excludeHeaders=[]] - Headers to exclude from matching + * @property {boolean} [matchBody=true] - Whether to match request body + * @property {boolean} [matchQuery=true] - Whether to match query properties + * @property {boolean} [caseSensitive=false] - Whether header matching is case-sensitive + */ + +/** + * @typedef {Object} SnapshotRecorderOptions + * @property {string} [snapshotPath] - Path to save/load snapshots + * @property {import('./snapshot-utils').SnapshotMode} [mode='record'] - Mode: 'record' or 'playback' + * @property {number} [maxSnapshots=Infinity] - Maximum number of snapshots to keep + * @property {boolean} [autoFlush=false] - Whether to automatically flush snapshots to disk + * @property {number} [flushInterval=30000] - Auto-flush interval in milliseconds (default: 30 seconds) + * @property {Array} [excludeUrls=[]] - URLs to exclude from recording + * @property {function} [shouldRecord=null] - Function to filter requests for recording + * @property {function} [shouldPlayback=null] - Function to filter requests + */ + +/** + * @typedef {Object} SnapshotFormattedRequest + * @property {string} method - HTTP method (e.g. 'GET', 'POST', etc.) + * @property {string} url - Full URL of the request (with query parameters if matchQuery is true) + * @property {import('./snapshot-utils').NormalizedHeaders} headers - Normalized headers as a lowercase object + * @property {string} body - Request body (optional, only if matchBody is true) + */ + +/** + * @typedef {Object} SnapshotInfo + * @property {string} hash - Hash key for the snapshot + * @property {SnapshotEntryRequest} request - The request object + * @property {number} responseCount - Number of responses recorded for this request + * @property {number} callCount - Number of times this snapshot has been called + * @property {string} timestamp - ISO timestamp of when the snapshot was created + */ + +/** + * Formats a request for consistent snapshot storage + * Caches normalized headers to avoid repeated processing + * + * @param {SnapshotRequestOptions} opts - Request options + * @param {import('./snapshot-utils').HeaderFilters} headerFilters - Cached header sets for performance + * @param {SnapshotRecorderMatchOptions} [matchOptions] - Matching options for headers and body + * @returns {SnapshotFormattedRequest} - Formatted request object + */ +function formatRequestKey (opts, headerFilters, matchOptions = {}) { + const url = new URL(opts.path, opts.origin) + + // Cache normalized headers if not already done + const normalized = opts._normalizedHeaders || normalizeHeaders(opts.headers) + if (!opts._normalizedHeaders) { + opts._normalizedHeaders = normalized + } + + return { + method: opts.method || 'GET', + url: matchOptions.matchQuery !== false ? url.toString() : `${url.origin}${url.pathname}`, + headers: filterHeadersForMatching(normalized, headerFilters, matchOptions), + body: matchOptions.matchBody !== false && opts.body ? String(opts.body) : '' + } +} + +/** + * Filters headers based on matching configuration + * + * @param {import('./snapshot-utils').Headers} headers - Headers to filter + * @param {import('./snapshot-utils').HeaderFilters} headerFilters - Cached sets for ignore, exclude, and match headers + * @param {SnapshotRecorderMatchOptions} [matchOptions] - Matching options for headers + */ +function filterHeadersForMatching (headers, headerFilters, matchOptions = {}) { + if (!headers || typeof headers !== 'object') return {} + + const { + caseSensitive = false + } = matchOptions + + const filtered = {} + const { ignore, exclude, match } = headerFilters + + for (const [key, value] of Object.entries(headers)) { + const headerKey = caseSensitive ? key : key.toLowerCase() + + // Skip if in exclude list (for security) + if (exclude.has(headerKey)) continue + + // Skip if in ignore list (for matching) + if (ignore.has(headerKey)) continue + + // If matchHeaders is specified, only include those headers + if (match.size !== 0) { + if (!match.has(headerKey)) continue + } + + filtered[headerKey] = value + } + + return filtered +} + +/** + * Filters headers for storage (only excludes sensitive headers) + * + * @param {import('./snapshot-utils').Headers} headers - Headers to filter + * @param {import('./snapshot-utils').HeaderFilters} headerFilters - Cached sets for ignore, exclude, and match headers + * @param {SnapshotRecorderMatchOptions} [matchOptions] - Matching options for headers + */ +function filterHeadersForStorage (headers, headerFilters, matchOptions = {}) { + if (!headers || typeof headers !== 'object') return {} + + const { + caseSensitive = false + } = matchOptions + + const filtered = {} + const { exclude: excludeSet } = headerFilters + + for (const [key, value] of Object.entries(headers)) { + const headerKey = caseSensitive ? key : key.toLowerCase() + + // Skip if in exclude list (for security) + if (excludeSet.has(headerKey)) continue + + filtered[headerKey] = value + } + + return filtered +} + +/** + * Creates a hash key for request matching + * Properly orders headers to avoid conflicts and uses crypto hashing when available + * + * @param {SnapshotFormattedRequest} formattedRequest - Request object + * @returns {string} - Base64url encoded hash of the request + */ +function createRequestHash (formattedRequest) { + const parts = [ + formattedRequest.method, + formattedRequest.url + ] + + // Process headers in a deterministic way to avoid conflicts + if (formattedRequest.headers && typeof formattedRequest.headers === 'object') { + const headerKeys = Object.keys(formattedRequest.headers).sort() + for (const key of headerKeys) { + const values = Array.isArray(formattedRequest.headers[key]) + ? formattedRequest.headers[key] + : [formattedRequest.headers[key]] + + // Add header name + parts.push(key) + + // Add all values for this header, sorted for consistency + for (const value of values.sort()) { + parts.push(String(value)) + } + } + } + + // Add body + parts.push(formattedRequest.body) + + const content = parts.join('|') + + return hashId(content) +} + +class SnapshotRecorder { + /** @type {NodeJS.Timeout | null} */ + #flushTimeout + + /** @type {import('./snapshot-utils').IsUrlExcluded} */ + #isUrlExcluded + + /** @type {Map} */ + #snapshots = new Map() + + /** @type {string|undefined} */ + #snapshotPath + + /** @type {number} */ + #maxSnapshots = Infinity + + /** @type {boolean} */ + #autoFlush = false + + /** @type {import('./snapshot-utils').HeaderFilters} */ + #headerFilters + + /** + * Creates a new SnapshotRecorder instance + * @param {SnapshotRecorderOptions&SnapshotRecorderMatchOptions} [options={}] - Configuration options for the recorder + */ + constructor (options = {}) { + this.#snapshotPath = options.snapshotPath + this.#maxSnapshots = options.maxSnapshots || Infinity + this.#autoFlush = options.autoFlush || false + this.flushInterval = options.flushInterval || 30000 // 30 seconds default + this._flushTimer = null + + // Matching configuration + /** @type {Required} */ + this.matchOptions = { + matchHeaders: options.matchHeaders || [], // empty means match all headers + ignoreHeaders: options.ignoreHeaders || [], + excludeHeaders: options.excludeHeaders || [], + matchBody: options.matchBody !== false, // default: true + matchQuery: options.matchQuery !== false, // default: true + caseSensitive: options.caseSensitive || false + } + + // Cache processed header sets to avoid recreating them on every request + this.#headerFilters = createHeaderFilters(this.matchOptions) + + // Request filtering callbacks + this.shouldRecord = options.shouldRecord || (() => true) // function(requestOpts) -> boolean + this.shouldPlayback = options.shouldPlayback || (() => true) // function(requestOpts) -> boolean + + // URL pattern filtering + this.#isUrlExcluded = isUrlExcludedFactory(options.excludeUrls) // Array of regex patterns or strings + + // Start auto-flush timer if enabled + if (this.#autoFlush && this.#snapshotPath) { + this.#startAutoFlush() + } + } + + /** + * Records a request-response interaction + * @param {SnapshotRequestOptions} requestOpts - Request options + * @param {SnapshotEntryResponse} response - Response data to record + * @return {Promise} - Resolves when the recording is complete + */ + async record (requestOpts, response) { + // Check if recording should be filtered out + if (!this.shouldRecord(requestOpts)) { + return // Skip recording + } + + // Check URL exclusion patterns + const url = new URL(requestOpts.path, requestOpts.origin).toString() + if (this.#isUrlExcluded(url)) { + return // Skip recording + } + + const request = formatRequestKey(requestOpts, this.#headerFilters, this.matchOptions) + const hash = createRequestHash(request) + + // Extract response data - always store body as base64 + const normalizedHeaders = normalizeHeaders(response.headers) + + /** @type {SnapshotEntryResponse} */ + const responseData = { + statusCode: response.statusCode, + headers: filterHeadersForStorage(normalizedHeaders, this.#headerFilters, this.matchOptions), + body: Buffer.isBuffer(response.body) + ? response.body.toString('base64') + : Buffer.from(String(response.body || '')).toString('base64'), + trailers: response.trailers + } + + // Remove oldest snapshot if we exceed maxSnapshots limit + if (this.#snapshots.size >= this.#maxSnapshots && !this.#snapshots.has(hash)) { + const oldestKey = this.#snapshots.keys().next().value + this.#snapshots.delete(oldestKey) + } + + // Support sequential responses - if snapshot exists, add to responses array + const existingSnapshot = this.#snapshots.get(hash) + if (existingSnapshot && existingSnapshot.responses) { + existingSnapshot.responses.push(responseData) + existingSnapshot.timestamp = new Date().toISOString() + } else { + this.#snapshots.set(hash, { + request, + responses: [responseData], // Always store as array for consistency + callCount: 0, + timestamp: new Date().toISOString() + }) + } + + // Auto-flush if enabled + if (this.#autoFlush && this.#snapshotPath) { + this.#scheduleFlush() + } + } + + /** + * Finds a matching snapshot for the given request + * Returns the appropriate response based on call count for sequential responses + * + * @param {SnapshotRequestOptions} requestOpts - Request options to match + * @returns {SnapshotEntry&Record<'response', SnapshotEntryResponse>|undefined} - Matching snapshot response or undefined if not found + */ + findSnapshot (requestOpts) { + // Check if playback should be filtered out + if (!this.shouldPlayback(requestOpts)) { + return undefined // Skip playback + } + + // Check URL exclusion patterns + const url = new URL(requestOpts.path, requestOpts.origin).toString() + if (this.#isUrlExcluded(url)) { + return undefined // Skip playback + } + + const request = formatRequestKey(requestOpts, this.#headerFilters, this.matchOptions) + const hash = createRequestHash(request) + const snapshot = this.#snapshots.get(hash) + + if (!snapshot) return undefined + + // Handle sequential responses + const currentCallCount = snapshot.callCount || 0 + const responseIndex = Math.min(currentCallCount, snapshot.responses.length - 1) + snapshot.callCount = currentCallCount + 1 + + return { + ...snapshot, + response: snapshot.responses[responseIndex] + } + } + + /** + * Loads snapshots from file + * @param {string} [filePath] - Optional file path to load snapshots from + * @return {Promise} - Resolves when snapshots are loaded + */ + async loadSnapshots (filePath) { + const path = filePath || this.#snapshotPath + if (!path) { + throw new InvalidArgumentError('Snapshot path is required') + } + + try { + const data = await readFile(resolve(path), 'utf8') + const parsed = JSON.parse(data) + + // Convert array format back to Map + if (Array.isArray(parsed)) { + this.#snapshots.clear() + for (const { hash, snapshot } of parsed) { + this.#snapshots.set(hash, snapshot) + } + } else { + // Legacy object format + this.#snapshots = new Map(Object.entries(parsed)) + } + } catch (error) { + if (error.code === 'ENOENT') { + // File doesn't exist yet - that's ok for recording mode + this.#snapshots.clear() + } else { + throw new UndiciError(`Failed to load snapshots from ${path}`, { cause: error }) + } + } + } + + /** + * Saves snapshots to file + * + * @param {string} [filePath] - Optional file path to save snapshots + * @returns {Promise} - Resolves when snapshots are saved + */ + async saveSnapshots (filePath) { + const path = filePath || this.#snapshotPath + if (!path) { + throw new InvalidArgumentError('Snapshot path is required') + } + + const resolvedPath = resolve(path) + + // Ensure directory exists + await mkdir(dirname(resolvedPath), { recursive: true }) + + // Convert Map to serializable format + const data = Array.from(this.#snapshots.entries()).map(([hash, snapshot]) => ({ + hash, + snapshot + })) + + await writeFile(resolvedPath, JSON.stringify(data, null, 2), { flush: true }) + } + + /** + * Clears all recorded snapshots + * @returns {void} + */ + clear () { + this.#snapshots.clear() + } + + /** + * Gets all recorded snapshots + * @return {Array} - Array of all recorded snapshots + */ + getSnapshots () { + return Array.from(this.#snapshots.values()) + } + + /** + * Gets snapshot count + * @return {number} - Number of recorded snapshots + */ + size () { + return this.#snapshots.size + } + + /** + * Resets call counts for all snapshots (useful for test cleanup) + * @returns {void} + */ + resetCallCounts () { + for (const snapshot of this.#snapshots.values()) { + snapshot.callCount = 0 + } + } + + /** + * Deletes a specific snapshot by request options + * @param {SnapshotRequestOptions} requestOpts - Request options to match + * @returns {boolean} - True if snapshot was deleted, false if not found + */ + deleteSnapshot (requestOpts) { + const request = formatRequestKey(requestOpts, this.#headerFilters, this.matchOptions) + const hash = createRequestHash(request) + return this.#snapshots.delete(hash) + } + + /** + * Gets information about a specific snapshot + * @param {SnapshotRequestOptions} requestOpts - Request options to match + * @returns {SnapshotInfo|null} - Snapshot information or null if not found + */ + getSnapshotInfo (requestOpts) { + const request = formatRequestKey(requestOpts, this.#headerFilters, this.matchOptions) + const hash = createRequestHash(request) + const snapshot = this.#snapshots.get(hash) + + if (!snapshot) return null + + return { + hash, + request: snapshot.request, + responseCount: snapshot.responses ? snapshot.responses.length : (snapshot.response ? 1 : 0), // .response for legacy snapshots + callCount: snapshot.callCount || 0, + timestamp: snapshot.timestamp + } + } + + /** + * Replaces all snapshots with new data (full replacement) + * @param {Array<{hash: string; snapshot: SnapshotEntry}>|Record} snapshotData - New snapshot data to replace existing ones + * @returns {void} + */ + replaceSnapshots (snapshotData) { + this.#snapshots.clear() + + if (Array.isArray(snapshotData)) { + for (const { hash, snapshot } of snapshotData) { + this.#snapshots.set(hash, snapshot) + } + } else if (snapshotData && typeof snapshotData === 'object') { + // Legacy object format + this.#snapshots = new Map(Object.entries(snapshotData)) + } + } + + /** + * Starts the auto-flush timer + * @returns {void} + */ + #startAutoFlush () { + return this.#scheduleFlush() + } + + /** + * Stops the auto-flush timer + * @returns {void} + */ + #stopAutoFlush () { + if (this.#flushTimeout) { + clearTimeout(this.#flushTimeout) + // Ensure any pending flush is completed + this.saveSnapshots().catch(() => { + // Ignore flush errors + }) + this.#flushTimeout = null + } + } + + /** + * Schedules a flush (debounced to avoid excessive writes) + */ + #scheduleFlush () { + this.#flushTimeout = setTimeout(() => { + this.saveSnapshots().catch(() => { + // Ignore flush errors + }) + if (this.#autoFlush) { + this.#flushTimeout?.refresh() + } else { + this.#flushTimeout = null + } + }, 1000) // 1 second debounce + } + + /** + * Cleanup method to stop timers + * @returns {void} + */ + destroy () { + this.#stopAutoFlush() + if (this.#flushTimeout) { + clearTimeout(this.#flushTimeout) + this.#flushTimeout = null + } + } + + /** + * Async close method that saves all recordings and performs cleanup + * @returns {Promise} + */ + async close () { + // Save any pending recordings if we have a snapshot path + if (this.#snapshotPath && this.#snapshots.size !== 0) { + await this.saveSnapshots() + } + + // Perform cleanup + this.destroy() + } +} + +module.exports = { SnapshotRecorder, formatRequestKey, createRequestHash, filterHeadersForMatching, filterHeadersForStorage, createHeaderFilters } diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/mock/snapshot-utils.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/mock/snapshot-utils.js new file mode 100644 index 0000000000000000000000000000000000000000..ebad12e888ff2995df38c726517755c1e8840455 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/mock/snapshot-utils.js @@ -0,0 +1,158 @@ +'use strict' + +const { InvalidArgumentError } = require('../core/errors') + +/** + * @typedef {Object} HeaderFilters + * @property {Set} ignore - Set of headers to ignore for matching + * @property {Set} exclude - Set of headers to exclude from matching + * @property {Set} match - Set of headers to match (empty means match + */ + +/** + * Creates cached header sets for performance + * + * @param {import('./snapshot-recorder').SnapshotRecorderMatchOptions} matchOptions - Matching options for headers + * @returns {HeaderFilters} - Cached sets for ignore, exclude, and match headers + */ +function createHeaderFilters (matchOptions = {}) { + const { ignoreHeaders = [], excludeHeaders = [], matchHeaders = [], caseSensitive = false } = matchOptions + + return { + ignore: new Set(ignoreHeaders.map(header => caseSensitive ? header : header.toLowerCase())), + exclude: new Set(excludeHeaders.map(header => caseSensitive ? header : header.toLowerCase())), + match: new Set(matchHeaders.map(header => caseSensitive ? header : header.toLowerCase())) + } +} + +let crypto +try { + crypto = require('node:crypto') +} catch { /* Fallback if crypto is not available */ } + +/** + * @callback HashIdFunction + * @param {string} value - The value to hash + * @returns {string} - The base64url encoded hash of the value + */ + +/** + * Generates a hash for a given value + * @type {HashIdFunction} + */ +const hashId = crypto?.hash + ? (value) => crypto.hash('sha256', value, 'base64url') + : (value) => Buffer.from(value).toString('base64url') + +/** + * @typedef {(url: string) => boolean} IsUrlExcluded Checks if a URL matches any of the exclude patterns + */ + +/** @typedef {{[key: Lowercase]: string}} NormalizedHeaders */ +/** @typedef {Array} UndiciHeaders */ +/** @typedef {Record} Headers */ + +/** + * @param {*} headers + * @returns {headers is UndiciHeaders} + */ +function isUndiciHeaders (headers) { + return Array.isArray(headers) && (headers.length & 1) === 0 +} + +/** + * Factory function to create a URL exclusion checker + * @param {Array} [excludePatterns=[]] - Array of patterns to exclude + * @returns {IsUrlExcluded} - A function that checks if a URL matches any of the exclude patterns + */ +function isUrlExcludedFactory (excludePatterns = []) { + if (excludePatterns.length === 0) { + return () => false + } + + return function isUrlExcluded (url) { + let urlLowerCased + + for (const pattern of excludePatterns) { + if (typeof pattern === 'string') { + if (!urlLowerCased) { + // Convert URL to lowercase only once + urlLowerCased = url.toLowerCase() + } + // Simple string match (case-insensitive) + if (urlLowerCased.includes(pattern.toLowerCase())) { + return true + } + } else if (pattern instanceof RegExp) { + // Regex pattern match + if (pattern.test(url)) { + return true + } + } + } + + return false + } +} + +/** + * Normalizes headers for consistent comparison + * + * @param {Object|UndiciHeaders} headers - Headers to normalize + * @returns {NormalizedHeaders} - Normalized headers as a lowercase object + */ +function normalizeHeaders (headers) { + /** @type {NormalizedHeaders} */ + const normalizedHeaders = {} + + if (!headers) return normalizedHeaders + + // Handle array format (undici internal format: [name, value, name, value, ...]) + if (isUndiciHeaders(headers)) { + for (let i = 0; i < headers.length; i += 2) { + const key = headers[i] + const value = headers[i + 1] + if (key && value !== undefined) { + // Convert Buffers to strings if needed + const keyStr = Buffer.isBuffer(key) ? key.toString() : key + const valueStr = Buffer.isBuffer(value) ? value.toString() : value + normalizedHeaders[keyStr.toLowerCase()] = valueStr + } + } + return normalizedHeaders + } + + // Handle object format + if (headers && typeof headers === 'object') { + for (const [key, value] of Object.entries(headers)) { + if (key && typeof key === 'string') { + normalizedHeaders[key.toLowerCase()] = Array.isArray(value) ? value.join(', ') : String(value) + } + } + } + + return normalizedHeaders +} + +const validSnapshotModes = /** @type {const} */ (['record', 'playback', 'update']) + +/** @typedef {typeof validSnapshotModes[number]} SnapshotMode */ + +/** + * @param {*} mode - The snapshot mode to validate + * @returns {asserts mode is SnapshotMode} + */ +function validateSnapshotMode (mode) { + if (!validSnapshotModes.includes(mode)) { + throw new InvalidArgumentError(`Invalid snapshot mode: ${mode}. Must be one of: ${validSnapshotModes.join(', ')}`) + } +} + +module.exports = { + createHeaderFilters, + hashId, + isUndiciHeaders, + normalizeHeaders, + isUrlExcludedFactory, + validateSnapshotMode +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/util/cache.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/util/cache.js new file mode 100644 index 0000000000000000000000000000000000000000..a05530f783b76d0a616394c679c40c0790285429 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/util/cache.js @@ -0,0 +1,377 @@ +'use strict' + +const { + safeHTTPMethods, + pathHasQueryOrFragment +} = require('../core/util') + +const { serializePathWithQuery } = require('../core/util') + +/** + * @param {import('../../types/dispatcher.d.ts').default.DispatchOptions} opts + */ +function makeCacheKey (opts) { + if (!opts.origin) { + throw new Error('opts.origin is undefined') + } + + let fullPath = opts.path || '/' + + if (opts.query && !pathHasQueryOrFragment(opts.path)) { + fullPath = serializePathWithQuery(fullPath, opts.query) + } + + return { + origin: opts.origin.toString(), + method: opts.method, + path: fullPath, + headers: opts.headers + } +} + +/** + * @param {Record} + * @returns {Record} + */ +function normalizeHeaders (opts) { + let headers + if (opts.headers == null) { + headers = {} + } else if (typeof opts.headers[Symbol.iterator] === 'function') { + headers = {} + for (const x of opts.headers) { + if (!Array.isArray(x)) { + throw new Error('opts.headers is not a valid header map') + } + const [key, val] = x + if (typeof key !== 'string' || typeof val !== 'string') { + throw new Error('opts.headers is not a valid header map') + } + headers[key.toLowerCase()] = val + } + } else if (typeof opts.headers === 'object') { + headers = {} + + for (const key of Object.keys(opts.headers)) { + headers[key.toLowerCase()] = opts.headers[key] + } + } else { + throw new Error('opts.headers is not an object') + } + + return headers +} + +/** + * @param {any} key + */ +function assertCacheKey (key) { + if (typeof key !== 'object') { + throw new TypeError(`expected key to be object, got ${typeof key}`) + } + + for (const property of ['origin', 'method', 'path']) { + if (typeof key[property] !== 'string') { + throw new TypeError(`expected key.${property} to be string, got ${typeof key[property]}`) + } + } + + if (key.headers !== undefined && typeof key.headers !== 'object') { + throw new TypeError(`expected headers to be object, got ${typeof key}`) + } +} + +/** + * @param {any} value + */ +function assertCacheValue (value) { + if (typeof value !== 'object') { + throw new TypeError(`expected value to be object, got ${typeof value}`) + } + + for (const property of ['statusCode', 'cachedAt', 'staleAt', 'deleteAt']) { + if (typeof value[property] !== 'number') { + throw new TypeError(`expected value.${property} to be number, got ${typeof value[property]}`) + } + } + + if (typeof value.statusMessage !== 'string') { + throw new TypeError(`expected value.statusMessage to be string, got ${typeof value.statusMessage}`) + } + + if (value.headers != null && typeof value.headers !== 'object') { + throw new TypeError(`expected value.rawHeaders to be object, got ${typeof value.headers}`) + } + + if (value.vary !== undefined && typeof value.vary !== 'object') { + throw new TypeError(`expected value.vary to be object, got ${typeof value.vary}`) + } + + if (value.etag !== undefined && typeof value.etag !== 'string') { + throw new TypeError(`expected value.etag to be string, got ${typeof value.etag}`) + } +} + +/** + * @see https://www.rfc-editor.org/rfc/rfc9111.html#name-cache-control + * @see https://www.iana.org/assignments/http-cache-directives/http-cache-directives.xhtml + + * @param {string | string[]} header + * @returns {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives} + */ +function parseCacheControlHeader (header) { + /** + * @type {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives} + */ + const output = {} + + let directives + if (Array.isArray(header)) { + directives = [] + + for (const directive of header) { + directives.push(...directive.split(',')) + } + } else { + directives = header.split(',') + } + + for (let i = 0; i < directives.length; i++) { + const directive = directives[i].toLowerCase() + const keyValueDelimiter = directive.indexOf('=') + + let key + let value + if (keyValueDelimiter !== -1) { + key = directive.substring(0, keyValueDelimiter).trimStart() + value = directive.substring(keyValueDelimiter + 1) + } else { + key = directive.trim() + } + + switch (key) { + case 'min-fresh': + case 'max-stale': + case 'max-age': + case 's-maxage': + case 'stale-while-revalidate': + case 'stale-if-error': { + if (value === undefined || value[0] === ' ') { + continue + } + + if ( + value.length >= 2 && + value[0] === '"' && + value[value.length - 1] === '"' + ) { + value = value.substring(1, value.length - 1) + } + + const parsedValue = parseInt(value, 10) + // eslint-disable-next-line no-self-compare + if (parsedValue !== parsedValue) { + continue + } + + if (key === 'max-age' && key in output && output[key] >= parsedValue) { + continue + } + + output[key] = parsedValue + + break + } + case 'private': + case 'no-cache': { + if (value) { + // The private and no-cache directives can be unqualified (aka just + // `private` or `no-cache`) or qualified (w/ a value). When they're + // qualified, it's a list of headers like `no-cache=header1`, + // `no-cache="header1"`, or `no-cache="header1, header2"` + // If we're given multiple headers, the comma messes us up since + // we split the full header by commas. So, let's loop through the + // remaining parts in front of us until we find one that ends in a + // quote. We can then just splice all of the parts in between the + // starting quote and the ending quote out of the directives array + // and continue parsing like normal. + // https://www.rfc-editor.org/rfc/rfc9111.html#name-no-cache-2 + if (value[0] === '"') { + // Something like `no-cache="some-header"` OR `no-cache="some-header, another-header"`. + + // Add the first header on and cut off the leading quote + const headers = [value.substring(1)] + + let foundEndingQuote = value[value.length - 1] === '"' + if (!foundEndingQuote) { + // Something like `no-cache="some-header, another-header"` + // This can still be something invalid, e.g. `no-cache="some-header, ...` + for (let j = i + 1; j < directives.length; j++) { + const nextPart = directives[j] + const nextPartLength = nextPart.length + + headers.push(nextPart.trim()) + + if (nextPartLength !== 0 && nextPart[nextPartLength - 1] === '"') { + foundEndingQuote = true + break + } + } + } + + if (foundEndingQuote) { + let lastHeader = headers[headers.length - 1] + if (lastHeader[lastHeader.length - 1] === '"') { + lastHeader = lastHeader.substring(0, lastHeader.length - 1) + headers[headers.length - 1] = lastHeader + } + + if (key in output) { + output[key] = output[key].concat(headers) + } else { + output[key] = headers + } + } + } else { + // Something like `no-cache="some-header"` + if (key in output) { + output[key] = output[key].concat(value) + } else { + output[key] = [value] + } + } + + break + } + } + // eslint-disable-next-line no-fallthrough + case 'public': + case 'no-store': + case 'must-revalidate': + case 'proxy-revalidate': + case 'immutable': + case 'no-transform': + case 'must-understand': + case 'only-if-cached': + if (value) { + // These are qualified (something like `public=...`) when they aren't + // allowed to be, skip + continue + } + + output[key] = true + break + default: + // Ignore unknown directives as per https://www.rfc-editor.org/rfc/rfc9111.html#section-5.2.3-1 + continue + } + } + + return output +} + +/** + * @param {string | string[]} varyHeader Vary header from the server + * @param {Record} headers Request headers + * @returns {Record} + */ +function parseVaryHeader (varyHeader, headers) { + if (typeof varyHeader === 'string' && varyHeader.includes('*')) { + return headers + } + + const output = /** @type {Record} */ ({}) + + const varyingHeaders = typeof varyHeader === 'string' + ? varyHeader.split(',') + : varyHeader + + for (const header of varyingHeaders) { + const trimmedHeader = header.trim().toLowerCase() + + output[trimmedHeader] = headers[trimmedHeader] ?? null + } + + return output +} + +/** + * Note: this deviates from the spec a little. Empty etags ("", W/"") are valid, + * however, including them in cached resposnes serves little to no purpose. + * + * @see https://www.rfc-editor.org/rfc/rfc9110.html#name-etag + * + * @param {string} etag + * @returns {boolean} + */ +function isEtagUsable (etag) { + if (etag.length <= 2) { + // Shortest an etag can be is two chars (just ""). This is where we deviate + // from the spec requiring a min of 3 chars however + return false + } + + if (etag[0] === '"' && etag[etag.length - 1] === '"') { + // ETag: ""asd123"" or ETag: "W/"asd123"", kinda undefined behavior in the + // spec. Some servers will accept these while others don't. + // ETag: "asd123" + return !(etag[1] === '"' || etag.startsWith('"W/')) + } + + if (etag.startsWith('W/"') && etag[etag.length - 1] === '"') { + // ETag: W/"", also where we deviate from the spec & require a min of 3 + // chars + // ETag: for W/"", W/"asd123" + return etag.length !== 4 + } + + // Anything else + return false +} + +/** + * @param {unknown} store + * @returns {asserts store is import('../../types/cache-interceptor.d.ts').default.CacheStore} + */ +function assertCacheStore (store, name = 'CacheStore') { + if (typeof store !== 'object' || store === null) { + throw new TypeError(`expected type of ${name} to be a CacheStore, got ${store === null ? 'null' : typeof store}`) + } + + for (const fn of ['get', 'createWriteStream', 'delete']) { + if (typeof store[fn] !== 'function') { + throw new TypeError(`${name} needs to have a \`${fn}()\` function`) + } + } +} +/** + * @param {unknown} methods + * @returns {asserts methods is import('../../types/cache-interceptor.d.ts').default.CacheMethods[]} + */ +function assertCacheMethods (methods, name = 'CacheMethods') { + if (!Array.isArray(methods)) { + throw new TypeError(`expected type of ${name} needs to be an array, got ${methods === null ? 'null' : typeof methods}`) + } + + if (methods.length === 0) { + throw new TypeError(`${name} needs to have at least one method`) + } + + for (const method of methods) { + if (!safeHTTPMethods.includes(method)) { + throw new TypeError(`element of ${name}-array needs to be one of following values: ${safeHTTPMethods.join(', ')}, got ${method}`) + } + } +} + +module.exports = { + makeCacheKey, + normalizeHeaders, + assertCacheKey, + assertCacheValue, + parseCacheControlHeader, + parseVaryHeader, + isEtagUsable, + assertCacheMethods, + assertCacheStore +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/util/date.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/util/date.js new file mode 100644 index 0000000000000000000000000000000000000000..b871c4497bfa9c6864d9130e3fb266dc2ea25ab4 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/util/date.js @@ -0,0 +1,259 @@ +'use strict' + +const IMF_DAYS = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] +const IMF_SPACES = [4, 7, 11, 16, 25] +const IMF_MONTHS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'] +const IMF_COLONS = [19, 22] + +const ASCTIME_SPACES = [3, 7, 10, 19] + +const RFC850_DAYS = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'] + +/** + * @see https://www.rfc-editor.org/rfc/rfc9110.html#name-date-time-formats + * + * @param {string} date + * @param {Date} [now] + * @returns {Date | undefined} + */ +function parseHttpDate (date, now) { + // Sun, 06 Nov 1994 08:49:37 GMT ; IMF-fixdate + // Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format + // Sunday, 06-Nov-94 08:49:37 GMT ; obsolete RFC 850 format + + date = date.toLowerCase() + + switch (date[3]) { + case ',': return parseImfDate(date) + case ' ': return parseAscTimeDate(date) + default: return parseRfc850Date(date, now) + } +} + +/** + * @see https://httpwg.org/specs/rfc9110.html#preferred.date.format + * + * @param {string} date + * @returns {Date | undefined} + */ +function parseImfDate (date) { + if (date.length !== 29) { + return undefined + } + + if (!date.endsWith('gmt')) { + // Unsupported timezone + return undefined + } + + for (const spaceInx of IMF_SPACES) { + if (date[spaceInx] !== ' ') { + return undefined + } + } + + for (const colonIdx of IMF_COLONS) { + if (date[colonIdx] !== ':') { + return undefined + } + } + + const dayName = date.substring(0, 3) + if (!IMF_DAYS.includes(dayName)) { + return undefined + } + + const dayString = date.substring(5, 7) + const day = Number.parseInt(dayString) + if (isNaN(day) || (day < 10 && dayString[0] !== '0')) { + // Not a number, 0, or it's less than 10 and didn't start with a 0 + return undefined + } + + const month = date.substring(8, 11) + const monthIdx = IMF_MONTHS.indexOf(month) + if (monthIdx === -1) { + return undefined + } + + const year = Number.parseInt(date.substring(12, 16)) + if (isNaN(year)) { + return undefined + } + + const hourString = date.substring(17, 19) + const hour = Number.parseInt(hourString) + if (isNaN(hour) || (hour < 10 && hourString[0] !== '0')) { + return undefined + } + + const minuteString = date.substring(20, 22) + const minute = Number.parseInt(minuteString) + if (isNaN(minute) || (minute < 10 && minuteString[0] !== '0')) { + return undefined + } + + const secondString = date.substring(23, 25) + const second = Number.parseInt(secondString) + if (isNaN(second) || (second < 10 && secondString[0] !== '0')) { + return undefined + } + + return new Date(Date.UTC(year, monthIdx, day, hour, minute, second)) +} + +/** + * @see https://httpwg.org/specs/rfc9110.html#obsolete.date.formats + * + * @param {string} date + * @returns {Date | undefined} + */ +function parseAscTimeDate (date) { + // This is assumed to be in UTC + + if (date.length !== 24) { + return undefined + } + + for (const spaceIdx of ASCTIME_SPACES) { + if (date[spaceIdx] !== ' ') { + return undefined + } + } + + const dayName = date.substring(0, 3) + if (!IMF_DAYS.includes(dayName)) { + return undefined + } + + const month = date.substring(4, 7) + const monthIdx = IMF_MONTHS.indexOf(month) + if (monthIdx === -1) { + return undefined + } + + const dayString = date.substring(8, 10) + const day = Number.parseInt(dayString) + if (isNaN(day) || (day < 10 && dayString[0] !== ' ')) { + return undefined + } + + const hourString = date.substring(11, 13) + const hour = Number.parseInt(hourString) + if (isNaN(hour) || (hour < 10 && hourString[0] !== '0')) { + return undefined + } + + const minuteString = date.substring(14, 16) + const minute = Number.parseInt(minuteString) + if (isNaN(minute) || (minute < 10 && minuteString[0] !== '0')) { + return undefined + } + + const secondString = date.substring(17, 19) + const second = Number.parseInt(secondString) + if (isNaN(second) || (second < 10 && secondString[0] !== '0')) { + return undefined + } + + const year = Number.parseInt(date.substring(20, 24)) + if (isNaN(year)) { + return undefined + } + + return new Date(Date.UTC(year, monthIdx, day, hour, minute, second)) +} + +/** + * @see https://httpwg.org/specs/rfc9110.html#obsolete.date.formats + * + * @param {string} date + * @param {Date} [now] + * @returns {Date | undefined} + */ +function parseRfc850Date (date, now = new Date()) { + if (!date.endsWith('gmt')) { + // Unsupported timezone + return undefined + } + + const commaIndex = date.indexOf(',') + if (commaIndex === -1) { + return undefined + } + + if ((date.length - commaIndex - 1) !== 23) { + return undefined + } + + const dayName = date.substring(0, commaIndex) + if (!RFC850_DAYS.includes(dayName)) { + return undefined + } + + if ( + date[commaIndex + 1] !== ' ' || + date[commaIndex + 4] !== '-' || + date[commaIndex + 8] !== '-' || + date[commaIndex + 11] !== ' ' || + date[commaIndex + 14] !== ':' || + date[commaIndex + 17] !== ':' || + date[commaIndex + 20] !== ' ' + ) { + return undefined + } + + const dayString = date.substring(commaIndex + 2, commaIndex + 4) + const day = Number.parseInt(dayString) + if (isNaN(day) || (day < 10 && dayString[0] !== '0')) { + // Not a number, or it's less than 10 and didn't start with a 0 + return undefined + } + + const month = date.substring(commaIndex + 5, commaIndex + 8) + const monthIdx = IMF_MONTHS.indexOf(month) + if (monthIdx === -1) { + return undefined + } + + // As of this point year is just the decade (i.e. 94) + let year = Number.parseInt(date.substring(commaIndex + 9, commaIndex + 11)) + if (isNaN(year)) { + return undefined + } + + const currentYear = now.getUTCFullYear() + const currentDecade = currentYear % 100 + const currentCentury = Math.floor(currentYear / 100) + + if (year > currentDecade && year - currentDecade >= 50) { + // Over 50 years in future, go to previous century + year += (currentCentury - 1) * 100 + } else { + year += currentCentury * 100 + } + + const hourString = date.substring(commaIndex + 12, commaIndex + 14) + const hour = Number.parseInt(hourString) + if (isNaN(hour) || (hour < 10 && hourString[0] !== '0')) { + return undefined + } + + const minuteString = date.substring(commaIndex + 15, commaIndex + 17) + const minute = Number.parseInt(minuteString) + if (isNaN(minute) || (minute < 10 && minuteString[0] !== '0')) { + return undefined + } + + const secondString = date.substring(commaIndex + 18, commaIndex + 20) + const second = Number.parseInt(secondString) + if (isNaN(second) || (second < 10 && secondString[0] !== '0')) { + return undefined + } + + return new Date(Date.UTC(year, monthIdx, day, hour, minute, second)) +} + +module.exports = { + parseHttpDate +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/util/promise.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/util/promise.js new file mode 100644 index 0000000000000000000000000000000000000000..048f86e34ef9dcefc152cdea36c704588e3bd1d9 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/util/promise.js @@ -0,0 +1,28 @@ +'use strict' + +/** + * @template {*} T + * @typedef {Object} DeferredPromise + * @property {Promise} promise + * @property {(value?: T) => void} resolve + * @property {(reason?: any) => void} reject + */ + +/** + * @template {*} T + * @returns {DeferredPromise} An object containing a promise and its resolve/reject methods. + */ +function createDeferredPromise () { + let res + let rej + const promise = new Promise((resolve, reject) => { + res = resolve + rej = reject + }) + + return { promise, resolve: res, reject: rej } +} + +module.exports = { + createDeferredPromise +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/util/stats.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/util/stats.js new file mode 100644 index 0000000000000000000000000000000000000000..a13132e4ec8d2820630ea486d49127d53961f536 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/util/stats.js @@ -0,0 +1,32 @@ +'use strict' + +const { + kConnected, + kPending, + kRunning, + kSize, + kFree, + kQueued +} = require('../core/symbols') + +class ClientStats { + constructor (client) { + this.connected = client[kConnected] + this.pending = client[kPending] + this.running = client[kRunning] + this.size = client[kSize] + } +} + +class PoolStats { + constructor (pool) { + this.connected = pool[kConnected] + this.free = pool[kFree] + this.pending = pool[kPending] + this.queued = pool[kQueued] + this.running = pool[kRunning] + this.size = pool[kSize] + } +} + +module.exports = { ClientStats, PoolStats } diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/util/timers.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/util/timers.js new file mode 100644 index 0000000000000000000000000000000000000000..14984d42ef2901af503b595002bc973bf069f9a4 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/util/timers.js @@ -0,0 +1,425 @@ +'use strict' + +/** + * This module offers an optimized timer implementation designed for scenarios + * where high precision is not critical. + * + * The timer achieves faster performance by using a low-resolution approach, + * with an accuracy target of within 500ms. This makes it particularly useful + * for timers with delays of 1 second or more, where exact timing is less + * crucial. + * + * It's important to note that Node.js timers are inherently imprecise, as + * delays can occur due to the event loop being blocked by other operations. + * Consequently, timers may trigger later than their scheduled time. + */ + +/** + * The fastNow variable contains the internal fast timer clock value. + * + * @type {number} + */ +let fastNow = 0 + +/** + * RESOLUTION_MS represents the target resolution time in milliseconds. + * + * @type {number} + * @default 1000 + */ +const RESOLUTION_MS = 1e3 + +/** + * TICK_MS defines the desired interval in milliseconds between each tick. + * The target value is set to half the resolution time, minus 1 ms, to account + * for potential event loop overhead. + * + * @type {number} + * @default 499 + */ +const TICK_MS = (RESOLUTION_MS >> 1) - 1 + +/** + * fastNowTimeout is a Node.js timer used to manage and process + * the FastTimers stored in the `fastTimers` array. + * + * @type {NodeJS.Timeout} + */ +let fastNowTimeout + +/** + * The kFastTimer symbol is used to identify FastTimer instances. + * + * @type {Symbol} + */ +const kFastTimer = Symbol('kFastTimer') + +/** + * The fastTimers array contains all active FastTimers. + * + * @type {FastTimer[]} + */ +const fastTimers = [] + +/** + * These constants represent the various states of a FastTimer. + */ + +/** + * The `NOT_IN_LIST` constant indicates that the FastTimer is not included + * in the `fastTimers` array. Timers with this status will not be processed + * during the next tick by the `onTick` function. + * + * A FastTimer can be re-added to the `fastTimers` array by invoking the + * `refresh` method on the FastTimer instance. + * + * @type {-2} + */ +const NOT_IN_LIST = -2 + +/** + * The `TO_BE_CLEARED` constant indicates that the FastTimer is scheduled + * for removal from the `fastTimers` array. A FastTimer in this state will + * be removed in the next tick by the `onTick` function and will no longer + * be processed. + * + * This status is also set when the `clear` method is called on the FastTimer instance. + * + * @type {-1} + */ +const TO_BE_CLEARED = -1 + +/** + * The `PENDING` constant signifies that the FastTimer is awaiting processing + * in the next tick by the `onTick` function. Timers with this status will have + * their `_idleStart` value set and their status updated to `ACTIVE` in the next tick. + * + * @type {0} + */ +const PENDING = 0 + +/** + * The `ACTIVE` constant indicates that the FastTimer is active and waiting + * for its timer to expire. During the next tick, the `onTick` function will + * check if the timer has expired, and if so, it will execute the associated callback. + * + * @type {1} + */ +const ACTIVE = 1 + +/** + * The onTick function processes the fastTimers array. + * + * @returns {void} + */ +function onTick () { + /** + * Increment the fastNow value by the TICK_MS value, despite the actual time + * that has passed since the last tick. This approach ensures independence + * from the system clock and delays caused by a blocked event loop. + * + * @type {number} + */ + fastNow += TICK_MS + + /** + * The `idx` variable is used to iterate over the `fastTimers` array. + * Expired timers are removed by replacing them with the last element in the array. + * Consequently, `idx` is only incremented when the current element is not removed. + * + * @type {number} + */ + let idx = 0 + + /** + * The len variable will contain the length of the fastTimers array + * and will be decremented when a FastTimer should be removed from the + * fastTimers array. + * + * @type {number} + */ + let len = fastTimers.length + + while (idx < len) { + /** + * @type {FastTimer} + */ + const timer = fastTimers[idx] + + // If the timer is in the ACTIVE state and the timer has expired, it will + // be processed in the next tick. + if (timer._state === PENDING) { + // Set the _idleStart value to the fastNow value minus the TICK_MS value + // to account for the time the timer was in the PENDING state. + timer._idleStart = fastNow - TICK_MS + timer._state = ACTIVE + } else if ( + timer._state === ACTIVE && + fastNow >= timer._idleStart + timer._idleTimeout + ) { + timer._state = TO_BE_CLEARED + timer._idleStart = -1 + timer._onTimeout(timer._timerArg) + } + + if (timer._state === TO_BE_CLEARED) { + timer._state = NOT_IN_LIST + + // Move the last element to the current index and decrement len if it is + // not the only element in the array. + if (--len !== 0) { + fastTimers[idx] = fastTimers[len] + } + } else { + ++idx + } + } + + // Set the length of the fastTimers array to the new length and thus + // removing the excess FastTimers elements from the array. + fastTimers.length = len + + // If there are still active FastTimers in the array, refresh the Timer. + // If there are no active FastTimers, the timer will be refreshed again + // when a new FastTimer is instantiated. + if (fastTimers.length !== 0) { + refreshTimeout() + } +} + +function refreshTimeout () { + // If the fastNowTimeout is already set and the Timer has the refresh()- + // method available, call it to refresh the timer. + // Some timer objects returned by setTimeout may not have a .refresh() + // method (e.g. mocked timers in tests). + if (fastNowTimeout?.refresh) { + fastNowTimeout.refresh() + // fastNowTimeout is not instantiated yet or refresh is not availabe, + // create a new Timer. + } else { + clearTimeout(fastNowTimeout) + fastNowTimeout = setTimeout(onTick, TICK_MS) + // If the Timer has an unref method, call it to allow the process to exit, + // if there are no other active handles. When using fake timers or mocked + // environments (like Jest), .unref() may not be defined, + fastNowTimeout?.unref() + } +} + +/** + * The `FastTimer` class is a data structure designed to store and manage + * timer information. + */ +class FastTimer { + [kFastTimer] = true + + /** + * The state of the timer, which can be one of the following: + * - NOT_IN_LIST (-2) + * - TO_BE_CLEARED (-1) + * - PENDING (0) + * - ACTIVE (1) + * + * @type {-2|-1|0|1} + * @private + */ + _state = NOT_IN_LIST + + /** + * The number of milliseconds to wait before calling the callback. + * + * @type {number} + * @private + */ + _idleTimeout = -1 + + /** + * The time in milliseconds when the timer was started. This value is used to + * calculate when the timer should expire. + * + * @type {number} + * @default -1 + * @private + */ + _idleStart = -1 + + /** + * The function to be executed when the timer expires. + * @type {Function} + * @private + */ + _onTimeout + + /** + * The argument to be passed to the callback when the timer expires. + * + * @type {*} + * @private + */ + _timerArg + + /** + * @constructor + * @param {Function} callback A function to be executed after the timer + * expires. + * @param {number} delay The time, in milliseconds that the timer should wait + * before the specified function or code is executed. + * @param {*} arg + */ + constructor (callback, delay, arg) { + this._onTimeout = callback + this._idleTimeout = delay + this._timerArg = arg + + this.refresh() + } + + /** + * Sets the timer's start time to the current time, and reschedules the timer + * to call its callback at the previously specified duration adjusted to the + * current time. + * Using this on a timer that has already called its callback will reactivate + * the timer. + * + * @returns {void} + */ + refresh () { + // In the special case that the timer is not in the list of active timers, + // add it back to the array to be processed in the next tick by the onTick + // function. + if (this._state === NOT_IN_LIST) { + fastTimers.push(this) + } + + // If the timer is the only active timer, refresh the fastNowTimeout for + // better resolution. + if (!fastNowTimeout || fastTimers.length === 1) { + refreshTimeout() + } + + // Setting the state to PENDING will cause the timer to be reset in the + // next tick by the onTick function. + this._state = PENDING + } + + /** + * The `clear` method cancels the timer, preventing it from executing. + * + * @returns {void} + * @private + */ + clear () { + // Set the state to TO_BE_CLEARED to mark the timer for removal in the next + // tick by the onTick function. + this._state = TO_BE_CLEARED + + // Reset the _idleStart value to -1 to indicate that the timer is no longer + // active. + this._idleStart = -1 + } +} + +/** + * This module exports a setTimeout and clearTimeout function that can be + * used as a drop-in replacement for the native functions. + */ +module.exports = { + /** + * The setTimeout() method sets a timer which executes a function once the + * timer expires. + * @param {Function} callback A function to be executed after the timer + * expires. + * @param {number} delay The time, in milliseconds that the timer should + * wait before the specified function or code is executed. + * @param {*} [arg] An optional argument to be passed to the callback function + * when the timer expires. + * @returns {NodeJS.Timeout|FastTimer} + */ + setTimeout (callback, delay, arg) { + // If the delay is less than or equal to the RESOLUTION_MS value return a + // native Node.js Timer instance. + return delay <= RESOLUTION_MS + ? setTimeout(callback, delay, arg) + : new FastTimer(callback, delay, arg) + }, + /** + * The clearTimeout method cancels an instantiated Timer previously created + * by calling setTimeout. + * + * @param {NodeJS.Timeout|FastTimer} timeout + */ + clearTimeout (timeout) { + // If the timeout is a FastTimer, call its own clear method. + if (timeout[kFastTimer]) { + /** + * @type {FastTimer} + */ + timeout.clear() + // Otherwise it is an instance of a native NodeJS.Timeout, so call the + // Node.js native clearTimeout function. + } else { + clearTimeout(timeout) + } + }, + /** + * The setFastTimeout() method sets a fastTimer which executes a function once + * the timer expires. + * @param {Function} callback A function to be executed after the timer + * expires. + * @param {number} delay The time, in milliseconds that the timer should + * wait before the specified function or code is executed. + * @param {*} [arg] An optional argument to be passed to the callback function + * when the timer expires. + * @returns {FastTimer} + */ + setFastTimeout (callback, delay, arg) { + return new FastTimer(callback, delay, arg) + }, + /** + * The clearTimeout method cancels an instantiated FastTimer previously + * created by calling setFastTimeout. + * + * @param {FastTimer} timeout + */ + clearFastTimeout (timeout) { + timeout.clear() + }, + /** + * The now method returns the value of the internal fast timer clock. + * + * @returns {number} + */ + now () { + return fastNow + }, + /** + * Trigger the onTick function to process the fastTimers array. + * Exported for testing purposes only. + * Marking as deprecated to discourage any use outside of testing. + * @deprecated + * @param {number} [delay=0] The delay in milliseconds to add to the now value. + */ + tick (delay = 0) { + fastNow += delay - RESOLUTION_MS + 1 + onTick() + onTick() + }, + /** + * Reset FastTimers. + * Exported for testing purposes only. + * Marking as deprecated to discourage any use outside of testing. + * @deprecated + */ + reset () { + fastNow = 0 + fastTimers.length = 0 + clearTimeout(fastNowTimeout) + fastNowTimeout = null + }, + /** + * Exporting for testing purposes only. + * Marking as deprecated to discourage any use outside of testing. + * @deprecated + */ + kFastTimer +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/cache/cache.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/cache/cache.js new file mode 100644 index 0000000000000000000000000000000000000000..70a3787a71d415c5c536d069ba2404f99adbee87 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/cache/cache.js @@ -0,0 +1,864 @@ +'use strict' + +const assert = require('node:assert') + +const { kConstruct } = require('../../core/symbols') +const { urlEquals, getFieldValues } = require('./util') +const { kEnumerableProperty, isDisturbed } = require('../../core/util') +const { webidl } = require('../webidl') +const { cloneResponse, fromInnerResponse, getResponseState } = require('../fetch/response') +const { Request, fromInnerRequest, getRequestState } = require('../fetch/request') +const { fetching } = require('../fetch/index') +const { urlIsHttpHttpsScheme, readAllBytes } = require('../fetch/util') +const { createDeferredPromise } = require('../../util/promise') + +/** + * @see https://w3c.github.io/ServiceWorker/#dfn-cache-batch-operation + * @typedef {Object} CacheBatchOperation + * @property {'delete' | 'put'} type + * @property {any} request + * @property {any} response + * @property {import('../../../types/cache').CacheQueryOptions} options + */ + +/** + * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list + * @typedef {[any, any][]} requestResponseList + */ + +class Cache { + /** + * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list + * @type {requestResponseList} + */ + #relevantRequestResponseList + + constructor () { + if (arguments[0] !== kConstruct) { + webidl.illegalConstructor() + } + + webidl.util.markAsUncloneable(this) + this.#relevantRequestResponseList = arguments[1] + } + + async match (request, options = {}) { + webidl.brandCheck(this, Cache) + + const prefix = 'Cache.match' + webidl.argumentLengthCheck(arguments, 1, prefix) + + request = webidl.converters.RequestInfo(request) + options = webidl.converters.CacheQueryOptions(options, prefix, 'options') + + const p = this.#internalMatchAll(request, options, 1) + + if (p.length === 0) { + return + } + + return p[0] + } + + async matchAll (request = undefined, options = {}) { + webidl.brandCheck(this, Cache) + + const prefix = 'Cache.matchAll' + if (request !== undefined) request = webidl.converters.RequestInfo(request) + options = webidl.converters.CacheQueryOptions(options, prefix, 'options') + + return this.#internalMatchAll(request, options) + } + + async add (request) { + webidl.brandCheck(this, Cache) + + const prefix = 'Cache.add' + webidl.argumentLengthCheck(arguments, 1, prefix) + + request = webidl.converters.RequestInfo(request) + + // 1. + const requests = [request] + + // 2. + const responseArrayPromise = this.addAll(requests) + + // 3. + return await responseArrayPromise + } + + async addAll (requests) { + webidl.brandCheck(this, Cache) + + const prefix = 'Cache.addAll' + webidl.argumentLengthCheck(arguments, 1, prefix) + + // 1. + const responsePromises = [] + + // 2. + const requestList = [] + + // 3. + for (let request of requests) { + if (request === undefined) { + throw webidl.errors.conversionFailed({ + prefix, + argument: 'Argument 1', + types: ['undefined is not allowed'] + }) + } + + request = webidl.converters.RequestInfo(request) + + if (typeof request === 'string') { + continue + } + + // 3.1 + const r = getRequestState(request) + + // 3.2 + if (!urlIsHttpHttpsScheme(r.url) || r.method !== 'GET') { + throw webidl.errors.exception({ + header: prefix, + message: 'Expected http/s scheme when method is not GET.' + }) + } + } + + // 4. + /** @type {ReturnType[]} */ + const fetchControllers = [] + + // 5. + for (const request of requests) { + // 5.1 + const r = getRequestState(new Request(request)) + + // 5.2 + if (!urlIsHttpHttpsScheme(r.url)) { + throw webidl.errors.exception({ + header: prefix, + message: 'Expected http/s scheme.' + }) + } + + // 5.4 + r.initiator = 'fetch' + r.destination = 'subresource' + + // 5.5 + requestList.push(r) + + // 5.6 + const responsePromise = createDeferredPromise() + + // 5.7 + fetchControllers.push(fetching({ + request: r, + processResponse (response) { + // 1. + if (response.type === 'error' || response.status === 206 || response.status < 200 || response.status > 299) { + responsePromise.reject(webidl.errors.exception({ + header: 'Cache.addAll', + message: 'Received an invalid status code or the request failed.' + })) + } else if (response.headersList.contains('vary')) { // 2. + // 2.1 + const fieldValues = getFieldValues(response.headersList.get('vary')) + + // 2.2 + for (const fieldValue of fieldValues) { + // 2.2.1 + if (fieldValue === '*') { + responsePromise.reject(webidl.errors.exception({ + header: 'Cache.addAll', + message: 'invalid vary field value' + })) + + for (const controller of fetchControllers) { + controller.abort() + } + + return + } + } + } + }, + processResponseEndOfBody (response) { + // 1. + if (response.aborted) { + responsePromise.reject(new DOMException('aborted', 'AbortError')) + return + } + + // 2. + responsePromise.resolve(response) + } + })) + + // 5.8 + responsePromises.push(responsePromise.promise) + } + + // 6. + const p = Promise.all(responsePromises) + + // 7. + const responses = await p + + // 7.1 + const operations = [] + + // 7.2 + let index = 0 + + // 7.3 + for (const response of responses) { + // 7.3.1 + /** @type {CacheBatchOperation} */ + const operation = { + type: 'put', // 7.3.2 + request: requestList[index], // 7.3.3 + response // 7.3.4 + } + + operations.push(operation) // 7.3.5 + + index++ // 7.3.6 + } + + // 7.5 + const cacheJobPromise = createDeferredPromise() + + // 7.6.1 + let errorData = null + + // 7.6.2 + try { + this.#batchCacheOperations(operations) + } catch (e) { + errorData = e + } + + // 7.6.3 + queueMicrotask(() => { + // 7.6.3.1 + if (errorData === null) { + cacheJobPromise.resolve(undefined) + } else { + // 7.6.3.2 + cacheJobPromise.reject(errorData) + } + }) + + // 7.7 + return cacheJobPromise.promise + } + + async put (request, response) { + webidl.brandCheck(this, Cache) + + const prefix = 'Cache.put' + webidl.argumentLengthCheck(arguments, 2, prefix) + + request = webidl.converters.RequestInfo(request) + response = webidl.converters.Response(response, prefix, 'response') + + // 1. + let innerRequest = null + + // 2. + if (webidl.is.Request(request)) { + innerRequest = getRequestState(request) + } else { // 3. + innerRequest = getRequestState(new Request(request)) + } + + // 4. + if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== 'GET') { + throw webidl.errors.exception({ + header: prefix, + message: 'Expected an http/s scheme when method is not GET' + }) + } + + // 5. + const innerResponse = getResponseState(response) + + // 6. + if (innerResponse.status === 206) { + throw webidl.errors.exception({ + header: prefix, + message: 'Got 206 status' + }) + } + + // 7. + if (innerResponse.headersList.contains('vary')) { + // 7.1. + const fieldValues = getFieldValues(innerResponse.headersList.get('vary')) + + // 7.2. + for (const fieldValue of fieldValues) { + // 7.2.1 + if (fieldValue === '*') { + throw webidl.errors.exception({ + header: prefix, + message: 'Got * vary field value' + }) + } + } + } + + // 8. + if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) { + throw webidl.errors.exception({ + header: prefix, + message: 'Response body is locked or disturbed' + }) + } + + // 9. + const clonedResponse = cloneResponse(innerResponse) + + // 10. + const bodyReadPromise = createDeferredPromise() + + // 11. + if (innerResponse.body != null) { + // 11.1 + const stream = innerResponse.body.stream + + // 11.2 + const reader = stream.getReader() + + // 11.3 + readAllBytes(reader, bodyReadPromise.resolve, bodyReadPromise.reject) + } else { + bodyReadPromise.resolve(undefined) + } + + // 12. + /** @type {CacheBatchOperation[]} */ + const operations = [] + + // 13. + /** @type {CacheBatchOperation} */ + const operation = { + type: 'put', // 14. + request: innerRequest, // 15. + response: clonedResponse // 16. + } + + // 17. + operations.push(operation) + + // 19. + const bytes = await bodyReadPromise.promise + + if (clonedResponse.body != null) { + clonedResponse.body.source = bytes + } + + // 19.1 + const cacheJobPromise = createDeferredPromise() + + // 19.2.1 + let errorData = null + + // 19.2.2 + try { + this.#batchCacheOperations(operations) + } catch (e) { + errorData = e + } + + // 19.2.3 + queueMicrotask(() => { + // 19.2.3.1 + if (errorData === null) { + cacheJobPromise.resolve() + } else { // 19.2.3.2 + cacheJobPromise.reject(errorData) + } + }) + + return cacheJobPromise.promise + } + + async delete (request, options = {}) { + webidl.brandCheck(this, Cache) + + const prefix = 'Cache.delete' + webidl.argumentLengthCheck(arguments, 1, prefix) + + request = webidl.converters.RequestInfo(request) + options = webidl.converters.CacheQueryOptions(options, prefix, 'options') + + /** + * @type {Request} + */ + let r = null + + if (webidl.is.Request(request)) { + r = getRequestState(request) + + if (r.method !== 'GET' && !options.ignoreMethod) { + return false + } + } else { + assert(typeof request === 'string') + + r = getRequestState(new Request(request)) + } + + /** @type {CacheBatchOperation[]} */ + const operations = [] + + /** @type {CacheBatchOperation} */ + const operation = { + type: 'delete', + request: r, + options + } + + operations.push(operation) + + const cacheJobPromise = createDeferredPromise() + + let errorData = null + let requestResponses + + try { + requestResponses = this.#batchCacheOperations(operations) + } catch (e) { + errorData = e + } + + queueMicrotask(() => { + if (errorData === null) { + cacheJobPromise.resolve(!!requestResponses?.length) + } else { + cacheJobPromise.reject(errorData) + } + }) + + return cacheJobPromise.promise + } + + /** + * @see https://w3c.github.io/ServiceWorker/#dom-cache-keys + * @param {any} request + * @param {import('../../../types/cache').CacheQueryOptions} options + * @returns {Promise} + */ + async keys (request = undefined, options = {}) { + webidl.brandCheck(this, Cache) + + const prefix = 'Cache.keys' + + if (request !== undefined) request = webidl.converters.RequestInfo(request) + options = webidl.converters.CacheQueryOptions(options, prefix, 'options') + + // 1. + let r = null + + // 2. + if (request !== undefined) { + // 2.1 + if (webidl.is.Request(request)) { + // 2.1.1 + r = getRequestState(request) + + // 2.1.2 + if (r.method !== 'GET' && !options.ignoreMethod) { + return [] + } + } else if (typeof request === 'string') { // 2.2 + r = getRequestState(new Request(request)) + } + } + + // 4. + const promise = createDeferredPromise() + + // 5. + // 5.1 + const requests = [] + + // 5.2 + if (request === undefined) { + // 5.2.1 + for (const requestResponse of this.#relevantRequestResponseList) { + // 5.2.1.1 + requests.push(requestResponse[0]) + } + } else { // 5.3 + // 5.3.1 + const requestResponses = this.#queryCache(r, options) + + // 5.3.2 + for (const requestResponse of requestResponses) { + // 5.3.2.1 + requests.push(requestResponse[0]) + } + } + + // 5.4 + queueMicrotask(() => { + // 5.4.1 + const requestList = [] + + // 5.4.2 + for (const request of requests) { + const requestObject = fromInnerRequest( + request, + undefined, + new AbortController().signal, + 'immutable' + ) + // 5.4.2.1 + requestList.push(requestObject) + } + + // 5.4.3 + promise.resolve(Object.freeze(requestList)) + }) + + return promise.promise + } + + /** + * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm + * @param {CacheBatchOperation[]} operations + * @returns {requestResponseList} + */ + #batchCacheOperations (operations) { + // 1. + const cache = this.#relevantRequestResponseList + + // 2. + const backupCache = [...cache] + + // 3. + const addedItems = [] + + // 4.1 + const resultList = [] + + try { + // 4.2 + for (const operation of operations) { + // 4.2.1 + if (operation.type !== 'delete' && operation.type !== 'put') { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'operation type does not match "delete" or "put"' + }) + } + + // 4.2.2 + if (operation.type === 'delete' && operation.response != null) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'delete operation should not have an associated response' + }) + } + + // 4.2.3 + if (this.#queryCache(operation.request, operation.options, addedItems).length) { + throw new DOMException('???', 'InvalidStateError') + } + + // 4.2.4 + let requestResponses + + // 4.2.5 + if (operation.type === 'delete') { + // 4.2.5.1 + requestResponses = this.#queryCache(operation.request, operation.options) + + // TODO: the spec is wrong, this is needed to pass WPTs + if (requestResponses.length === 0) { + return [] + } + + // 4.2.5.2 + for (const requestResponse of requestResponses) { + const idx = cache.indexOf(requestResponse) + assert(idx !== -1) + + // 4.2.5.2.1 + cache.splice(idx, 1) + } + } else if (operation.type === 'put') { // 4.2.6 + // 4.2.6.1 + if (operation.response == null) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'put operation should have an associated response' + }) + } + + // 4.2.6.2 + const r = operation.request + + // 4.2.6.3 + if (!urlIsHttpHttpsScheme(r.url)) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'expected http or https scheme' + }) + } + + // 4.2.6.4 + if (r.method !== 'GET') { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'not get method' + }) + } + + // 4.2.6.5 + if (operation.options != null) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'options must not be defined' + }) + } + + // 4.2.6.6 + requestResponses = this.#queryCache(operation.request) + + // 4.2.6.7 + for (const requestResponse of requestResponses) { + const idx = cache.indexOf(requestResponse) + assert(idx !== -1) + + // 4.2.6.7.1 + cache.splice(idx, 1) + } + + // 4.2.6.8 + cache.push([operation.request, operation.response]) + + // 4.2.6.10 + addedItems.push([operation.request, operation.response]) + } + + // 4.2.7 + resultList.push([operation.request, operation.response]) + } + + // 4.3 + return resultList + } catch (e) { // 5. + // 5.1 + this.#relevantRequestResponseList.length = 0 + + // 5.2 + this.#relevantRequestResponseList = backupCache + + // 5.3 + throw e + } + } + + /** + * @see https://w3c.github.io/ServiceWorker/#query-cache + * @param {any} requestQuery + * @param {import('../../../types/cache').CacheQueryOptions} options + * @param {requestResponseList} targetStorage + * @returns {requestResponseList} + */ + #queryCache (requestQuery, options, targetStorage) { + /** @type {requestResponseList} */ + const resultList = [] + + const storage = targetStorage ?? this.#relevantRequestResponseList + + for (const requestResponse of storage) { + const [cachedRequest, cachedResponse] = requestResponse + if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) { + resultList.push(requestResponse) + } + } + + return resultList + } + + /** + * @see https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm + * @param {any} requestQuery + * @param {any} request + * @param {any | null} response + * @param {import('../../../types/cache').CacheQueryOptions | undefined} options + * @returns {boolean} + */ + #requestMatchesCachedItem (requestQuery, request, response = null, options) { + // if (options?.ignoreMethod === false && request.method === 'GET') { + // return false + // } + + const queryURL = new URL(requestQuery.url) + + const cachedURL = new URL(request.url) + + if (options?.ignoreSearch) { + cachedURL.search = '' + + queryURL.search = '' + } + + if (!urlEquals(queryURL, cachedURL, true)) { + return false + } + + if ( + response == null || + options?.ignoreVary || + !response.headersList.contains('vary') + ) { + return true + } + + const fieldValues = getFieldValues(response.headersList.get('vary')) + + for (const fieldValue of fieldValues) { + if (fieldValue === '*') { + return false + } + + const requestValue = request.headersList.get(fieldValue) + const queryValue = requestQuery.headersList.get(fieldValue) + + // If one has the header and the other doesn't, or one has + // a different value than the other, return false + if (requestValue !== queryValue) { + return false + } + } + + return true + } + + #internalMatchAll (request, options, maxResponses = Infinity) { + // 1. + let r = null + + // 2. + if (request !== undefined) { + if (webidl.is.Request(request)) { + // 2.1.1 + r = getRequestState(request) + + // 2.1.2 + if (r.method !== 'GET' && !options.ignoreMethod) { + return [] + } + } else if (typeof request === 'string') { + // 2.2.1 + r = getRequestState(new Request(request)) + } + } + + // 5. + // 5.1 + const responses = [] + + // 5.2 + if (request === undefined) { + // 5.2.1 + for (const requestResponse of this.#relevantRequestResponseList) { + responses.push(requestResponse[1]) + } + } else { // 5.3 + // 5.3.1 + const requestResponses = this.#queryCache(r, options) + + // 5.3.2 + for (const requestResponse of requestResponses) { + responses.push(requestResponse[1]) + } + } + + // 5.4 + // We don't implement CORs so we don't need to loop over the responses, yay! + + // 5.5.1 + const responseList = [] + + // 5.5.2 + for (const response of responses) { + // 5.5.2.1 + const responseObject = fromInnerResponse(response, 'immutable') + + responseList.push(responseObject.clone()) + + if (responseList.length >= maxResponses) { + break + } + } + + // 6. + return Object.freeze(responseList) + } +} + +Object.defineProperties(Cache.prototype, { + [Symbol.toStringTag]: { + value: 'Cache', + configurable: true + }, + match: kEnumerableProperty, + matchAll: kEnumerableProperty, + add: kEnumerableProperty, + addAll: kEnumerableProperty, + put: kEnumerableProperty, + delete: kEnumerableProperty, + keys: kEnumerableProperty +}) + +const cacheQueryOptionConverters = [ + { + key: 'ignoreSearch', + converter: webidl.converters.boolean, + defaultValue: () => false + }, + { + key: 'ignoreMethod', + converter: webidl.converters.boolean, + defaultValue: () => false + }, + { + key: 'ignoreVary', + converter: webidl.converters.boolean, + defaultValue: () => false + } +] + +webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters) + +webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([ + ...cacheQueryOptionConverters, + { + key: 'cacheName', + converter: webidl.converters.DOMString + } +]) + +webidl.converters.Response = webidl.interfaceConverter( + webidl.is.Response, + 'Response' +) + +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.RequestInfo +) + +module.exports = { + Cache +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/cache/cachestorage.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/cache/cachestorage.js new file mode 100644 index 0000000000000000000000000000000000000000..c49b1e82ec1ffffd84a87c4e81e26f9754d8ab34 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/cache/cachestorage.js @@ -0,0 +1,152 @@ +'use strict' + +const { Cache } = require('./cache') +const { webidl } = require('../webidl') +const { kEnumerableProperty } = require('../../core/util') +const { kConstruct } = require('../../core/symbols') + +class CacheStorage { + /** + * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map + * @type {Map} + */ + async has (cacheName) { + webidl.brandCheck(this, CacheStorage) + + const prefix = 'CacheStorage.has' + webidl.argumentLengthCheck(arguments, 1, prefix) + + cacheName = webidl.converters.DOMString(cacheName, prefix, 'cacheName') + + // 2.1.1 + // 2.2 + return this.#caches.has(cacheName) + } + + /** + * @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open + * @param {string} cacheName + * @returns {Promise} + */ + async open (cacheName) { + webidl.brandCheck(this, CacheStorage) + + const prefix = 'CacheStorage.open' + webidl.argumentLengthCheck(arguments, 1, prefix) + + cacheName = webidl.converters.DOMString(cacheName, prefix, 'cacheName') + + // 2.1 + if (this.#caches.has(cacheName)) { + // await caches.open('v1') !== await caches.open('v1') + + // 2.1.1 + const cache = this.#caches.get(cacheName) + + // 2.1.1.1 + return new Cache(kConstruct, cache) + } + + // 2.2 + const cache = [] + + // 2.3 + this.#caches.set(cacheName, cache) + + // 2.4 + return new Cache(kConstruct, cache) + } + + /** + * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete + * @param {string} cacheName + * @returns {Promise} + */ + async delete (cacheName) { + webidl.brandCheck(this, CacheStorage) + + const prefix = 'CacheStorage.delete' + webidl.argumentLengthCheck(arguments, 1, prefix) + + cacheName = webidl.converters.DOMString(cacheName, prefix, 'cacheName') + + return this.#caches.delete(cacheName) + } + + /** + * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys + * @returns {Promise} + */ + async keys () { + webidl.brandCheck(this, CacheStorage) + + // 2.1 + const keys = this.#caches.keys() + + // 2.2 + return [...keys] + } +} + +Object.defineProperties(CacheStorage.prototype, { + [Symbol.toStringTag]: { + value: 'CacheStorage', + configurable: true + }, + match: kEnumerableProperty, + has: kEnumerableProperty, + open: kEnumerableProperty, + delete: kEnumerableProperty, + keys: kEnumerableProperty +}) + +module.exports = { + CacheStorage +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/cache/util.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/cache/util.js new file mode 100644 index 0000000000000000000000000000000000000000..5ac9d846ddc09b972754c86f0fd431b36035404e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/cache/util.js @@ -0,0 +1,45 @@ +'use strict' + +const assert = require('node:assert') +const { URLSerializer } = require('../fetch/data-url') +const { isValidHeaderName } = require('../fetch/util') + +/** + * @see https://url.spec.whatwg.org/#concept-url-equals + * @param {URL} A + * @param {URL} B + * @param {boolean | undefined} excludeFragment + * @returns {boolean} + */ +function urlEquals (A, B, excludeFragment = false) { + const serializedA = URLSerializer(A, excludeFragment) + + const serializedB = URLSerializer(B, excludeFragment) + + return serializedA === serializedB +} + +/** + * @see https://github.com/chromium/chromium/blob/694d20d134cb553d8d89e5500b9148012b1ba299/content/browser/cache_storage/cache_storage_cache.cc#L260-L262 + * @param {string} header + */ +function getFieldValues (header) { + assert(header !== null) + + const values = [] + + for (let value of header.split(',')) { + value = value.trim() + + if (isValidHeaderName(value)) { + values.push(value) + } + } + + return values +} + +module.exports = { + urlEquals, + getFieldValues +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/cookies/constants.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/cookies/constants.js new file mode 100644 index 0000000000000000000000000000000000000000..85f1fec0e93c805bb9c8f830009f853f1345ff1c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/cookies/constants.js @@ -0,0 +1,12 @@ +'use strict' + +// https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size +const maxAttributeValueSize = 1024 + +// https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size +const maxNameValuePairSize = 4096 + +module.exports = { + maxAttributeValueSize, + maxNameValuePairSize +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/cookies/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/cookies/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1d891f1d692ea2d124ccfd55617aa39f1e567053 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/cookies/index.js @@ -0,0 +1,199 @@ +'use strict' + +const { parseSetCookie } = require('./parse') +const { stringify } = require('./util') +const { webidl } = require('../webidl') +const { Headers } = require('../fetch/headers') + +const brandChecks = webidl.brandCheckMultiple([Headers, globalThis.Headers].filter(Boolean)) + +/** + * @typedef {Object} Cookie + * @property {string} name + * @property {string} value + * @property {Date|number} [expires] + * @property {number} [maxAge] + * @property {string} [domain] + * @property {string} [path] + * @property {boolean} [secure] + * @property {boolean} [httpOnly] + * @property {'Strict'|'Lax'|'None'} [sameSite] + * @property {string[]} [unparsed] + */ + +/** + * @param {Headers} headers + * @returns {Record} + */ +function getCookies (headers) { + webidl.argumentLengthCheck(arguments, 1, 'getCookies') + + brandChecks(headers) + + const cookie = headers.get('cookie') + + /** @type {Record} */ + const out = {} + + if (!cookie) { + return out + } + + for (const piece of cookie.split(';')) { + const [name, ...value] = piece.split('=') + + out[name.trim()] = value.join('=') + } + + return out +} + +/** + * @param {Headers} headers + * @param {string} name + * @param {{ path?: string, domain?: string }|undefined} attributes + * @returns {void} + */ +function deleteCookie (headers, name, attributes) { + brandChecks(headers) + + const prefix = 'deleteCookie' + webidl.argumentLengthCheck(arguments, 2, prefix) + + name = webidl.converters.DOMString(name, prefix, 'name') + attributes = webidl.converters.DeleteCookieAttributes(attributes) + + // Matches behavior of + // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278 + setCookie(headers, { + name, + value: '', + expires: new Date(0), + ...attributes + }) +} + +/** + * @param {Headers} headers + * @returns {Cookie[]} + */ +function getSetCookies (headers) { + webidl.argumentLengthCheck(arguments, 1, 'getSetCookies') + + brandChecks(headers) + + const cookies = headers.getSetCookie() + + if (!cookies) { + return [] + } + + return cookies.map((pair) => parseSetCookie(pair)) +} + +/** + * Parses a cookie string + * @param {string} cookie + */ +function parseCookie (cookie) { + cookie = webidl.converters.DOMString(cookie) + + return parseSetCookie(cookie) +} + +/** + * @param {Headers} headers + * @param {Cookie} cookie + * @returns {void} + */ +function setCookie (headers, cookie) { + webidl.argumentLengthCheck(arguments, 2, 'setCookie') + + brandChecks(headers) + + cookie = webidl.converters.Cookie(cookie) + + const str = stringify(cookie) + + if (str) { + headers.append('set-cookie', str, true) + } +} + +webidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([ + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'path', + defaultValue: () => null + }, + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'domain', + defaultValue: () => null + } +]) + +webidl.converters.Cookie = webidl.dictionaryConverter([ + { + converter: webidl.converters.DOMString, + key: 'name' + }, + { + converter: webidl.converters.DOMString, + key: 'value' + }, + { + converter: webidl.nullableConverter((value) => { + if (typeof value === 'number') { + return webidl.converters['unsigned long long'](value) + } + + return new Date(value) + }), + key: 'expires', + defaultValue: () => null + }, + { + converter: webidl.nullableConverter(webidl.converters['long long']), + key: 'maxAge', + defaultValue: () => null + }, + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'domain', + defaultValue: () => null + }, + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'path', + defaultValue: () => null + }, + { + converter: webidl.nullableConverter(webidl.converters.boolean), + key: 'secure', + defaultValue: () => null + }, + { + converter: webidl.nullableConverter(webidl.converters.boolean), + key: 'httpOnly', + defaultValue: () => null + }, + { + converter: webidl.converters.USVString, + key: 'sameSite', + allowedValues: ['Strict', 'Lax', 'None'] + }, + { + converter: webidl.sequenceConverter(webidl.converters.DOMString), + key: 'unparsed', + defaultValue: () => new Array(0) + } +]) + +module.exports = { + getCookies, + deleteCookie, + getSetCookies, + setCookie, + parseCookie +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/cookies/parse.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/cookies/parse.js new file mode 100644 index 0000000000000000000000000000000000000000..708be8b146943fe84800db9d6c1df08d2c4eeb96 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/cookies/parse.js @@ -0,0 +1,322 @@ +'use strict' + +const { maxNameValuePairSize, maxAttributeValueSize } = require('./constants') +const { isCTLExcludingHtab } = require('./util') +const { collectASequenceOfCodePointsFast } = require('../fetch/data-url') +const assert = require('node:assert') +const { unescape: qsUnescape } = require('node:querystring') + +/** + * @description Parses the field-value attributes of a set-cookie header string. + * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4 + * @param {string} header + * @returns {import('./index').Cookie|null} if the header is invalid, null will be returned + */ +function parseSetCookie (header) { + // 1. If the set-cookie-string contains a %x00-08 / %x0A-1F / %x7F + // character (CTL characters excluding HTAB): Abort these steps and + // ignore the set-cookie-string entirely. + if (isCTLExcludingHtab(header)) { + return null + } + + let nameValuePair = '' + let unparsedAttributes = '' + let name = '' + let value = '' + + // 2. If the set-cookie-string contains a %x3B (";") character: + if (header.includes(';')) { + // 1. The name-value-pair string consists of the characters up to, + // but not including, the first %x3B (";"), and the unparsed- + // attributes consist of the remainder of the set-cookie-string + // (including the %x3B (";") in question). + const position = { position: 0 } + + nameValuePair = collectASequenceOfCodePointsFast(';', header, position) + unparsedAttributes = header.slice(position.position) + } else { + // Otherwise: + + // 1. The name-value-pair string consists of all the characters + // contained in the set-cookie-string, and the unparsed- + // attributes is the empty string. + nameValuePair = header + } + + // 3. If the name-value-pair string lacks a %x3D ("=") character, then + // the name string is empty, and the value string is the value of + // name-value-pair. + if (!nameValuePair.includes('=')) { + value = nameValuePair + } else { + // Otherwise, the name string consists of the characters up to, but + // not including, the first %x3D ("=") character, and the (possibly + // empty) value string consists of the characters after the first + // %x3D ("=") character. + const position = { position: 0 } + name = collectASequenceOfCodePointsFast( + '=', + nameValuePair, + position + ) + value = nameValuePair.slice(position.position + 1) + } + + // 4. Remove any leading or trailing WSP characters from the name + // string and the value string. + name = name.trim() + value = value.trim() + + // 5. If the sum of the lengths of the name string and the value string + // is more than 4096 octets, abort these steps and ignore the set- + // cookie-string entirely. + if (name.length + value.length > maxNameValuePairSize) { + return null + } + + // 6. The cookie-name is the name string, and the cookie-value is the + // value string. + // https://datatracker.ietf.org/doc/html/rfc6265 + // To maximize compatibility with user agents, servers that wish to + // store arbitrary data in a cookie-value SHOULD encode that data, for + // example, using Base64 [RFC4648]. + return { + name, value: qsUnescape(value), ...parseUnparsedAttributes(unparsedAttributes) + } +} + +/** + * Parses the remaining attributes of a set-cookie header + * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4 + * @param {string} unparsedAttributes + * @param {Object.} [cookieAttributeList={}] + */ +function parseUnparsedAttributes (unparsedAttributes, cookieAttributeList = {}) { + // 1. If the unparsed-attributes string is empty, skip the rest of + // these steps. + if (unparsedAttributes.length === 0) { + return cookieAttributeList + } + + // 2. Discard the first character of the unparsed-attributes (which + // will be a %x3B (";") character). + assert(unparsedAttributes[0] === ';') + unparsedAttributes = unparsedAttributes.slice(1) + + let cookieAv = '' + + // 3. If the remaining unparsed-attributes contains a %x3B (";") + // character: + if (unparsedAttributes.includes(';')) { + // 1. Consume the characters of the unparsed-attributes up to, but + // not including, the first %x3B (";") character. + cookieAv = collectASequenceOfCodePointsFast( + ';', + unparsedAttributes, + { position: 0 } + ) + unparsedAttributes = unparsedAttributes.slice(cookieAv.length) + } else { + // Otherwise: + + // 1. Consume the remainder of the unparsed-attributes. + cookieAv = unparsedAttributes + unparsedAttributes = '' + } + + // Let the cookie-av string be the characters consumed in this step. + + let attributeName = '' + let attributeValue = '' + + // 4. If the cookie-av string contains a %x3D ("=") character: + if (cookieAv.includes('=')) { + // 1. The (possibly empty) attribute-name string consists of the + // characters up to, but not including, the first %x3D ("=") + // character, and the (possibly empty) attribute-value string + // consists of the characters after the first %x3D ("=") + // character. + const position = { position: 0 } + + attributeName = collectASequenceOfCodePointsFast( + '=', + cookieAv, + position + ) + attributeValue = cookieAv.slice(position.position + 1) + } else { + // Otherwise: + + // 1. The attribute-name string consists of the entire cookie-av + // string, and the attribute-value string is empty. + attributeName = cookieAv + } + + // 5. Remove any leading or trailing WSP characters from the attribute- + // name string and the attribute-value string. + attributeName = attributeName.trim() + attributeValue = attributeValue.trim() + + // 6. If the attribute-value is longer than 1024 octets, ignore the + // cookie-av string and return to Step 1 of this algorithm. + if (attributeValue.length > maxAttributeValueSize) { + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } + + // 7. Process the attribute-name and attribute-value according to the + // requirements in the following subsections. (Notice that + // attributes with unrecognized attribute-names are ignored.) + const attributeNameLowercase = attributeName.toLowerCase() + + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.1 + // If the attribute-name case-insensitively matches the string + // "Expires", the user agent MUST process the cookie-av as follows. + if (attributeNameLowercase === 'expires') { + // 1. Let the expiry-time be the result of parsing the attribute-value + // as cookie-date (see Section 5.1.1). + const expiryTime = new Date(attributeValue) + + // 2. If the attribute-value failed to parse as a cookie date, ignore + // the cookie-av. + + cookieAttributeList.expires = expiryTime + } else if (attributeNameLowercase === 'max-age') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.2 + // If the attribute-name case-insensitively matches the string "Max- + // Age", the user agent MUST process the cookie-av as follows. + + // 1. If the first character of the attribute-value is not a DIGIT or a + // "-" character, ignore the cookie-av. + const charCode = attributeValue.charCodeAt(0) + + if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') { + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } + + // 2. If the remainder of attribute-value contains a non-DIGIT + // character, ignore the cookie-av. + if (!/^\d+$/.test(attributeValue)) { + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } + + // 3. Let delta-seconds be the attribute-value converted to an integer. + const deltaSeconds = Number(attributeValue) + + // 4. Let cookie-age-limit be the maximum age of the cookie (which + // SHOULD be 400 days or less, see Section 4.1.2.2). + + // 5. Set delta-seconds to the smaller of its present value and cookie- + // age-limit. + // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs) + + // 6. If delta-seconds is less than or equal to zero (0), let expiry- + // time be the earliest representable date and time. Otherwise, let + // the expiry-time be the current date and time plus delta-seconds + // seconds. + // const expiryTime = deltaSeconds <= 0 ? Date.now() : Date.now() + deltaSeconds + + // 7. Append an attribute to the cookie-attribute-list with an + // attribute-name of Max-Age and an attribute-value of expiry-time. + cookieAttributeList.maxAge = deltaSeconds + } else if (attributeNameLowercase === 'domain') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.3 + // If the attribute-name case-insensitively matches the string "Domain", + // the user agent MUST process the cookie-av as follows. + + // 1. Let cookie-domain be the attribute-value. + let cookieDomain = attributeValue + + // 2. If cookie-domain starts with %x2E ("."), let cookie-domain be + // cookie-domain without its leading %x2E ("."). + if (cookieDomain[0] === '.') { + cookieDomain = cookieDomain.slice(1) + } + + // 3. Convert the cookie-domain to lower case. + cookieDomain = cookieDomain.toLowerCase() + + // 4. Append an attribute to the cookie-attribute-list with an + // attribute-name of Domain and an attribute-value of cookie-domain. + cookieAttributeList.domain = cookieDomain + } else if (attributeNameLowercase === 'path') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.4 + // If the attribute-name case-insensitively matches the string "Path", + // the user agent MUST process the cookie-av as follows. + + // 1. If the attribute-value is empty or if the first character of the + // attribute-value is not %x2F ("/"): + let cookiePath = '' + if (attributeValue.length === 0 || attributeValue[0] !== '/') { + // 1. Let cookie-path be the default-path. + cookiePath = '/' + } else { + // Otherwise: + + // 1. Let cookie-path be the attribute-value. + cookiePath = attributeValue + } + + // 2. Append an attribute to the cookie-attribute-list with an + // attribute-name of Path and an attribute-value of cookie-path. + cookieAttributeList.path = cookiePath + } else if (attributeNameLowercase === 'secure') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.5 + // If the attribute-name case-insensitively matches the string "Secure", + // the user agent MUST append an attribute to the cookie-attribute-list + // with an attribute-name of Secure and an empty attribute-value. + + cookieAttributeList.secure = true + } else if (attributeNameLowercase === 'httponly') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.6 + // If the attribute-name case-insensitively matches the string + // "HttpOnly", the user agent MUST append an attribute to the cookie- + // attribute-list with an attribute-name of HttpOnly and an empty + // attribute-value. + + cookieAttributeList.httpOnly = true + } else if (attributeNameLowercase === 'samesite') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.7 + // If the attribute-name case-insensitively matches the string + // "SameSite", the user agent MUST process the cookie-av as follows: + + // 1. Let enforcement be "Default". + let enforcement = 'Default' + + const attributeValueLowercase = attributeValue.toLowerCase() + // 2. If cookie-av's attribute-value is a case-insensitive match for + // "None", set enforcement to "None". + if (attributeValueLowercase.includes('none')) { + enforcement = 'None' + } + + // 3. If cookie-av's attribute-value is a case-insensitive match for + // "Strict", set enforcement to "Strict". + if (attributeValueLowercase.includes('strict')) { + enforcement = 'Strict' + } + + // 4. If cookie-av's attribute-value is a case-insensitive match for + // "Lax", set enforcement to "Lax". + if (attributeValueLowercase.includes('lax')) { + enforcement = 'Lax' + } + + // 5. Append an attribute to the cookie-attribute-list with an + // attribute-name of "SameSite" and an attribute-value of + // enforcement. + cookieAttributeList.sameSite = enforcement + } else { + cookieAttributeList.unparsed ??= [] + + cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`) + } + + // 8. Return to Step 1 of this algorithm. + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) +} + +module.exports = { + parseSetCookie, + parseUnparsedAttributes +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/cookies/util.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/cookies/util.js new file mode 100644 index 0000000000000000000000000000000000000000..254f5419e905bbdbb8e1706bf87860d8157717d1 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/cookies/util.js @@ -0,0 +1,282 @@ +'use strict' + +/** + * @param {string} value + * @returns {boolean} + */ +function isCTLExcludingHtab (value) { + for (let i = 0; i < value.length; ++i) { + const code = value.charCodeAt(i) + + if ( + (code >= 0x00 && code <= 0x08) || + (code >= 0x0A && code <= 0x1F) || + code === 0x7F + ) { + return true + } + } + return false +} + +/** + CHAR = + token = 1* + separators = "(" | ")" | "<" | ">" | "@" + | "," | ";" | ":" | "\" | <"> + | "/" | "[" | "]" | "?" | "=" + | "{" | "}" | SP | HT + * @param {string} name + */ +function validateCookieName (name) { + for (let i = 0; i < name.length; ++i) { + const code = name.charCodeAt(i) + + if ( + code < 0x21 || // exclude CTLs (0-31), SP and HT + code > 0x7E || // exclude non-ascii and DEL + code === 0x22 || // " + code === 0x28 || // ( + code === 0x29 || // ) + code === 0x3C || // < + code === 0x3E || // > + code === 0x40 || // @ + code === 0x2C || // , + code === 0x3B || // ; + code === 0x3A || // : + code === 0x5C || // \ + code === 0x2F || // / + code === 0x5B || // [ + code === 0x5D || // ] + code === 0x3F || // ? + code === 0x3D || // = + code === 0x7B || // { + code === 0x7D // } + ) { + throw new Error('Invalid cookie name') + } + } +} + +/** + cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE ) + cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E + ; US-ASCII characters excluding CTLs, + ; whitespace DQUOTE, comma, semicolon, + ; and backslash + * @param {string} value + */ +function validateCookieValue (value) { + let len = value.length + let i = 0 + + // if the value is wrapped in DQUOTE + if (value[0] === '"') { + if (len === 1 || value[len - 1] !== '"') { + throw new Error('Invalid cookie value') + } + --len + ++i + } + + while (i < len) { + const code = value.charCodeAt(i++) + + if ( + code < 0x21 || // exclude CTLs (0-31) + code > 0x7E || // non-ascii and DEL (127) + code === 0x22 || // " + code === 0x2C || // , + code === 0x3B || // ; + code === 0x5C // \ + ) { + throw new Error('Invalid cookie value') + } + } +} + +/** + * path-value = + * @param {string} path + */ +function validateCookiePath (path) { + for (let i = 0; i < path.length; ++i) { + const code = path.charCodeAt(i) + + if ( + code < 0x20 || // exclude CTLs (0-31) + code === 0x7F || // DEL + code === 0x3B // ; + ) { + throw new Error('Invalid cookie path') + } + } +} + +/** + * I have no idea why these values aren't allowed to be honest, + * but Deno tests these. - Khafra + * @param {string} domain + */ +function validateCookieDomain (domain) { + if ( + domain.startsWith('-') || + domain.endsWith('.') || + domain.endsWith('-') + ) { + throw new Error('Invalid cookie domain') + } +} + +const IMFDays = [ + 'Sun', 'Mon', 'Tue', 'Wed', + 'Thu', 'Fri', 'Sat' +] + +const IMFMonths = [ + 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', + 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' +] + +const IMFPaddedNumbers = Array(61).fill(0).map((_, i) => i.toString().padStart(2, '0')) + +/** + * @see https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1 + * @param {number|Date} date + IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT + ; fixed length/zone/capitalization subset of the format + ; see Section 3.3 of [RFC5322] + + day-name = %x4D.6F.6E ; "Mon", case-sensitive + / %x54.75.65 ; "Tue", case-sensitive + / %x57.65.64 ; "Wed", case-sensitive + / %x54.68.75 ; "Thu", case-sensitive + / %x46.72.69 ; "Fri", case-sensitive + / %x53.61.74 ; "Sat", case-sensitive + / %x53.75.6E ; "Sun", case-sensitive + date1 = day SP month SP year + ; e.g., 02 Jun 1982 + + day = 2DIGIT + month = %x4A.61.6E ; "Jan", case-sensitive + / %x46.65.62 ; "Feb", case-sensitive + / %x4D.61.72 ; "Mar", case-sensitive + / %x41.70.72 ; "Apr", case-sensitive + / %x4D.61.79 ; "May", case-sensitive + / %x4A.75.6E ; "Jun", case-sensitive + / %x4A.75.6C ; "Jul", case-sensitive + / %x41.75.67 ; "Aug", case-sensitive + / %x53.65.70 ; "Sep", case-sensitive + / %x4F.63.74 ; "Oct", case-sensitive + / %x4E.6F.76 ; "Nov", case-sensitive + / %x44.65.63 ; "Dec", case-sensitive + year = 4DIGIT + + GMT = %x47.4D.54 ; "GMT", case-sensitive + + time-of-day = hour ":" minute ":" second + ; 00:00:00 - 23:59:60 (leap second) + + hour = 2DIGIT + minute = 2DIGIT + second = 2DIGIT + */ +function toIMFDate (date) { + if (typeof date === 'number') { + date = new Date(date) + } + + return `${IMFDays[date.getUTCDay()]}, ${IMFPaddedNumbers[date.getUTCDate()]} ${IMFMonths[date.getUTCMonth()]} ${date.getUTCFullYear()} ${IMFPaddedNumbers[date.getUTCHours()]}:${IMFPaddedNumbers[date.getUTCMinutes()]}:${IMFPaddedNumbers[date.getUTCSeconds()]} GMT` +} + +/** + max-age-av = "Max-Age=" non-zero-digit *DIGIT + ; In practice, both expires-av and max-age-av + ; are limited to dates representable by the + ; user agent. + * @param {number} maxAge + */ +function validateCookieMaxAge (maxAge) { + if (maxAge < 0) { + throw new Error('Invalid cookie max-age') + } +} + +/** + * @see https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1 + * @param {import('./index').Cookie} cookie + */ +function stringify (cookie) { + if (cookie.name.length === 0) { + return null + } + + validateCookieName(cookie.name) + validateCookieValue(cookie.value) + + const out = [`${cookie.name}=${cookie.value}`] + + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.1 + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.2 + if (cookie.name.startsWith('__Secure-')) { + cookie.secure = true + } + + if (cookie.name.startsWith('__Host-')) { + cookie.secure = true + cookie.domain = null + cookie.path = '/' + } + + if (cookie.secure) { + out.push('Secure') + } + + if (cookie.httpOnly) { + out.push('HttpOnly') + } + + if (typeof cookie.maxAge === 'number') { + validateCookieMaxAge(cookie.maxAge) + out.push(`Max-Age=${cookie.maxAge}`) + } + + if (cookie.domain) { + validateCookieDomain(cookie.domain) + out.push(`Domain=${cookie.domain}`) + } + + if (cookie.path) { + validateCookiePath(cookie.path) + out.push(`Path=${cookie.path}`) + } + + if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') { + out.push(`Expires=${toIMFDate(cookie.expires)}`) + } + + if (cookie.sameSite) { + out.push(`SameSite=${cookie.sameSite}`) + } + + for (const part of cookie.unparsed) { + if (!part.includes('=')) { + throw new Error('Invalid unparsed') + } + + const [key, ...value] = part.split('=') + + out.push(`${key.trim()}=${value.join('=')}`) + } + + return out.join('; ') +} + +module.exports = { + isCTLExcludingHtab, + validateCookieName, + validateCookiePath, + validateCookieValue, + toIMFDate, + stringify +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/eventsource/eventsource-stream.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/eventsource/eventsource-stream.js new file mode 100644 index 0000000000000000000000000000000000000000..59cf7468800bcaef04434eccccda552fb6ac38e5 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/eventsource/eventsource-stream.js @@ -0,0 +1,399 @@ +'use strict' +const { Transform } = require('node:stream') +const { isASCIINumber, isValidLastEventId } = require('./util') + +/** + * @type {number[]} BOM + */ +const BOM = [0xEF, 0xBB, 0xBF] +/** + * @type {10} LF + */ +const LF = 0x0A +/** + * @type {13} CR + */ +const CR = 0x0D +/** + * @type {58} COLON + */ +const COLON = 0x3A +/** + * @type {32} SPACE + */ +const SPACE = 0x20 + +/** + * @typedef {object} EventSourceStreamEvent + * @type {object} + * @property {string} [event] The event type. + * @property {string} [data] The data of the message. + * @property {string} [id] A unique ID for the event. + * @property {string} [retry] The reconnection time, in milliseconds. + */ + +/** + * @typedef eventSourceSettings + * @type {object} + * @property {string} [lastEventId] The last event ID received from the server. + * @property {string} [origin] The origin of the event source. + * @property {number} [reconnectionTime] The reconnection time, in milliseconds. + */ + +class EventSourceStream extends Transform { + /** + * @type {eventSourceSettings} + */ + state + + /** + * Leading byte-order-mark check. + * @type {boolean} + */ + checkBOM = true + + /** + * @type {boolean} + */ + crlfCheck = false + + /** + * @type {boolean} + */ + eventEndCheck = false + + /** + * @type {Buffer|null} + */ + buffer = null + + pos = 0 + + event = { + data: undefined, + event: undefined, + id: undefined, + retry: undefined + } + + /** + * @param {object} options + * @param {boolean} [options.readableObjectMode] + * @param {eventSourceSettings} [options.eventSourceSettings] + * @param {(chunk: any, encoding?: BufferEncoding | undefined) => boolean} [options.push] + */ + constructor (options = {}) { + // Enable object mode as EventSourceStream emits objects of shape + // EventSourceStreamEvent + options.readableObjectMode = true + + super(options) + + this.state = options.eventSourceSettings || {} + if (options.push) { + this.push = options.push + } + } + + /** + * @param {Buffer} chunk + * @param {string} _encoding + * @param {Function} callback + * @returns {void} + */ + _transform (chunk, _encoding, callback) { + if (chunk.length === 0) { + callback() + return + } + + // Cache the chunk in the buffer, as the data might not be complete while + // processing it + // TODO: Investigate if there is a more performant way to handle + // incoming chunks + // see: https://github.com/nodejs/undici/issues/2630 + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]) + } else { + this.buffer = chunk + } + + // Strip leading byte-order-mark if we opened the stream and started + // the processing of the incoming data + if (this.checkBOM) { + switch (this.buffer.length) { + case 1: + // Check if the first byte is the same as the first byte of the BOM + if (this.buffer[0] === BOM[0]) { + // If it is, we need to wait for more data + callback() + return + } + // Set the checkBOM flag to false as we don't need to check for the + // BOM anymore + this.checkBOM = false + + // The buffer only contains one byte so we need to wait for more data + callback() + return + case 2: + // Check if the first two bytes are the same as the first two bytes + // of the BOM + if ( + this.buffer[0] === BOM[0] && + this.buffer[1] === BOM[1] + ) { + // If it is, we need to wait for more data, because the third byte + // is needed to determine if it is the BOM or not + callback() + return + } + + // Set the checkBOM flag to false as we don't need to check for the + // BOM anymore + this.checkBOM = false + break + case 3: + // Check if the first three bytes are the same as the first three + // bytes of the BOM + if ( + this.buffer[0] === BOM[0] && + this.buffer[1] === BOM[1] && + this.buffer[2] === BOM[2] + ) { + // If it is, we can drop the buffered data, as it is only the BOM + this.buffer = Buffer.alloc(0) + // Set the checkBOM flag to false as we don't need to check for the + // BOM anymore + this.checkBOM = false + + // Await more data + callback() + return + } + // If it is not the BOM, we can start processing the data + this.checkBOM = false + break + default: + // The buffer is longer than 3 bytes, so we can drop the BOM if it is + // present + if ( + this.buffer[0] === BOM[0] && + this.buffer[1] === BOM[1] && + this.buffer[2] === BOM[2] + ) { + // Remove the BOM from the buffer + this.buffer = this.buffer.subarray(3) + } + + // Set the checkBOM flag to false as we don't need to check for the + this.checkBOM = false + break + } + } + + while (this.pos < this.buffer.length) { + // If the previous line ended with an end-of-line, we need to check + // if the next character is also an end-of-line. + if (this.eventEndCheck) { + // If the the current character is an end-of-line, then the event + // is finished and we can process it + + // If the previous line ended with a carriage return, we need to + // check if the current character is a line feed and remove it + // from the buffer. + if (this.crlfCheck) { + // If the current character is a line feed, we can remove it + // from the buffer and reset the crlfCheck flag + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1) + this.pos = 0 + this.crlfCheck = false + + // It is possible that the line feed is not the end of the + // event. We need to check if the next character is an + // end-of-line character to determine if the event is + // finished. We simply continue the loop to check the next + // character. + + // As we removed the line feed from the buffer and set the + // crlfCheck flag to false, we basically don't make any + // distinction between a line feed and a carriage return. + continue + } + this.crlfCheck = false + } + + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + // If the current character is a carriage return, we need to + // set the crlfCheck flag to true, as we need to check if the + // next character is a line feed so we can remove it from the + // buffer + if (this.buffer[this.pos] === CR) { + this.crlfCheck = true + } + + this.buffer = this.buffer.subarray(this.pos + 1) + this.pos = 0 + if ( + this.event.data !== undefined || this.event.event || this.event.id || this.event.retry) { + this.processEvent(this.event) + } + this.clearEvent() + continue + } + // If the current character is not an end-of-line, then the event + // is not finished and we have to reset the eventEndCheck flag + this.eventEndCheck = false + continue + } + + // If the current character is an end-of-line, we can process the + // line + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + // If the current character is a carriage return, we need to + // set the crlfCheck flag to true, as we need to check if the + // next character is a line feed + if (this.buffer[this.pos] === CR) { + this.crlfCheck = true + } + + // In any case, we can process the line as we reached an + // end-of-line character + this.parseLine(this.buffer.subarray(0, this.pos), this.event) + + // Remove the processed line from the buffer + this.buffer = this.buffer.subarray(this.pos + 1) + // Reset the position as we removed the processed line from the buffer + this.pos = 0 + // A line was processed and this could be the end of the event. We need + // to check if the next line is empty to determine if the event is + // finished. + this.eventEndCheck = true + continue + } + + this.pos++ + } + + callback() + } + + /** + * @param {Buffer} line + * @param {EventSourceStreamEvent} event + */ + parseLine (line, event) { + // If the line is empty (a blank line) + // Dispatch the event, as defined below. + // This will be handled in the _transform method + if (line.length === 0) { + return + } + + // If the line starts with a U+003A COLON character (:) + // Ignore the line. + const colonPosition = line.indexOf(COLON) + if (colonPosition === 0) { + return + } + + let field = '' + let value = '' + + // If the line contains a U+003A COLON character (:) + if (colonPosition !== -1) { + // Collect the characters on the line before the first U+003A COLON + // character (:), and let field be that string. + // TODO: Investigate if there is a more performant way to extract the + // field + // see: https://github.com/nodejs/undici/issues/2630 + field = line.subarray(0, colonPosition).toString('utf8') + + // Collect the characters on the line after the first U+003A COLON + // character (:), and let value be that string. + // If value starts with a U+0020 SPACE character, remove it from value. + let valueStart = colonPosition + 1 + if (line[valueStart] === SPACE) { + ++valueStart + } + // TODO: Investigate if there is a more performant way to extract the + // value + // see: https://github.com/nodejs/undici/issues/2630 + value = line.subarray(valueStart).toString('utf8') + + // Otherwise, the string is not empty but does not contain a U+003A COLON + // character (:) + } else { + // Process the field using the steps described below, using the whole + // line as the field name, and the empty string as the field value. + field = line.toString('utf8') + value = '' + } + + // Modify the event with the field name and value. The value is also + // decoded as UTF-8 + switch (field) { + case 'data': + if (event[field] === undefined) { + event[field] = value + } else { + event[field] += `\n${value}` + } + break + case 'retry': + if (isASCIINumber(value)) { + event[field] = value + } + break + case 'id': + if (isValidLastEventId(value)) { + event[field] = value + } + break + case 'event': + if (value.length > 0) { + event[field] = value + } + break + } + } + + /** + * @param {EventSourceStreamEvent} event + */ + processEvent (event) { + if (event.retry && isASCIINumber(event.retry)) { + this.state.reconnectionTime = parseInt(event.retry, 10) + } + + if (event.id && isValidLastEventId(event.id)) { + this.state.lastEventId = event.id + } + + // only dispatch event, when data is provided + if (event.data !== undefined) { + this.push({ + type: event.event || 'message', + options: { + data: event.data, + lastEventId: this.state.lastEventId, + origin: this.state.origin + } + }) + } + } + + clearEvent () { + this.event = { + data: undefined, + event: undefined, + id: undefined, + retry: undefined + } + } +} + +module.exports = { + EventSourceStream +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/eventsource/eventsource.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/eventsource/eventsource.js new file mode 100644 index 0000000000000000000000000000000000000000..1ff4e36ca2a071969323f11f2dda38b30d59729a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/eventsource/eventsource.js @@ -0,0 +1,496 @@ +'use strict' + +const { pipeline } = require('node:stream') +const { fetching } = require('../fetch') +const { makeRequest } = require('../fetch/request') +const { webidl } = require('../webidl') +const { EventSourceStream } = require('./eventsource-stream') +const { parseMIMEType } = require('../fetch/data-url') +const { createFastMessageEvent } = require('../websocket/events') +const { isNetworkError } = require('../fetch/response') +const { delay } = require('./util') +const { kEnumerableProperty } = require('../../core/util') +const { environmentSettingsObject } = require('../fetch/util') + +let experimentalWarned = false + +/** + * A reconnection time, in milliseconds. This must initially be an implementation-defined value, + * probably in the region of a few seconds. + * + * In Comparison: + * - Chrome uses 3000ms. + * - Deno uses 5000ms. + * + * @type {3000} + */ +const defaultReconnectionTime = 3000 + +/** + * The readyState attribute represents the state of the connection. + * @typedef ReadyState + * @type {0|1|2} + * @readonly + * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource-readystate-dev + */ + +/** + * The connection has not yet been established, or it was closed and the user + * agent is reconnecting. + * @type {0} + */ +const CONNECTING = 0 + +/** + * The user agent has an open connection and is dispatching events as it + * receives them. + * @type {1} + */ +const OPEN = 1 + +/** + * The connection is not open, and the user agent is not trying to reconnect. + * @type {2} + */ +const CLOSED = 2 + +/** + * Requests for the element will have their mode set to "cors" and their credentials mode set to "same-origin". + * @type {'anonymous'} + */ +const ANONYMOUS = 'anonymous' + +/** + * Requests for the element will have their mode set to "cors" and their credentials mode set to "include". + * @type {'use-credentials'} + */ +const USE_CREDENTIALS = 'use-credentials' + +/** + * The EventSource interface is used to receive server-sent events. It + * connects to a server over HTTP and receives events in text/event-stream + * format without closing the connection. + * @extends {EventTarget} + * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events + * @api public + */ +class EventSource extends EventTarget { + #events = { + open: null, + error: null, + message: null + } + + #url + #withCredentials = false + + /** + * @type {ReadyState} + */ + #readyState = CONNECTING + + #request = null + #controller = null + + #dispatcher + + /** + * @type {import('./eventsource-stream').eventSourceSettings} + */ + #state + + /** + * Creates a new EventSource object. + * @param {string} url + * @param {EventSourceInit} [eventSourceInitDict={}] + * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#the-eventsource-interface + */ + constructor (url, eventSourceInitDict = {}) { + // 1. Let ev be a new EventSource object. + super() + + webidl.util.markAsUncloneable(this) + + const prefix = 'EventSource constructor' + webidl.argumentLengthCheck(arguments, 1, prefix) + + if (!experimentalWarned) { + experimentalWarned = true + process.emitWarning('EventSource is experimental, expect them to change at any time.', { + code: 'UNDICI-ES' + }) + } + + url = webidl.converters.USVString(url) + eventSourceInitDict = webidl.converters.EventSourceInitDict(eventSourceInitDict, prefix, 'eventSourceInitDict') + + this.#dispatcher = eventSourceInitDict.node.dispatcher || eventSourceInitDict.dispatcher + this.#state = { + lastEventId: '', + reconnectionTime: eventSourceInitDict.node.reconnectionTime + } + + // 2. Let settings be ev's relevant settings object. + // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object + const settings = environmentSettingsObject + + let urlRecord + + try { + // 3. Let urlRecord be the result of encoding-parsing a URL given url, relative to settings. + urlRecord = new URL(url, settings.settingsObject.baseUrl) + this.#state.origin = urlRecord.origin + } catch (e) { + // 4. If urlRecord is failure, then throw a "SyntaxError" DOMException. + throw new DOMException(e, 'SyntaxError') + } + + // 5. Set ev's url to urlRecord. + this.#url = urlRecord.href + + // 6. Let corsAttributeState be Anonymous. + let corsAttributeState = ANONYMOUS + + // 7. If the value of eventSourceInitDict's withCredentials member is true, + // then set corsAttributeState to Use Credentials and set ev's + // withCredentials attribute to true. + if (eventSourceInitDict.withCredentials === true) { + corsAttributeState = USE_CREDENTIALS + this.#withCredentials = true + } + + // 8. Let request be the result of creating a potential-CORS request given + // urlRecord, the empty string, and corsAttributeState. + const initRequest = { + redirect: 'follow', + keepalive: true, + // @see https://html.spec.whatwg.org/multipage/urls-and-fetching.html#cors-settings-attributes + mode: 'cors', + credentials: corsAttributeState === 'anonymous' + ? 'same-origin' + : 'omit', + referrer: 'no-referrer' + } + + // 9. Set request's client to settings. + initRequest.client = environmentSettingsObject.settingsObject + + // 10. User agents may set (`Accept`, `text/event-stream`) in request's header list. + initRequest.headersList = [['accept', { name: 'accept', value: 'text/event-stream' }]] + + // 11. Set request's cache mode to "no-store". + initRequest.cache = 'no-store' + + // 12. Set request's initiator type to "other". + initRequest.initiator = 'other' + + initRequest.urlList = [new URL(this.#url)] + + // 13. Set ev's request to request. + this.#request = makeRequest(initRequest) + + this.#connect() + } + + /** + * Returns the state of this EventSource object's connection. It can have the + * values described below. + * @returns {ReadyState} + * @readonly + */ + get readyState () { + return this.#readyState + } + + /** + * Returns the URL providing the event stream. + * @readonly + * @returns {string} + */ + get url () { + return this.#url + } + + /** + * Returns a boolean indicating whether the EventSource object was + * instantiated with CORS credentials set (true), or not (false, the default). + */ + get withCredentials () { + return this.#withCredentials + } + + #connect () { + if (this.#readyState === CLOSED) return + + this.#readyState = CONNECTING + + const fetchParams = { + request: this.#request, + dispatcher: this.#dispatcher + } + + // 14. Let processEventSourceEndOfBody given response res be the following step: if res is not a network error, then reestablish the connection. + const processEventSourceEndOfBody = (response) => { + if (!isNetworkError(response)) { + return this.#reconnect() + } + } + + // 15. Fetch request, with processResponseEndOfBody set to processEventSourceEndOfBody... + fetchParams.processResponseEndOfBody = processEventSourceEndOfBody + + // and processResponse set to the following steps given response res: + fetchParams.processResponse = (response) => { + // 1. If res is an aborted network error, then fail the connection. + + if (isNetworkError(response)) { + // 1. When a user agent is to fail the connection, the user agent + // must queue a task which, if the readyState attribute is set to a + // value other than CLOSED, sets the readyState attribute to CLOSED + // and fires an event named error at the EventSource object. Once the + // user agent has failed the connection, it does not attempt to + // reconnect. + if (response.aborted) { + this.close() + this.dispatchEvent(new Event('error')) + return + // 2. Otherwise, if res is a network error, then reestablish the + // connection, unless the user agent knows that to be futile, in + // which case the user agent may fail the connection. + } else { + this.#reconnect() + return + } + } + + // 3. Otherwise, if res's status is not 200, or if res's `Content-Type` + // is not `text/event-stream`, then fail the connection. + const contentType = response.headersList.get('content-type', true) + const mimeType = contentType !== null ? parseMIMEType(contentType) : 'failure' + const contentTypeValid = mimeType !== 'failure' && mimeType.essence === 'text/event-stream' + if ( + response.status !== 200 || + contentTypeValid === false + ) { + this.close() + this.dispatchEvent(new Event('error')) + return + } + + // 4. Otherwise, announce the connection and interpret res's body + // line by line. + + // When a user agent is to announce the connection, the user agent + // must queue a task which, if the readyState attribute is set to a + // value other than CLOSED, sets the readyState attribute to OPEN + // and fires an event named open at the EventSource object. + // @see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model + this.#readyState = OPEN + this.dispatchEvent(new Event('open')) + + // If redirected to a different origin, set the origin to the new origin. + this.#state.origin = response.urlList[response.urlList.length - 1].origin + + const eventSourceStream = new EventSourceStream({ + eventSourceSettings: this.#state, + push: (event) => { + this.dispatchEvent(createFastMessageEvent( + event.type, + event.options + )) + } + }) + + pipeline(response.body.stream, + eventSourceStream, + (error) => { + if ( + error?.aborted === false + ) { + this.close() + this.dispatchEvent(new Event('error')) + } + }) + } + + this.#controller = fetching(fetchParams) + } + + /** + * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model + * @returns {Promise} + */ + async #reconnect () { + // When a user agent is to reestablish the connection, the user agent must + // run the following steps. These steps are run in parallel, not as part of + // a task. (The tasks that it queues, of course, are run like normal tasks + // and not themselves in parallel.) + + // 1. Queue a task to run the following steps: + + // 1. If the readyState attribute is set to CLOSED, abort the task. + if (this.#readyState === CLOSED) return + + // 2. Set the readyState attribute to CONNECTING. + this.#readyState = CONNECTING + + // 3. Fire an event named error at the EventSource object. + this.dispatchEvent(new Event('error')) + + // 2. Wait a delay equal to the reconnection time of the event source. + await delay(this.#state.reconnectionTime) + + // 5. Queue a task to run the following steps: + + // 1. If the EventSource object's readyState attribute is not set to + // CONNECTING, then return. + if (this.#readyState !== CONNECTING) return + + // 2. Let request be the EventSource object's request. + // 3. If the EventSource object's last event ID string is not the empty + // string, then: + // 1. Let lastEventIDValue be the EventSource object's last event ID + // string, encoded as UTF-8. + // 2. Set (`Last-Event-ID`, lastEventIDValue) in request's header + // list. + if (this.#state.lastEventId.length) { + this.#request.headersList.set('last-event-id', this.#state.lastEventId, true) + } + + // 4. Fetch request and process the response obtained in this fashion, if any, as described earlier in this section. + this.#connect() + } + + /** + * Closes the connection, if any, and sets the readyState attribute to + * CLOSED. + */ + close () { + webidl.brandCheck(this, EventSource) + + if (this.#readyState === CLOSED) return + this.#readyState = CLOSED + this.#controller.abort() + this.#request = null + } + + get onopen () { + return this.#events.open + } + + set onopen (fn) { + if (this.#events.open) { + this.removeEventListener('open', this.#events.open) + } + + if (typeof fn === 'function') { + this.#events.open = fn + this.addEventListener('open', fn) + } else { + this.#events.open = null + } + } + + get onmessage () { + return this.#events.message + } + + set onmessage (fn) { + if (this.#events.message) { + this.removeEventListener('message', this.#events.message) + } + + if (typeof fn === 'function') { + this.#events.message = fn + this.addEventListener('message', fn) + } else { + this.#events.message = null + } + } + + get onerror () { + return this.#events.error + } + + set onerror (fn) { + if (this.#events.error) { + this.removeEventListener('error', this.#events.error) + } + + if (typeof fn === 'function') { + this.#events.error = fn + this.addEventListener('error', fn) + } else { + this.#events.error = null + } + } +} + +const constantsPropertyDescriptors = { + CONNECTING: { + __proto__: null, + configurable: false, + enumerable: true, + value: CONNECTING, + writable: false + }, + OPEN: { + __proto__: null, + configurable: false, + enumerable: true, + value: OPEN, + writable: false + }, + CLOSED: { + __proto__: null, + configurable: false, + enumerable: true, + value: CLOSED, + writable: false + } +} + +Object.defineProperties(EventSource, constantsPropertyDescriptors) +Object.defineProperties(EventSource.prototype, constantsPropertyDescriptors) + +Object.defineProperties(EventSource.prototype, { + close: kEnumerableProperty, + onerror: kEnumerableProperty, + onmessage: kEnumerableProperty, + onopen: kEnumerableProperty, + readyState: kEnumerableProperty, + url: kEnumerableProperty, + withCredentials: kEnumerableProperty +}) + +webidl.converters.EventSourceInitDict = webidl.dictionaryConverter([ + { + key: 'withCredentials', + converter: webidl.converters.boolean, + defaultValue: () => false + }, + { + key: 'dispatcher', // undici only + converter: webidl.converters.any + }, + { + key: 'node', // undici only + converter: webidl.dictionaryConverter([ + { + key: 'reconnectionTime', + converter: webidl.converters['unsigned long'], + defaultValue: () => defaultReconnectionTime + }, + { + key: 'dispatcher', + converter: webidl.converters.any + } + ]), + defaultValue: () => ({}) + } +]) + +module.exports = { + EventSource, + defaultReconnectionTime +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/eventsource/util.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/eventsource/util.js new file mode 100644 index 0000000000000000000000000000000000000000..ee0b4d36df03c0a1ee9138fac8b532c04f8805e0 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/eventsource/util.js @@ -0,0 +1,37 @@ +'use strict' + +/** + * Checks if the given value is a valid LastEventId. + * @param {string} value + * @returns {boolean} + */ +function isValidLastEventId (value) { + // LastEventId should not contain U+0000 NULL + return value.indexOf('\u0000') === -1 +} + +/** + * Checks if the given value is a base 10 digit. + * @param {string} value + * @returns {boolean} + */ +function isASCIINumber (value) { + if (value.length === 0) return false + for (let i = 0; i < value.length; i++) { + if (value.charCodeAt(i) < 0x30 || value.charCodeAt(i) > 0x39) return false + } + return true +} + +// https://github.com/nodejs/undici/issues/2664 +function delay (ms) { + return new Promise((resolve) => { + setTimeout(resolve, ms) + }) +} + +module.exports = { + isValidLastEventId, + isASCIINumber, + delay +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/fetch/LICENSE b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/fetch/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..294350045bbb56c0a5dbbdd15981cfdd20719dd0 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/fetch/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Ethan Arrowood + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/fetch/body.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/fetch/body.js new file mode 100644 index 0000000000000000000000000000000000000000..73c4b2e317cfa17120d1e29aaa9c32f913f726f3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/fetch/body.js @@ -0,0 +1,543 @@ +'use strict' + +const util = require('../../core/util') +const { + ReadableStreamFrom, + readableStreamClose, + fullyReadBody, + extractMimeType, + utf8DecodeBytes +} = require('./util') +const { FormData, setFormDataState } = require('./formdata') +const { webidl } = require('../webidl') +const assert = require('node:assert') +const { isErrored, isDisturbed } = require('node:stream') +const { isArrayBuffer } = require('node:util/types') +const { serializeAMimeType } = require('./data-url') +const { multipartFormDataParser } = require('./formdata-parser') +const { createDeferredPromise } = require('../../util/promise') + +let random + +try { + const crypto = require('node:crypto') + random = (max) => crypto.randomInt(0, max) +} catch { + random = (max) => Math.floor(Math.random() * max) +} + +const textEncoder = new TextEncoder() +function noop () {} + +const streamRegistry = new FinalizationRegistry((weakRef) => { + const stream = weakRef.deref() + if (stream && !stream.locked && !isDisturbed(stream) && !isErrored(stream)) { + stream.cancel('Response object has been garbage collected').catch(noop) + } +}) + +/** + * Extract a body with type from a byte sequence or BodyInit object + * + * @param {import('../../../types').BodyInit} object - The BodyInit object to extract from + * @param {boolean} [keepalive=false] - If true, indicates that the body + * @returns {[{stream: ReadableStream, source: any, length: number | null}, string | null]} - Returns a tuple containing the body and its type + * + * @see https://fetch.spec.whatwg.org/#concept-bodyinit-extract + */ +function extractBody (object, keepalive = false) { + // 1. Let stream be null. + let stream = null + + // 2. If object is a ReadableStream object, then set stream to object. + if (webidl.is.ReadableStream(object)) { + stream = object + } else if (webidl.is.Blob(object)) { + // 3. Otherwise, if object is a Blob object, set stream to the + // result of running object’s get stream. + stream = object.stream() + } else { + // 4. Otherwise, set stream to a new ReadableStream object, and set + // up stream with byte reading support. + stream = new ReadableStream({ + async pull (controller) { + const buffer = typeof source === 'string' ? textEncoder.encode(source) : source + + if (buffer.byteLength) { + controller.enqueue(buffer) + } + + queueMicrotask(() => readableStreamClose(controller)) + }, + start () {}, + type: 'bytes' + }) + } + + // 5. Assert: stream is a ReadableStream object. + assert(webidl.is.ReadableStream(stream)) + + // 6. Let action be null. + let action = null + + // 7. Let source be null. + let source = null + + // 8. Let length be null. + let length = null + + // 9. Let type be null. + let type = null + + // 10. Switch on object: + if (typeof object === 'string') { + // Set source to the UTF-8 encoding of object. + // Note: setting source to a Uint8Array here breaks some mocking assumptions. + source = object + + // Set type to `text/plain;charset=UTF-8`. + type = 'text/plain;charset=UTF-8' + } else if (webidl.is.URLSearchParams(object)) { + // URLSearchParams + + // spec says to run application/x-www-form-urlencoded on body.list + // this is implemented in Node.js as apart of an URLSearchParams instance toString method + // See: https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L490 + // and https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L1100 + + // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list. + source = object.toString() + + // Set type to `application/x-www-form-urlencoded;charset=UTF-8`. + type = 'application/x-www-form-urlencoded;charset=UTF-8' + } else if (isArrayBuffer(object)) { + // BufferSource/ArrayBuffer + + // Set source to a copy of the bytes held by object. + source = new Uint8Array(object.slice()) + } else if (ArrayBuffer.isView(object)) { + // BufferSource/ArrayBufferView + + // Set source to a copy of the bytes held by object. + source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength)) + } else if (webidl.is.FormData(object)) { + const boundary = `----formdata-undici-0${`${random(1e11)}`.padStart(11, '0')}` + const prefix = `--${boundary}\r\nContent-Disposition: form-data` + + /*! formdata-polyfill. MIT License. Jimmy Wärting */ + const formdataEscape = (str) => + str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22') + const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, '\r\n') + + // Set action to this step: run the multipart/form-data + // encoding algorithm, with object’s entry list and UTF-8. + // - This ensures that the body is immutable and can't be changed afterwords + // - That the content-length is calculated in advance. + // - And that all parts are pre-encoded and ready to be sent. + + const blobParts = [] + const rn = new Uint8Array([13, 10]) // '\r\n' + length = 0 + let hasUnknownSizeValue = false + + for (const [name, value] of object) { + if (typeof value === 'string') { + const chunk = textEncoder.encode(prefix + + `; name="${formdataEscape(normalizeLinefeeds(name))}"` + + `\r\n\r\n${normalizeLinefeeds(value)}\r\n`) + blobParts.push(chunk) + length += chunk.byteLength + } else { + const chunk = textEncoder.encode(`${prefix}; name="${formdataEscape(normalizeLinefeeds(name))}"` + + (value.name ? `; filename="${formdataEscape(value.name)}"` : '') + '\r\n' + + `Content-Type: ${ + value.type || 'application/octet-stream' + }\r\n\r\n`) + blobParts.push(chunk, value, rn) + if (typeof value.size === 'number') { + length += chunk.byteLength + value.size + rn.byteLength + } else { + hasUnknownSizeValue = true + } + } + } + + // CRLF is appended to the body to function with legacy servers and match other implementations. + // https://github.com/curl/curl/blob/3434c6b46e682452973972e8313613dfa58cd690/lib/mime.c#L1029-L1030 + // https://github.com/form-data/form-data/issues/63 + const chunk = textEncoder.encode(`--${boundary}--\r\n`) + blobParts.push(chunk) + length += chunk.byteLength + if (hasUnknownSizeValue) { + length = null + } + + // Set source to object. + source = object + + action = async function * () { + for (const part of blobParts) { + if (part.stream) { + yield * part.stream() + } else { + yield part + } + } + } + + // Set type to `multipart/form-data; boundary=`, + // followed by the multipart/form-data boundary string generated + // by the multipart/form-data encoding algorithm. + type = `multipart/form-data; boundary=${boundary}` + } else if (webidl.is.Blob(object)) { + // Blob + + // Set source to object. + source = object + + // Set length to object’s size. + length = object.size + + // If object’s type attribute is not the empty byte sequence, set + // type to its value. + if (object.type) { + type = object.type + } + } else if (typeof object[Symbol.asyncIterator] === 'function') { + // If keepalive is true, then throw a TypeError. + if (keepalive) { + throw new TypeError('keepalive') + } + + // If object is disturbed or locked, then throw a TypeError. + if (util.isDisturbed(object) || object.locked) { + throw new TypeError( + 'Response body object should not be disturbed or locked' + ) + } + + stream = + webidl.is.ReadableStream(object) ? object : ReadableStreamFrom(object) + } + + // 11. If source is a byte sequence, then set action to a + // step that returns source and length to source’s length. + if (typeof source === 'string' || util.isBuffer(source)) { + length = Buffer.byteLength(source) + } + + // 12. If action is non-null, then run these steps in in parallel: + if (action != null) { + // Run action. + let iterator + stream = new ReadableStream({ + async start () { + iterator = action(object)[Symbol.asyncIterator]() + }, + async pull (controller) { + const { value, done } = await iterator.next() + if (done) { + // When running action is done, close stream. + queueMicrotask(() => { + controller.close() + controller.byobRequest?.respond(0) + }) + } else { + // Whenever one or more bytes are available and stream is not errored, + // enqueue a Uint8Array wrapping an ArrayBuffer containing the available + // bytes into stream. + if (!isErrored(stream)) { + const buffer = new Uint8Array(value) + if (buffer.byteLength) { + controller.enqueue(buffer) + } + } + } + return controller.desiredSize > 0 + }, + async cancel (reason) { + await iterator.return() + }, + type: 'bytes' + }) + } + + // 13. Let body be a body whose stream is stream, source is source, + // and length is length. + const body = { stream, source, length } + + // 14. Return (body, type). + return [body, type] +} + +/** + * @typedef {object} ExtractBodyResult + * @property {ReadableStream>} stream - The ReadableStream containing the body data + * @property {any} source - The original source of the body data + * @property {number | null} length - The length of the body data, or null + */ + +/** + * Safely extract a body with type from a byte sequence or BodyInit object. + * + * @param {import('../../../types').BodyInit} object - The BodyInit object to extract from + * @param {boolean} [keepalive=false] - If true, indicates that the body + * @returns {[ExtractBodyResult, string | null]} - Returns a tuple containing the body and its type + * + * @see https://fetch.spec.whatwg.org/#bodyinit-safely-extract + */ +function safelyExtractBody (object, keepalive = false) { + // To safely extract a body and a `Content-Type` value from + // a byte sequence or BodyInit object object, run these steps: + + // 1. If object is a ReadableStream object, then: + if (webidl.is.ReadableStream(object)) { + // Assert: object is neither disturbed nor locked. + assert(!util.isDisturbed(object), 'The body has already been consumed.') + assert(!object.locked, 'The stream is locked.') + } + + // 2. Return the results of extracting object. + return extractBody(object, keepalive) +} + +function cloneBody (body) { + // To clone a body body, run these steps: + + // https://fetch.spec.whatwg.org/#concept-body-clone + + // 1. Let « out1, out2 » be the result of teeing body’s stream. + const { 0: out1, 1: out2 } = body.stream.tee() + + // 2. Set body’s stream to out1. + body.stream = out1 + + // 3. Return a body whose stream is out2 and other members are copied from body. + return { + stream: out2, + length: body.length, + source: body.source + } +} + +function throwIfAborted (state) { + if (state.aborted) { + throw new DOMException('The operation was aborted.', 'AbortError') + } +} + +function bodyMixinMethods (instance, getInternalState) { + const methods = { + blob () { + // The blob() method steps are to return the result of + // running consume body with this and the following step + // given a byte sequence bytes: return a Blob whose + // contents are bytes and whose type attribute is this’s + // MIME type. + return consumeBody(this, (bytes) => { + let mimeType = bodyMimeType(getInternalState(this)) + + if (mimeType === null) { + mimeType = '' + } else if (mimeType) { + mimeType = serializeAMimeType(mimeType) + } + + // Return a Blob whose contents are bytes and type attribute + // is mimeType. + return new Blob([bytes], { type: mimeType }) + }, instance, getInternalState) + }, + + arrayBuffer () { + // The arrayBuffer() method steps are to return the result + // of running consume body with this and the following step + // given a byte sequence bytes: return a new ArrayBuffer + // whose contents are bytes. + return consumeBody(this, (bytes) => { + return new Uint8Array(bytes).buffer + }, instance, getInternalState) + }, + + text () { + // The text() method steps are to return the result of running + // consume body with this and UTF-8 decode. + return consumeBody(this, utf8DecodeBytes, instance, getInternalState) + }, + + json () { + // The json() method steps are to return the result of running + // consume body with this and parse JSON from bytes. + return consumeBody(this, parseJSONFromBytes, instance, getInternalState) + }, + + formData () { + // The formData() method steps are to return the result of running + // consume body with this and the following step given a byte sequence bytes: + return consumeBody(this, (value) => { + // 1. Let mimeType be the result of get the MIME type with this. + const mimeType = bodyMimeType(getInternalState(this)) + + // 2. If mimeType is non-null, then switch on mimeType’s essence and run + // the corresponding steps: + if (mimeType !== null) { + switch (mimeType.essence) { + case 'multipart/form-data': { + // 1. ... [long step] + // 2. If that fails for some reason, then throw a TypeError. + const parsed = multipartFormDataParser(value, mimeType) + + // 3. Return a new FormData object, appending each entry, + // resulting from the parsing operation, to its entry list. + const fd = new FormData() + setFormDataState(fd, parsed) + + return fd + } + case 'application/x-www-form-urlencoded': { + // 1. Let entries be the result of parsing bytes. + const entries = new URLSearchParams(value.toString()) + + // 2. If entries is failure, then throw a TypeError. + + // 3. Return a new FormData object whose entry list is entries. + const fd = new FormData() + + for (const [name, value] of entries) { + fd.append(name, value) + } + + return fd + } + } + } + + // 3. Throw a TypeError. + throw new TypeError( + 'Content-Type was not one of "multipart/form-data" or "application/x-www-form-urlencoded".' + ) + }, instance, getInternalState) + }, + + bytes () { + // The bytes() method steps are to return the result of running consume body + // with this and the following step given a byte sequence bytes: return the + // result of creating a Uint8Array from bytes in this’s relevant realm. + return consumeBody(this, (bytes) => { + return new Uint8Array(bytes) + }, instance, getInternalState) + } + } + + return methods +} + +function mixinBody (prototype, getInternalState) { + Object.assign(prototype.prototype, bodyMixinMethods(prototype, getInternalState)) +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-body-consume-body + * @param {any} object internal state + * @param {(value: unknown) => unknown} convertBytesToJSValue + * @param {any} instance + * @param {(target: any) => any} getInternalState + */ +async function consumeBody (object, convertBytesToJSValue, instance, getInternalState) { + webidl.brandCheck(object, instance) + + const state = getInternalState(object) + + // 1. If object is unusable, then return a promise rejected + // with a TypeError. + if (bodyUnusable(state)) { + throw new TypeError('Body is unusable: Body has already been read') + } + + throwIfAborted(state) + + // 2. Let promise be a new promise. + const promise = createDeferredPromise() + + // 3. Let errorSteps given error be to reject promise with error. + const errorSteps = (error) => promise.reject(error) + + // 4. Let successSteps given a byte sequence data be to resolve + // promise with the result of running convertBytesToJSValue + // with data. If that threw an exception, then run errorSteps + // with that exception. + const successSteps = (data) => { + try { + promise.resolve(convertBytesToJSValue(data)) + } catch (e) { + errorSteps(e) + } + } + + // 5. If object’s body is null, then run successSteps with an + // empty byte sequence. + if (state.body == null) { + successSteps(Buffer.allocUnsafe(0)) + return promise.promise + } + + // 6. Otherwise, fully read object’s body given successSteps, + // errorSteps, and object’s relevant global object. + fullyReadBody(state.body, successSteps, errorSteps) + + // 7. Return promise. + return promise.promise +} + +/** + * @see https://fetch.spec.whatwg.org/#body-unusable + * @param {any} object internal state + */ +function bodyUnusable (object) { + const body = object.body + + // An object including the Body interface mixin is + // said to be unusable if its body is non-null and + // its body’s stream is disturbed or locked. + return body != null && (body.stream.locked || util.isDisturbed(body.stream)) +} + +/** + * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value + * @param {Uint8Array} bytes + */ +function parseJSONFromBytes (bytes) { + return JSON.parse(utf8DecodeBytes(bytes)) +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-body-mime-type + * @param {any} requestOrResponse internal state + */ +function bodyMimeType (requestOrResponse) { + // 1. Let headers be null. + // 2. If requestOrResponse is a Request object, then set headers to requestOrResponse’s request’s header list. + // 3. Otherwise, set headers to requestOrResponse’s response’s header list. + /** @type {import('./headers').HeadersList} */ + const headers = requestOrResponse.headersList + + // 4. Let mimeType be the result of extracting a MIME type from headers. + const mimeType = extractMimeType(headers) + + // 5. If mimeType is failure, then return null. + if (mimeType === 'failure') { + return null + } + + // 6. Return mimeType. + return mimeType +} + +module.exports = { + extractBody, + safelyExtractBody, + cloneBody, + mixinBody, + streamRegistry, + bodyUnusable +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/fetch/constants.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/fetch/constants.js new file mode 100644 index 0000000000000000000000000000000000000000..ef63b0c8e106b5358824877ef6acf80fcdebedd6 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/fetch/constants.js @@ -0,0 +1,131 @@ +'use strict' + +const corsSafeListedMethods = /** @type {const} */ (['GET', 'HEAD', 'POST']) +const corsSafeListedMethodsSet = new Set(corsSafeListedMethods) + +const nullBodyStatus = /** @type {const} */ ([101, 204, 205, 304]) + +const redirectStatus = /** @type {const} */ ([301, 302, 303, 307, 308]) +const redirectStatusSet = new Set(redirectStatus) + +/** + * @see https://fetch.spec.whatwg.org/#block-bad-port + */ +const badPorts = /** @type {const} */ ([ + '1', '7', '9', '11', '13', '15', '17', '19', '20', '21', '22', '23', '25', '37', '42', '43', '53', '69', '77', '79', + '87', '95', '101', '102', '103', '104', '109', '110', '111', '113', '115', '117', '119', '123', '135', '137', + '139', '143', '161', '179', '389', '427', '465', '512', '513', '514', '515', '526', '530', '531', '532', + '540', '548', '554', '556', '563', '587', '601', '636', '989', '990', '993', '995', '1719', '1720', '1723', + '2049', '3659', '4045', '4190', '5060', '5061', '6000', '6566', '6665', '6666', '6667', '6668', '6669', '6679', + '6697', '10080' +]) +const badPortsSet = new Set(badPorts) + +/** + * @see https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-header + */ +const referrerPolicyTokens = /** @type {const} */ ([ + 'no-referrer', + 'no-referrer-when-downgrade', + 'same-origin', + 'origin', + 'strict-origin', + 'origin-when-cross-origin', + 'strict-origin-when-cross-origin', + 'unsafe-url' +]) + +/** + * @see https://w3c.github.io/webappsec-referrer-policy/#referrer-policies + */ +const referrerPolicy = /** @type {const} */ ([ + '', + ...referrerPolicyTokens +]) +const referrerPolicyTokensSet = new Set(referrerPolicyTokens) + +const requestRedirect = /** @type {const} */ (['follow', 'manual', 'error']) + +const safeMethods = /** @type {const} */ (['GET', 'HEAD', 'OPTIONS', 'TRACE']) +const safeMethodsSet = new Set(safeMethods) + +const requestMode = /** @type {const} */ (['navigate', 'same-origin', 'no-cors', 'cors']) + +const requestCredentials = /** @type {const} */ (['omit', 'same-origin', 'include']) + +const requestCache = /** @type {const} */ ([ + 'default', + 'no-store', + 'reload', + 'no-cache', + 'force-cache', + 'only-if-cached' +]) + +/** + * @see https://fetch.spec.whatwg.org/#request-body-header-name + */ +const requestBodyHeader = /** @type {const} */ ([ + 'content-encoding', + 'content-language', + 'content-location', + 'content-type', + // See https://github.com/nodejs/undici/issues/2021 + // 'Content-Length' is a forbidden header name, which is typically + // removed in the Headers implementation. However, undici doesn't + // filter out headers, so we add it here. + 'content-length' +]) + +/** + * @see https://fetch.spec.whatwg.org/#enumdef-requestduplex + */ +const requestDuplex = /** @type {const} */ ([ + 'half' +]) + +/** + * @see http://fetch.spec.whatwg.org/#forbidden-method + */ +const forbiddenMethods = /** @type {const} */ (['CONNECT', 'TRACE', 'TRACK']) +const forbiddenMethodsSet = new Set(forbiddenMethods) + +const subresource = /** @type {const} */ ([ + 'audio', + 'audioworklet', + 'font', + 'image', + 'manifest', + 'paintworklet', + 'script', + 'style', + 'track', + 'video', + 'xslt', + '' +]) +const subresourceSet = new Set(subresource) + +module.exports = { + subresource, + forbiddenMethods, + requestBodyHeader, + referrerPolicy, + requestRedirect, + requestMode, + requestCredentials, + requestCache, + redirectStatus, + corsSafeListedMethods, + nullBodyStatus, + safeMethods, + badPorts, + requestDuplex, + subresourceSet, + badPortsSet, + redirectStatusSet, + corsSafeListedMethodsSet, + safeMethodsSet, + forbiddenMethodsSet, + referrerPolicyTokens: referrerPolicyTokensSet +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/fetch/data-url.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/fetch/data-url.js new file mode 100644 index 0000000000000000000000000000000000000000..bc7a692a05a2b3de224708b0df7d3e7dc6b131ae --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/fetch/data-url.js @@ -0,0 +1,744 @@ +'use strict' + +const assert = require('node:assert') + +const encoder = new TextEncoder() + +/** + * @see https://mimesniff.spec.whatwg.org/#http-token-code-point + */ +const HTTP_TOKEN_CODEPOINTS = /^[!#$%&'*+\-.^_|~A-Za-z0-9]+$/ +const HTTP_WHITESPACE_REGEX = /[\u000A\u000D\u0009\u0020]/ // eslint-disable-line +const ASCII_WHITESPACE_REPLACE_REGEX = /[\u0009\u000A\u000C\u000D\u0020]/g // eslint-disable-line +/** + * @see https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point + */ +const HTTP_QUOTED_STRING_TOKENS = /^[\u0009\u0020-\u007E\u0080-\u00FF]+$/ // eslint-disable-line + +// https://fetch.spec.whatwg.org/#data-url-processor +/** @param {URL} dataURL */ +function dataURLProcessor (dataURL) { + // 1. Assert: dataURL’s scheme is "data". + assert(dataURL.protocol === 'data:') + + // 2. Let input be the result of running the URL + // serializer on dataURL with exclude fragment + // set to true. + let input = URLSerializer(dataURL, true) + + // 3. Remove the leading "data:" string from input. + input = input.slice(5) + + // 4. Let position point at the start of input. + const position = { position: 0 } + + // 5. Let mimeType be the result of collecting a + // sequence of code points that are not equal + // to U+002C (,), given position. + let mimeType = collectASequenceOfCodePointsFast( + ',', + input, + position + ) + + // 6. Strip leading and trailing ASCII whitespace + // from mimeType. + // Undici implementation note: we need to store the + // length because if the mimetype has spaces removed, + // the wrong amount will be sliced from the input in + // step #9 + const mimeTypeLength = mimeType.length + mimeType = removeASCIIWhitespace(mimeType, true, true) + + // 7. If position is past the end of input, then + // return failure + if (position.position >= input.length) { + return 'failure' + } + + // 8. Advance position by 1. + position.position++ + + // 9. Let encodedBody be the remainder of input. + const encodedBody = input.slice(mimeTypeLength + 1) + + // 10. Let body be the percent-decoding of encodedBody. + let body = stringPercentDecode(encodedBody) + + // 11. If mimeType ends with U+003B (;), followed by + // zero or more U+0020 SPACE, followed by an ASCII + // case-insensitive match for "base64", then: + if (/;(\u0020){0,}base64$/i.test(mimeType)) { + // 1. Let stringBody be the isomorphic decode of body. + const stringBody = isomorphicDecode(body) + + // 2. Set body to the forgiving-base64 decode of + // stringBody. + body = forgivingBase64(stringBody) + + // 3. If body is failure, then return failure. + if (body === 'failure') { + return 'failure' + } + + // 4. Remove the last 6 code points from mimeType. + mimeType = mimeType.slice(0, -6) + + // 5. Remove trailing U+0020 SPACE code points from mimeType, + // if any. + mimeType = mimeType.replace(/(\u0020)+$/, '') + + // 6. Remove the last U+003B (;) code point from mimeType. + mimeType = mimeType.slice(0, -1) + } + + // 12. If mimeType starts with U+003B (;), then prepend + // "text/plain" to mimeType. + if (mimeType.startsWith(';')) { + mimeType = 'text/plain' + mimeType + } + + // 13. Let mimeTypeRecord be the result of parsing + // mimeType. + let mimeTypeRecord = parseMIMEType(mimeType) + + // 14. If mimeTypeRecord is failure, then set + // mimeTypeRecord to text/plain;charset=US-ASCII. + if (mimeTypeRecord === 'failure') { + mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII') + } + + // 15. Return a new data: URL struct whose MIME + // type is mimeTypeRecord and body is body. + // https://fetch.spec.whatwg.org/#data-url-struct + return { mimeType: mimeTypeRecord, body } +} + +// https://url.spec.whatwg.org/#concept-url-serializer +/** + * @param {URL} url + * @param {boolean} excludeFragment + */ +function URLSerializer (url, excludeFragment = false) { + if (!excludeFragment) { + return url.href + } + + const href = url.href + const hashLength = url.hash.length + + const serialized = hashLength === 0 ? href : href.substring(0, href.length - hashLength) + + if (!hashLength && href.endsWith('#')) { + return serialized.slice(0, -1) + } + + return serialized +} + +// https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points +/** + * @param {(char: string) => boolean} condition + * @param {string} input + * @param {{ position: number }} position + */ +function collectASequenceOfCodePoints (condition, input, position) { + // 1. Let result be the empty string. + let result = '' + + // 2. While position doesn’t point past the end of input and the + // code point at position within input meets the condition condition: + while (position.position < input.length && condition(input[position.position])) { + // 1. Append that code point to the end of result. + result += input[position.position] + + // 2. Advance position by 1. + position.position++ + } + + // 3. Return result. + return result +} + +/** + * A faster collectASequenceOfCodePoints that only works when comparing a single character. + * @param {string} char + * @param {string} input + * @param {{ position: number }} position + */ +function collectASequenceOfCodePointsFast (char, input, position) { + const idx = input.indexOf(char, position.position) + const start = position.position + + if (idx === -1) { + position.position = input.length + return input.slice(start) + } + + position.position = idx + return input.slice(start, position.position) +} + +// https://url.spec.whatwg.org/#string-percent-decode +/** @param {string} input */ +function stringPercentDecode (input) { + // 1. Let bytes be the UTF-8 encoding of input. + const bytes = encoder.encode(input) + + // 2. Return the percent-decoding of bytes. + return percentDecode(bytes) +} + +/** + * @param {number} byte + */ +function isHexCharByte (byte) { + // 0-9 A-F a-f + return (byte >= 0x30 && byte <= 0x39) || (byte >= 0x41 && byte <= 0x46) || (byte >= 0x61 && byte <= 0x66) +} + +/** + * @param {number} byte + */ +function hexByteToNumber (byte) { + return ( + // 0-9 + byte >= 0x30 && byte <= 0x39 + ? (byte - 48) + // Convert to uppercase + // ((byte & 0xDF) - 65) + 10 + : ((byte & 0xDF) - 55) + ) +} + +// https://url.spec.whatwg.org/#percent-decode +/** @param {Uint8Array} input */ +function percentDecode (input) { + const length = input.length + // 1. Let output be an empty byte sequence. + /** @type {Uint8Array} */ + const output = new Uint8Array(length) + let j = 0 + // 2. For each byte byte in input: + for (let i = 0; i < length; ++i) { + const byte = input[i] + + // 1. If byte is not 0x25 (%), then append byte to output. + if (byte !== 0x25) { + output[j++] = byte + + // 2. Otherwise, if byte is 0x25 (%) and the next two bytes + // after byte in input are not in the ranges + // 0x30 (0) to 0x39 (9), 0x41 (A) to 0x46 (F), + // and 0x61 (a) to 0x66 (f), all inclusive, append byte + // to output. + } else if ( + byte === 0x25 && + !(isHexCharByte(input[i + 1]) && isHexCharByte(input[i + 2])) + ) { + output[j++] = 0x25 + + // 3. Otherwise: + } else { + // 1. Let bytePoint be the two bytes after byte in input, + // decoded, and then interpreted as hexadecimal number. + // 2. Append a byte whose value is bytePoint to output. + output[j++] = (hexByteToNumber(input[i + 1]) << 4) | hexByteToNumber(input[i + 2]) + + // 3. Skip the next two bytes in input. + i += 2 + } + } + + // 3. Return output. + return length === j ? output : output.subarray(0, j) +} + +// https://mimesniff.spec.whatwg.org/#parse-a-mime-type +/** @param {string} input */ +function parseMIMEType (input) { + // 1. Remove any leading and trailing HTTP whitespace + // from input. + input = removeHTTPWhitespace(input, true, true) + + // 2. Let position be a position variable for input, + // initially pointing at the start of input. + const position = { position: 0 } + + // 3. Let type be the result of collecting a sequence + // of code points that are not U+002F (/) from + // input, given position. + const type = collectASequenceOfCodePointsFast( + '/', + input, + position + ) + + // 4. If type is the empty string or does not solely + // contain HTTP token code points, then return failure. + // https://mimesniff.spec.whatwg.org/#http-token-code-point + if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) { + return 'failure' + } + + // 5. If position is past the end of input, then return + // failure + if (position.position >= input.length) { + return 'failure' + } + + // 6. Advance position by 1. (This skips past U+002F (/).) + position.position++ + + // 7. Let subtype be the result of collecting a sequence of + // code points that are not U+003B (;) from input, given + // position. + let subtype = collectASequenceOfCodePointsFast( + ';', + input, + position + ) + + // 8. Remove any trailing HTTP whitespace from subtype. + subtype = removeHTTPWhitespace(subtype, false, true) + + // 9. If subtype is the empty string or does not solely + // contain HTTP token code points, then return failure. + if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) { + return 'failure' + } + + const typeLowercase = type.toLowerCase() + const subtypeLowercase = subtype.toLowerCase() + + // 10. Let mimeType be a new MIME type record whose type + // is type, in ASCII lowercase, and subtype is subtype, + // in ASCII lowercase. + // https://mimesniff.spec.whatwg.org/#mime-type + const mimeType = { + type: typeLowercase, + subtype: subtypeLowercase, + /** @type {Map} */ + parameters: new Map(), + // https://mimesniff.spec.whatwg.org/#mime-type-essence + essence: `${typeLowercase}/${subtypeLowercase}` + } + + // 11. While position is not past the end of input: + while (position.position < input.length) { + // 1. Advance position by 1. (This skips past U+003B (;).) + position.position++ + + // 2. Collect a sequence of code points that are HTTP + // whitespace from input given position. + collectASequenceOfCodePoints( + // https://fetch.spec.whatwg.org/#http-whitespace + char => HTTP_WHITESPACE_REGEX.test(char), + input, + position + ) + + // 3. Let parameterName be the result of collecting a + // sequence of code points that are not U+003B (;) + // or U+003D (=) from input, given position. + let parameterName = collectASequenceOfCodePoints( + (char) => char !== ';' && char !== '=', + input, + position + ) + + // 4. Set parameterName to parameterName, in ASCII + // lowercase. + parameterName = parameterName.toLowerCase() + + // 5. If position is not past the end of input, then: + if (position.position < input.length) { + // 1. If the code point at position within input is + // U+003B (;), then continue. + if (input[position.position] === ';') { + continue + } + + // 2. Advance position by 1. (This skips past U+003D (=).) + position.position++ + } + + // 6. If position is past the end of input, then break. + if (position.position >= input.length) { + break + } + + // 7. Let parameterValue be null. + let parameterValue = null + + // 8. If the code point at position within input is + // U+0022 ("), then: + if (input[position.position] === '"') { + // 1. Set parameterValue to the result of collecting + // an HTTP quoted string from input, given position + // and the extract-value flag. + parameterValue = collectAnHTTPQuotedString(input, position, true) + + // 2. Collect a sequence of code points that are not + // U+003B (;) from input, given position. + collectASequenceOfCodePointsFast( + ';', + input, + position + ) + + // 9. Otherwise: + } else { + // 1. Set parameterValue to the result of collecting + // a sequence of code points that are not U+003B (;) + // from input, given position. + parameterValue = collectASequenceOfCodePointsFast( + ';', + input, + position + ) + + // 2. Remove any trailing HTTP whitespace from parameterValue. + parameterValue = removeHTTPWhitespace(parameterValue, false, true) + + // 3. If parameterValue is the empty string, then continue. + if (parameterValue.length === 0) { + continue + } + } + + // 10. If all of the following are true + // - parameterName is not the empty string + // - parameterName solely contains HTTP token code points + // - parameterValue solely contains HTTP quoted-string token code points + // - mimeType’s parameters[parameterName] does not exist + // then set mimeType’s parameters[parameterName] to parameterValue. + if ( + parameterName.length !== 0 && + HTTP_TOKEN_CODEPOINTS.test(parameterName) && + (parameterValue.length === 0 || HTTP_QUOTED_STRING_TOKENS.test(parameterValue)) && + !mimeType.parameters.has(parameterName) + ) { + mimeType.parameters.set(parameterName, parameterValue) + } + } + + // 12. Return mimeType. + return mimeType +} + +// https://infra.spec.whatwg.org/#forgiving-base64-decode +/** @param {string} data */ +function forgivingBase64 (data) { + // 1. Remove all ASCII whitespace from data. + data = data.replace(ASCII_WHITESPACE_REPLACE_REGEX, '') + + let dataLength = data.length + // 2. If data’s code point length divides by 4 leaving + // no remainder, then: + if (dataLength % 4 === 0) { + // 1. If data ends with one or two U+003D (=) code points, + // then remove them from data. + if (data.charCodeAt(dataLength - 1) === 0x003D) { + --dataLength + if (data.charCodeAt(dataLength - 1) === 0x003D) { + --dataLength + } + } + } + + // 3. If data’s code point length divides by 4 leaving + // a remainder of 1, then return failure. + if (dataLength % 4 === 1) { + return 'failure' + } + + // 4. If data contains a code point that is not one of + // U+002B (+) + // U+002F (/) + // ASCII alphanumeric + // then return failure. + if (/[^+/0-9A-Za-z]/.test(data.length === dataLength ? data : data.substring(0, dataLength))) { + return 'failure' + } + + const buffer = Buffer.from(data, 'base64') + return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength) +} + +// https://fetch.spec.whatwg.org/#collect-an-http-quoted-string +// tests: https://fetch.spec.whatwg.org/#example-http-quoted-string +/** + * @param {string} input + * @param {{ position: number }} position + * @param {boolean} [extractValue=false] + */ +function collectAnHTTPQuotedString (input, position, extractValue = false) { + // 1. Let positionStart be position. + const positionStart = position.position + + // 2. Let value be the empty string. + let value = '' + + // 3. Assert: the code point at position within input + // is U+0022 ("). + assert(input[position.position] === '"') + + // 4. Advance position by 1. + position.position++ + + // 5. While true: + while (true) { + // 1. Append the result of collecting a sequence of code points + // that are not U+0022 (") or U+005C (\) from input, given + // position, to value. + value += collectASequenceOfCodePoints( + (char) => char !== '"' && char !== '\\', + input, + position + ) + + // 2. If position is past the end of input, then break. + if (position.position >= input.length) { + break + } + + // 3. Let quoteOrBackslash be the code point at position within + // input. + const quoteOrBackslash = input[position.position] + + // 4. Advance position by 1. + position.position++ + + // 5. If quoteOrBackslash is U+005C (\), then: + if (quoteOrBackslash === '\\') { + // 1. If position is past the end of input, then append + // U+005C (\) to value and break. + if (position.position >= input.length) { + value += '\\' + break + } + + // 2. Append the code point at position within input to value. + value += input[position.position] + + // 3. Advance position by 1. + position.position++ + + // 6. Otherwise: + } else { + // 1. Assert: quoteOrBackslash is U+0022 ("). + assert(quoteOrBackslash === '"') + + // 2. Break. + break + } + } + + // 6. If the extract-value flag is set, then return value. + if (extractValue) { + return value + } + + // 7. Return the code points from positionStart to position, + // inclusive, within input. + return input.slice(positionStart, position.position) +} + +/** + * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type + */ +function serializeAMimeType (mimeType) { + assert(mimeType !== 'failure') + const { parameters, essence } = mimeType + + // 1. Let serialization be the concatenation of mimeType’s + // type, U+002F (/), and mimeType’s subtype. + let serialization = essence + + // 2. For each name → value of mimeType’s parameters: + for (let [name, value] of parameters.entries()) { + // 1. Append U+003B (;) to serialization. + serialization += ';' + + // 2. Append name to serialization. + serialization += name + + // 3. Append U+003D (=) to serialization. + serialization += '=' + + // 4. If value does not solely contain HTTP token code + // points or value is the empty string, then: + if (!HTTP_TOKEN_CODEPOINTS.test(value)) { + // 1. Precede each occurrence of U+0022 (") or + // U+005C (\) in value with U+005C (\). + value = value.replace(/(\\|")/g, '\\$1') + + // 2. Prepend U+0022 (") to value. + value = '"' + value + + // 3. Append U+0022 (") to value. + value += '"' + } + + // 5. Append value to serialization. + serialization += value + } + + // 3. Return serialization. + return serialization +} + +/** + * @see https://fetch.spec.whatwg.org/#http-whitespace + * @param {number} char + */ +function isHTTPWhiteSpace (char) { + // "\r\n\t " + return char === 0x00d || char === 0x00a || char === 0x009 || char === 0x020 +} + +/** + * @see https://fetch.spec.whatwg.org/#http-whitespace + * @param {string} str + * @param {boolean} [leading=true] + * @param {boolean} [trailing=true] + */ +function removeHTTPWhitespace (str, leading = true, trailing = true) { + return removeChars(str, leading, trailing, isHTTPWhiteSpace) +} + +/** + * @see https://infra.spec.whatwg.org/#ascii-whitespace + * @param {number} char + */ +function isASCIIWhitespace (char) { + // "\r\n\t\f " + return char === 0x00d || char === 0x00a || char === 0x009 || char === 0x00c || char === 0x020 +} + +/** + * @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace + * @param {string} str + * @param {boolean} [leading=true] + * @param {boolean} [trailing=true] + */ +function removeASCIIWhitespace (str, leading = true, trailing = true) { + return removeChars(str, leading, trailing, isASCIIWhitespace) +} + +/** + * @param {string} str + * @param {boolean} leading + * @param {boolean} trailing + * @param {(charCode: number) => boolean} predicate + * @returns + */ +function removeChars (str, leading, trailing, predicate) { + let lead = 0 + let trail = str.length - 1 + + if (leading) { + while (lead < str.length && predicate(str.charCodeAt(lead))) lead++ + } + + if (trailing) { + while (trail > 0 && predicate(str.charCodeAt(trail))) trail-- + } + + return lead === 0 && trail === str.length - 1 ? str : str.slice(lead, trail + 1) +} + +/** + * @see https://infra.spec.whatwg.org/#isomorphic-decode + * @param {Uint8Array} input + * @returns {string} + */ +function isomorphicDecode (input) { + // 1. To isomorphic decode a byte sequence input, return a string whose code point + // length is equal to input’s length and whose code points have the same values + // as the values of input’s bytes, in the same order. + const length = input.length + if ((2 << 15) - 1 > length) { + return String.fromCharCode.apply(null, input) + } + let result = ''; let i = 0 + let addition = (2 << 15) - 1 + while (i < length) { + if (i + addition > length) { + addition = length - i + } + result += String.fromCharCode.apply(null, input.subarray(i, i += addition)) + } + return result +} + +/** + * @see https://mimesniff.spec.whatwg.org/#minimize-a-supported-mime-type + * @param {Exclude, 'failure'>} mimeType + */ +function minimizeSupportedMimeType (mimeType) { + switch (mimeType.essence) { + case 'application/ecmascript': + case 'application/javascript': + case 'application/x-ecmascript': + case 'application/x-javascript': + case 'text/ecmascript': + case 'text/javascript': + case 'text/javascript1.0': + case 'text/javascript1.1': + case 'text/javascript1.2': + case 'text/javascript1.3': + case 'text/javascript1.4': + case 'text/javascript1.5': + case 'text/jscript': + case 'text/livescript': + case 'text/x-ecmascript': + case 'text/x-javascript': + // 1. If mimeType is a JavaScript MIME type, then return "text/javascript". + return 'text/javascript' + case 'application/json': + case 'text/json': + // 2. If mimeType is a JSON MIME type, then return "application/json". + return 'application/json' + case 'image/svg+xml': + // 3. If mimeType’s essence is "image/svg+xml", then return "image/svg+xml". + return 'image/svg+xml' + case 'text/xml': + case 'application/xml': + // 4. If mimeType is an XML MIME type, then return "application/xml". + return 'application/xml' + } + + // 2. If mimeType is a JSON MIME type, then return "application/json". + if (mimeType.subtype.endsWith('+json')) { + return 'application/json' + } + + // 4. If mimeType is an XML MIME type, then return "application/xml". + if (mimeType.subtype.endsWith('+xml')) { + return 'application/xml' + } + + // 5. If mimeType is supported by the user agent, then return mimeType’s essence. + // Technically, node doesn't support any mimetypes. + + // 6. Return the empty string. + return '' +} + +module.exports = { + dataURLProcessor, + URLSerializer, + collectASequenceOfCodePoints, + collectASequenceOfCodePointsFast, + stringPercentDecode, + parseMIMEType, + collectAnHTTPQuotedString, + serializeAMimeType, + removeChars, + removeHTTPWhitespace, + minimizeSupportedMimeType, + HTTP_TOKEN_CODEPOINTS, + isomorphicDecode +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/fetch/formdata-parser.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/fetch/formdata-parser.js new file mode 100644 index 0000000000000000000000000000000000000000..5fd11444622b292e33db606839ec280f9dc81043 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/fetch/formdata-parser.js @@ -0,0 +1,498 @@ +'use strict' + +const { bufferToLowerCasedHeaderName } = require('../../core/util') +const { utf8DecodeBytes } = require('./util') +const { HTTP_TOKEN_CODEPOINTS, isomorphicDecode } = require('./data-url') +const { makeEntry } = require('./formdata') +const { webidl } = require('../webidl') +const assert = require('node:assert') + +const formDataNameBuffer = Buffer.from('form-data; name="') +const filenameBuffer = Buffer.from('filename') +const dd = Buffer.from('--') +const ddcrlf = Buffer.from('--\r\n') + +/** + * @param {string} chars + */ +function isAsciiString (chars) { + for (let i = 0; i < chars.length; ++i) { + if ((chars.charCodeAt(i) & ~0x7F) !== 0) { + return false + } + } + return true +} + +/** + * @see https://andreubotella.github.io/multipart-form-data/#multipart-form-data-boundary + * @param {string} boundary + */ +function validateBoundary (boundary) { + const length = boundary.length + + // - its length is greater or equal to 27 and lesser or equal to 70, and + if (length < 27 || length > 70) { + return false + } + + // - it is composed by bytes in the ranges 0x30 to 0x39, 0x41 to 0x5A, or + // 0x61 to 0x7A, inclusive (ASCII alphanumeric), or which are 0x27 ('), + // 0x2D (-) or 0x5F (_). + for (let i = 0; i < length; ++i) { + const cp = boundary.charCodeAt(i) + + if (!( + (cp >= 0x30 && cp <= 0x39) || + (cp >= 0x41 && cp <= 0x5a) || + (cp >= 0x61 && cp <= 0x7a) || + cp === 0x27 || + cp === 0x2d || + cp === 0x5f + )) { + return false + } + } + + return true +} + +/** + * @see https://andreubotella.github.io/multipart-form-data/#multipart-form-data-parser + * @param {Buffer} input + * @param {ReturnType} mimeType + */ +function multipartFormDataParser (input, mimeType) { + // 1. Assert: mimeType’s essence is "multipart/form-data". + assert(mimeType !== 'failure' && mimeType.essence === 'multipart/form-data') + + const boundaryString = mimeType.parameters.get('boundary') + + // 2. If mimeType’s parameters["boundary"] does not exist, return failure. + // Otherwise, let boundary be the result of UTF-8 decoding mimeType’s + // parameters["boundary"]. + if (boundaryString === undefined) { + throw parsingError('missing boundary in content-type header') + } + + const boundary = Buffer.from(`--${boundaryString}`, 'utf8') + + // 3. Let entry list be an empty entry list. + const entryList = [] + + // 4. Let position be a pointer to a byte in input, initially pointing at + // the first byte. + const position = { position: 0 } + + // Note: undici addition, allows leading and trailing CRLFs. + while (input[position.position] === 0x0d && input[position.position + 1] === 0x0a) { + position.position += 2 + } + + let trailing = input.length + + while (input[trailing - 1] === 0x0a && input[trailing - 2] === 0x0d) { + trailing -= 2 + } + + if (trailing !== input.length) { + input = input.subarray(0, trailing) + } + + // 5. While true: + while (true) { + // 5.1. If position points to a sequence of bytes starting with 0x2D 0x2D + // (`--`) followed by boundary, advance position by 2 + the length of + // boundary. Otherwise, return failure. + // Note: boundary is padded with 2 dashes already, no need to add 2. + if (input.subarray(position.position, position.position + boundary.length).equals(boundary)) { + position.position += boundary.length + } else { + throw parsingError('expected a value starting with -- and the boundary') + } + + // 5.2. If position points to the sequence of bytes 0x2D 0x2D 0x0D 0x0A + // (`--` followed by CR LF) followed by the end of input, return entry list. + // Note: a body does NOT need to end with CRLF. It can end with --. + if ( + (position.position === input.length - 2 && bufferStartsWith(input, dd, position)) || + (position.position === input.length - 4 && bufferStartsWith(input, ddcrlf, position)) + ) { + return entryList + } + + // 5.3. If position does not point to a sequence of bytes starting with 0x0D + // 0x0A (CR LF), return failure. + if (input[position.position] !== 0x0d || input[position.position + 1] !== 0x0a) { + throw parsingError('expected CRLF') + } + + // 5.4. Advance position by 2. (This skips past the newline.) + position.position += 2 + + // 5.5. Let name, filename and contentType be the result of parsing + // multipart/form-data headers on input and position, if the result + // is not failure. Otherwise, return failure. + const result = parseMultipartFormDataHeaders(input, position) + + let { name, filename, contentType, encoding } = result + + // 5.6. Advance position by 2. (This skips past the empty line that marks + // the end of the headers.) + position.position += 2 + + // 5.7. Let body be the empty byte sequence. + let body + + // 5.8. Body loop: While position is not past the end of input: + // TODO: the steps here are completely wrong + { + const boundaryIndex = input.indexOf(boundary.subarray(2), position.position) + + if (boundaryIndex === -1) { + throw parsingError('expected boundary after body') + } + + body = input.subarray(position.position, boundaryIndex - 4) + + position.position += body.length + + // Note: position must be advanced by the body's length before being + // decoded, otherwise the parsing will fail. + if (encoding === 'base64') { + body = Buffer.from(body.toString(), 'base64') + } + } + + // 5.9. If position does not point to a sequence of bytes starting with + // 0x0D 0x0A (CR LF), return failure. Otherwise, advance position by 2. + if (input[position.position] !== 0x0d || input[position.position + 1] !== 0x0a) { + throw parsingError('expected CRLF') + } else { + position.position += 2 + } + + // 5.10. If filename is not null: + let value + + if (filename !== null) { + // 5.10.1. If contentType is null, set contentType to "text/plain". + contentType ??= 'text/plain' + + // 5.10.2. If contentType is not an ASCII string, set contentType to the empty string. + + // Note: `buffer.isAscii` can be used at zero-cost, but converting a string to a buffer is a high overhead. + // Content-Type is a relatively small string, so it is faster to use `String#charCodeAt`. + if (!isAsciiString(contentType)) { + contentType = '' + } + + // 5.10.3. Let value be a new File object with name filename, type contentType, and body body. + value = new File([body], filename, { type: contentType }) + } else { + // 5.11. Otherwise: + + // 5.11.1. Let value be the UTF-8 decoding without BOM of body. + value = utf8DecodeBytes(Buffer.from(body)) + } + + // 5.12. Assert: name is a scalar value string and value is either a scalar value string or a File object. + assert(webidl.is.USVString(name)) + assert((typeof value === 'string' && webidl.is.USVString(value)) || webidl.is.File(value)) + + // 5.13. Create an entry with name and value, and append it to entry list. + entryList.push(makeEntry(name, value, filename)) + } +} + +/** + * @see https://andreubotella.github.io/multipart-form-data/#parse-multipart-form-data-headers + * @param {Buffer} input + * @param {{ position: number }} position + */ +function parseMultipartFormDataHeaders (input, position) { + // 1. Let name, filename and contentType be null. + let name = null + let filename = null + let contentType = null + let encoding = null + + // 2. While true: + while (true) { + // 2.1. If position points to a sequence of bytes starting with 0x0D 0x0A (CR LF): + if (input[position.position] === 0x0d && input[position.position + 1] === 0x0a) { + // 2.1.1. If name is null, return failure. + if (name === null) { + throw parsingError('header name is null') + } + + // 2.1.2. Return name, filename and contentType. + return { name, filename, contentType, encoding } + } + + // 2.2. Let header name be the result of collecting a sequence of bytes that are + // not 0x0A (LF), 0x0D (CR) or 0x3A (:), given position. + let headerName = collectASequenceOfBytes( + (char) => char !== 0x0a && char !== 0x0d && char !== 0x3a, + input, + position + ) + + // 2.3. Remove any HTTP tab or space bytes from the start or end of header name. + headerName = removeChars(headerName, true, true, (char) => char === 0x9 || char === 0x20) + + // 2.4. If header name does not match the field-name token production, return failure. + if (!HTTP_TOKEN_CODEPOINTS.test(headerName.toString())) { + throw parsingError('header name does not match the field-name token production') + } + + // 2.5. If the byte at position is not 0x3A (:), return failure. + if (input[position.position] !== 0x3a) { + throw parsingError('expected :') + } + + // 2.6. Advance position by 1. + position.position++ + + // 2.7. Collect a sequence of bytes that are HTTP tab or space bytes given position. + // (Do nothing with those bytes.) + collectASequenceOfBytes( + (char) => char === 0x20 || char === 0x09, + input, + position + ) + + // 2.8. Byte-lowercase header name and switch on the result: + switch (bufferToLowerCasedHeaderName(headerName)) { + case 'content-disposition': { + // 1. Set name and filename to null. + name = filename = null + + // 2. If position does not point to a sequence of bytes starting with + // `form-data; name="`, return failure. + if (!bufferStartsWith(input, formDataNameBuffer, position)) { + throw parsingError('expected form-data; name=" for content-disposition header') + } + + // 3. Advance position so it points at the byte after the next 0x22 (") + // byte (the one in the sequence of bytes matched above). + position.position += 17 + + // 4. Set name to the result of parsing a multipart/form-data name given + // input and position, if the result is not failure. Otherwise, return + // failure. + name = parseMultipartFormDataName(input, position) + + // 5. If position points to a sequence of bytes starting with `; filename="`: + if (input[position.position] === 0x3b /* ; */ && input[position.position + 1] === 0x20 /* ' ' */) { + const at = { position: position.position + 2 } + + if (bufferStartsWith(input, filenameBuffer, at)) { + if (input[at.position + 8] === 0x2a /* '*' */) { + at.position += 10 // skip past filename*= + + // Remove leading http tab and spaces. See RFC for examples. + // https://datatracker.ietf.org/doc/html/rfc6266#section-5 + collectASequenceOfBytes( + (char) => char === 0x20 || char === 0x09, + input, + at + ) + + const headerValue = collectASequenceOfBytes( + (char) => char !== 0x20 && char !== 0x0d && char !== 0x0a, // ' ' or CRLF + input, + at + ) + + if ( + (headerValue[0] !== 0x75 && headerValue[0] !== 0x55) || // u or U + (headerValue[1] !== 0x74 && headerValue[1] !== 0x54) || // t or T + (headerValue[2] !== 0x66 && headerValue[2] !== 0x46) || // f or F + headerValue[3] !== 0x2d || // - + headerValue[4] !== 0x38 // 8 + ) { + throw parsingError('unknown encoding, expected utf-8\'\'') + } + + // skip utf-8'' + filename = decodeURIComponent(new TextDecoder().decode(headerValue.subarray(7))) + + position.position = at.position + } else { + // 1. Advance position so it points at the byte after the next 0x22 (") byte + // (the one in the sequence of bytes matched above). + position.position += 11 + + // Remove leading http tab and spaces. See RFC for examples. + // https://datatracker.ietf.org/doc/html/rfc6266#section-5 + collectASequenceOfBytes( + (char) => char === 0x20 || char === 0x09, + input, + position + ) + + position.position++ // skip past " after removing whitespace + + // 2. Set filename to the result of parsing a multipart/form-data name given + // input and position, if the result is not failure. Otherwise, return failure. + filename = parseMultipartFormDataName(input, position) + } + } + } + + break + } + case 'content-type': { + // 1. Let header value be the result of collecting a sequence of bytes that are + // not 0x0A (LF) or 0x0D (CR), given position. + let headerValue = collectASequenceOfBytes( + (char) => char !== 0x0a && char !== 0x0d, + input, + position + ) + + // 2. Remove any HTTP tab or space bytes from the end of header value. + headerValue = removeChars(headerValue, false, true, (char) => char === 0x9 || char === 0x20) + + // 3. Set contentType to the isomorphic decoding of header value. + contentType = isomorphicDecode(headerValue) + + break + } + case 'content-transfer-encoding': { + let headerValue = collectASequenceOfBytes( + (char) => char !== 0x0a && char !== 0x0d, + input, + position + ) + + headerValue = removeChars(headerValue, false, true, (char) => char === 0x9 || char === 0x20) + + encoding = isomorphicDecode(headerValue) + + break + } + default: { + // Collect a sequence of bytes that are not 0x0A (LF) or 0x0D (CR), given position. + // (Do nothing with those bytes.) + collectASequenceOfBytes( + (char) => char !== 0x0a && char !== 0x0d, + input, + position + ) + } + } + + // 2.9. If position does not point to a sequence of bytes starting with 0x0D 0x0A + // (CR LF), return failure. Otherwise, advance position by 2 (past the newline). + if (input[position.position] !== 0x0d && input[position.position + 1] !== 0x0a) { + throw parsingError('expected CRLF') + } else { + position.position += 2 + } + } +} + +/** + * @see https://andreubotella.github.io/multipart-form-data/#parse-a-multipart-form-data-name + * @param {Buffer} input + * @param {{ position: number }} position + */ +function parseMultipartFormDataName (input, position) { + // 1. Assert: The byte at (position - 1) is 0x22 ("). + assert(input[position.position - 1] === 0x22) + + // 2. Let name be the result of collecting a sequence of bytes that are not 0x0A (LF), 0x0D (CR) or 0x22 ("), given position. + /** @type {string | Buffer} */ + let name = collectASequenceOfBytes( + (char) => char !== 0x0a && char !== 0x0d && char !== 0x22, + input, + position + ) + + // 3. If the byte at position is not 0x22 ("), return failure. Otherwise, advance position by 1. + if (input[position.position] !== 0x22) { + throw parsingError('expected "') + } else { + position.position++ + } + + // 4. Replace any occurrence of the following subsequences in name with the given byte: + // - `%0A`: 0x0A (LF) + // - `%0D`: 0x0D (CR) + // - `%22`: 0x22 (") + name = new TextDecoder().decode(name) + .replace(/%0A/ig, '\n') + .replace(/%0D/ig, '\r') + .replace(/%22/g, '"') + + // 5. Return the UTF-8 decoding without BOM of name. + return name +} + +/** + * @param {(char: number) => boolean} condition + * @param {Buffer} input + * @param {{ position: number }} position + */ +function collectASequenceOfBytes (condition, input, position) { + let start = position.position + + while (start < input.length && condition(input[start])) { + ++start + } + + return input.subarray(position.position, (position.position = start)) +} + +/** + * @param {Buffer} buf + * @param {boolean} leading + * @param {boolean} trailing + * @param {(charCode: number) => boolean} predicate + * @returns {Buffer} + */ +function removeChars (buf, leading, trailing, predicate) { + let lead = 0 + let trail = buf.length - 1 + + if (leading) { + while (lead < buf.length && predicate(buf[lead])) lead++ + } + + if (trailing) { + while (trail > 0 && predicate(buf[trail])) trail-- + } + + return lead === 0 && trail === buf.length - 1 ? buf : buf.subarray(lead, trail + 1) +} + +/** + * Checks if {@param buffer} starts with {@param start} + * @param {Buffer} buffer + * @param {Buffer} start + * @param {{ position: number }} position + */ +function bufferStartsWith (buffer, start, position) { + if (buffer.length < start.length) { + return false + } + + for (let i = 0; i < start.length; i++) { + if (start[i] !== buffer[position.position + i]) { + return false + } + } + + return true +} + +function parsingError (cause) { + return new TypeError('Failed to parse body as FormData.', { cause: new TypeError(cause) }) +} + +module.exports = { + multipartFormDataParser, + validateBoundary +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/fetch/formdata.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/fetch/formdata.js new file mode 100644 index 0000000000000000000000000000000000000000..c21fb06a3eeb62df2a6cc4e3844c6094c01fa557 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/fetch/formdata.js @@ -0,0 +1,259 @@ +'use strict' + +const { iteratorMixin } = require('./util') +const { kEnumerableProperty } = require('../../core/util') +const { webidl } = require('../webidl') +const nodeUtil = require('node:util') + +// https://xhr.spec.whatwg.org/#formdata +class FormData { + #state = [] + + constructor (form = undefined) { + webidl.util.markAsUncloneable(this) + + if (form !== undefined) { + throw webidl.errors.conversionFailed({ + prefix: 'FormData constructor', + argument: 'Argument 1', + types: ['undefined'] + }) + } + } + + append (name, value, filename = undefined) { + webidl.brandCheck(this, FormData) + + const prefix = 'FormData.append' + webidl.argumentLengthCheck(arguments, 2, prefix) + + name = webidl.converters.USVString(name) + + if (arguments.length === 3 || webidl.is.Blob(value)) { + value = webidl.converters.Blob(value, prefix, 'value') + + if (filename !== undefined) { + filename = webidl.converters.USVString(filename) + } + } else { + value = webidl.converters.USVString(value) + } + + // 1. Let value be value if given; otherwise blobValue. + + // 2. Let entry be the result of creating an entry with + // name, value, and filename if given. + const entry = makeEntry(name, value, filename) + + // 3. Append entry to this’s entry list. + this.#state.push(entry) + } + + delete (name) { + webidl.brandCheck(this, FormData) + + const prefix = 'FormData.delete' + webidl.argumentLengthCheck(arguments, 1, prefix) + + name = webidl.converters.USVString(name) + + // The delete(name) method steps are to remove all entries whose name + // is name from this’s entry list. + this.#state = this.#state.filter(entry => entry.name !== name) + } + + get (name) { + webidl.brandCheck(this, FormData) + + const prefix = 'FormData.get' + webidl.argumentLengthCheck(arguments, 1, prefix) + + name = webidl.converters.USVString(name) + + // 1. If there is no entry whose name is name in this’s entry list, + // then return null. + const idx = this.#state.findIndex((entry) => entry.name === name) + if (idx === -1) { + return null + } + + // 2. Return the value of the first entry whose name is name from + // this’s entry list. + return this.#state[idx].value + } + + getAll (name) { + webidl.brandCheck(this, FormData) + + const prefix = 'FormData.getAll' + webidl.argumentLengthCheck(arguments, 1, prefix) + + name = webidl.converters.USVString(name) + + // 1. If there is no entry whose name is name in this’s entry list, + // then return the empty list. + // 2. Return the values of all entries whose name is name, in order, + // from this’s entry list. + return this.#state + .filter((entry) => entry.name === name) + .map((entry) => entry.value) + } + + has (name) { + webidl.brandCheck(this, FormData) + + const prefix = 'FormData.has' + webidl.argumentLengthCheck(arguments, 1, prefix) + + name = webidl.converters.USVString(name) + + // The has(name) method steps are to return true if there is an entry + // whose name is name in this’s entry list; otherwise false. + return this.#state.findIndex((entry) => entry.name === name) !== -1 + } + + set (name, value, filename = undefined) { + webidl.brandCheck(this, FormData) + + const prefix = 'FormData.set' + webidl.argumentLengthCheck(arguments, 2, prefix) + + name = webidl.converters.USVString(name) + + if (arguments.length === 3 || webidl.is.Blob(value)) { + value = webidl.converters.Blob(value, prefix, 'value') + + if (filename !== undefined) { + filename = webidl.converters.USVString(filename) + } + } else { + value = webidl.converters.USVString(value) + } + + // The set(name, value) and set(name, blobValue, filename) method steps + // are: + + // 1. Let value be value if given; otherwise blobValue. + + // 2. Let entry be the result of creating an entry with name, value, and + // filename if given. + const entry = makeEntry(name, value, filename) + + // 3. If there are entries in this’s entry list whose name is name, then + // replace the first such entry with entry and remove the others. + const idx = this.#state.findIndex((entry) => entry.name === name) + if (idx !== -1) { + this.#state = [ + ...this.#state.slice(0, idx), + entry, + ...this.#state.slice(idx + 1).filter((entry) => entry.name !== name) + ] + } else { + // 4. Otherwise, append entry to this’s entry list. + this.#state.push(entry) + } + } + + [nodeUtil.inspect.custom] (depth, options) { + const state = this.#state.reduce((a, b) => { + if (a[b.name]) { + if (Array.isArray(a[b.name])) { + a[b.name].push(b.value) + } else { + a[b.name] = [a[b.name], b.value] + } + } else { + a[b.name] = b.value + } + + return a + }, { __proto__: null }) + + options.depth ??= depth + options.colors ??= true + + const output = nodeUtil.formatWithOptions(options, state) + + // remove [Object null prototype] + return `FormData ${output.slice(output.indexOf(']') + 2)}` + } + + /** + * @param {FormData} formData + */ + static getFormDataState (formData) { + return formData.#state + } + + /** + * @param {FormData} formData + * @param {any[]} newState + */ + static setFormDataState (formData, newState) { + formData.#state = newState + } +} + +const { getFormDataState, setFormDataState } = FormData +Reflect.deleteProperty(FormData, 'getFormDataState') +Reflect.deleteProperty(FormData, 'setFormDataState') + +iteratorMixin('FormData', FormData, getFormDataState, 'name', 'value') + +Object.defineProperties(FormData.prototype, { + append: kEnumerableProperty, + delete: kEnumerableProperty, + get: kEnumerableProperty, + getAll: kEnumerableProperty, + has: kEnumerableProperty, + set: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'FormData', + configurable: true + } +}) + +/** + * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#create-an-entry + * @param {string} name + * @param {string|Blob} value + * @param {?string} filename + * @returns + */ +function makeEntry (name, value, filename) { + // 1. Set name to the result of converting name into a scalar value string. + // Note: This operation was done by the webidl converter USVString. + + // 2. If value is a string, then set value to the result of converting + // value into a scalar value string. + if (typeof value === 'string') { + // Note: This operation was done by the webidl converter USVString. + } else { + // 3. Otherwise: + + // 1. If value is not a File object, then set value to a new File object, + // representing the same bytes, whose name attribute value is "blob" + if (!webidl.is.File(value)) { + value = new File([value], 'blob', { type: value.type }) + } + + // 2. If filename is given, then set value to a new File object, + // representing the same bytes, whose name attribute is filename. + if (filename !== undefined) { + /** @type {FilePropertyBag} */ + const options = { + type: value.type, + lastModified: value.lastModified + } + + value = new File([value], filename, options) + } + } + + // 4. Return an entry whose name is name and whose value is value. + return { name, value } +} + +webidl.is.FormData = webidl.util.MakeTypeAssertion(FormData) + +module.exports = { FormData, makeEntry, setFormDataState } diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/fetch/global.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/fetch/global.js new file mode 100644 index 0000000000000000000000000000000000000000..1df6f1227bc2658bd0595c33b33c1074a9c13b05 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/fetch/global.js @@ -0,0 +1,40 @@ +'use strict' + +// In case of breaking changes, increase the version +// number to avoid conflicts. +const globalOrigin = Symbol.for('undici.globalOrigin.1') + +function getGlobalOrigin () { + return globalThis[globalOrigin] +} + +function setGlobalOrigin (newOrigin) { + if (newOrigin === undefined) { + Object.defineProperty(globalThis, globalOrigin, { + value: undefined, + writable: true, + enumerable: false, + configurable: false + }) + + return + } + + const parsedURL = new URL(newOrigin) + + if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') { + throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`) + } + + Object.defineProperty(globalThis, globalOrigin, { + value: parsedURL, + writable: true, + enumerable: false, + configurable: false + }) +} + +module.exports = { + getGlobalOrigin, + setGlobalOrigin +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/fetch/headers.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/fetch/headers.js new file mode 100644 index 0000000000000000000000000000000000000000..024d19895880a75e6d0020341bff9e57fdb1841c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/fetch/headers.js @@ -0,0 +1,719 @@ +// https://github.com/Ethan-Arrowood/undici-fetch + +'use strict' + +const { kConstruct } = require('../../core/symbols') +const { kEnumerableProperty } = require('../../core/util') +const { + iteratorMixin, + isValidHeaderName, + isValidHeaderValue +} = require('./util') +const { webidl } = require('../webidl') +const assert = require('node:assert') +const util = require('node:util') + +/** + * @param {number} code + * @returns {code is (0x0a | 0x0d | 0x09 | 0x20)} + */ +function isHTTPWhiteSpaceCharCode (code) { + return code === 0x0a || code === 0x0d || code === 0x09 || code === 0x20 +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize + * @param {string} potentialValue + * @returns {string} + */ +function headerValueNormalize (potentialValue) { + // To normalize a byte sequence potentialValue, remove + // any leading and trailing HTTP whitespace bytes from + // potentialValue. + let i = 0; let j = potentialValue.length + + while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j + while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i + + return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j) +} + +/** + * @param {Headers} headers + * @param {Array|Object} object + */ +function fill (headers, object) { + // To fill a Headers object headers with a given object object, run these steps: + + // 1. If object is a sequence, then for each header in object: + // Note: webidl conversion to array has already been done. + if (Array.isArray(object)) { + for (let i = 0; i < object.length; ++i) { + const header = object[i] + // 1. If header does not contain exactly two items, then throw a TypeError. + if (header.length !== 2) { + throw webidl.errors.exception({ + header: 'Headers constructor', + message: `expected name/value pair to be length 2, found ${header.length}.` + }) + } + + // 2. Append (header’s first item, header’s second item) to headers. + appendHeader(headers, header[0], header[1]) + } + } else if (typeof object === 'object' && object !== null) { + // Note: null should throw + + // 2. Otherwise, object is a record, then for each key → value in object, + // append (key, value) to headers + const keys = Object.keys(object) + for (let i = 0; i < keys.length; ++i) { + appendHeader(headers, keys[i], object[keys[i]]) + } + } else { + throw webidl.errors.conversionFailed({ + prefix: 'Headers constructor', + argument: 'Argument 1', + types: ['sequence>', 'record'] + }) + } +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-headers-append + * @param {Headers} headers + * @param {string} name + * @param {string} value + */ +function appendHeader (headers, name, value) { + // 1. Normalize value. + value = headerValueNormalize(value) + + // 2. If name is not a header name or value is not a + // header value, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.append', + value: name, + type: 'header name' + }) + } else if (!isValidHeaderValue(value)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.append', + value, + type: 'header value' + }) + } + + // 3. If headers’s guard is "immutable", then throw a TypeError. + // 4. Otherwise, if headers’s guard is "request" and name is a + // forbidden header name, return. + // 5. Otherwise, if headers’s guard is "request-no-cors": + // TODO + // Note: undici does not implement forbidden header names + if (getHeadersGuard(headers) === 'immutable') { + throw new TypeError('immutable') + } + + // 6. Otherwise, if headers’s guard is "response" and name is a + // forbidden response-header name, return. + + // 7. Append (name, value) to headers’s header list. + return getHeadersList(headers).append(name, value, false) + + // 8. If headers’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from headers +} + +// https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine +/** + * @param {Headers} target + */ +function headersListSortAndCombine (target) { + const headersList = getHeadersList(target) + + if (!headersList) { + return [] + } + + if (headersList.sortedMap) { + return headersList.sortedMap + } + + // 1. Let headers be an empty list of headers with the key being the name + // and value the value. + const headers = [] + + // 2. Let names be the result of convert header names to a sorted-lowercase + // set with all the names of the headers in list. + const names = headersList.toSortedArray() + + const cookies = headersList.cookies + + // fast-path + if (cookies === null || cookies.length === 1) { + // Note: The non-null assertion of value has already been done by `HeadersList#toSortedArray` + return (headersList.sortedMap = names) + } + + // 3. For each name of names: + for (let i = 0; i < names.length; ++i) { + const { 0: name, 1: value } = names[i] + // 1. If name is `set-cookie`, then: + if (name === 'set-cookie') { + // 1. Let values be a list of all values of headers in list whose name + // is a byte-case-insensitive match for name, in order. + + // 2. For each value of values: + // 1. Append (name, value) to headers. + for (let j = 0; j < cookies.length; ++j) { + headers.push([name, cookies[j]]) + } + } else { + // 2. Otherwise: + + // 1. Let value be the result of getting name from list. + + // 2. Assert: value is non-null. + // Note: This operation was done by `HeadersList#toSortedArray`. + + // 3. Append (name, value) to headers. + headers.push([name, value]) + } + } + + // 4. Return headers. + return (headersList.sortedMap = headers) +} + +function compareHeaderName (a, b) { + return a[0] < b[0] ? -1 : 1 +} + +class HeadersList { + /** @type {[string, string][]|null} */ + cookies = null + + sortedMap + headersMap + + constructor (init) { + if (init instanceof HeadersList) { + this.headersMap = new Map(init.headersMap) + this.sortedMap = init.sortedMap + this.cookies = init.cookies === null ? null : [...init.cookies] + } else { + this.headersMap = new Map(init) + this.sortedMap = null + } + } + + /** + * @see https://fetch.spec.whatwg.org/#header-list-contains + * @param {string} name + * @param {boolean} isLowerCase + */ + contains (name, isLowerCase) { + // A header list list contains a header name name if list + // contains a header whose name is a byte-case-insensitive + // match for name. + + return this.headersMap.has(isLowerCase ? name : name.toLowerCase()) + } + + clear () { + this.headersMap.clear() + this.sortedMap = null + this.cookies = null + } + + /** + * @see https://fetch.spec.whatwg.org/#concept-header-list-append + * @param {string} name + * @param {string} value + * @param {boolean} isLowerCase + */ + append (name, value, isLowerCase) { + this.sortedMap = null + + // 1. If list contains name, then set name to the first such + // header’s name. + const lowercaseName = isLowerCase ? name : name.toLowerCase() + const exists = this.headersMap.get(lowercaseName) + + // 2. Append (name, value) to list. + if (exists) { + const delimiter = lowercaseName === 'cookie' ? '; ' : ', ' + this.headersMap.set(lowercaseName, { + name: exists.name, + value: `${exists.value}${delimiter}${value}` + }) + } else { + this.headersMap.set(lowercaseName, { name, value }) + } + + if (lowercaseName === 'set-cookie') { + (this.cookies ??= []).push(value) + } + } + + /** + * @see https://fetch.spec.whatwg.org/#concept-header-list-set + * @param {string} name + * @param {string} value + * @param {boolean} isLowerCase + */ + set (name, value, isLowerCase) { + this.sortedMap = null + const lowercaseName = isLowerCase ? name : name.toLowerCase() + + if (lowercaseName === 'set-cookie') { + this.cookies = [value] + } + + // 1. If list contains name, then set the value of + // the first such header to value and remove the + // others. + // 2. Otherwise, append header (name, value) to list. + this.headersMap.set(lowercaseName, { name, value }) + } + + /** + * @see https://fetch.spec.whatwg.org/#concept-header-list-delete + * @param {string} name + * @param {boolean} isLowerCase + */ + delete (name, isLowerCase) { + this.sortedMap = null + if (!isLowerCase) name = name.toLowerCase() + + if (name === 'set-cookie') { + this.cookies = null + } + + this.headersMap.delete(name) + } + + /** + * @see https://fetch.spec.whatwg.org/#concept-header-list-get + * @param {string} name + * @param {boolean} isLowerCase + * @returns {string | null} + */ + get (name, isLowerCase) { + // 1. If list does not contain name, then return null. + // 2. Return the values of all headers in list whose name + // is a byte-case-insensitive match for name, + // separated from each other by 0x2C 0x20, in order. + return this.headersMap.get(isLowerCase ? name : name.toLowerCase())?.value ?? null + } + + * [Symbol.iterator] () { + // use the lowercased name + for (const { 0: name, 1: { value } } of this.headersMap) { + yield [name, value] + } + } + + get entries () { + const headers = {} + + if (this.headersMap.size !== 0) { + for (const { name, value } of this.headersMap.values()) { + headers[name] = value + } + } + + return headers + } + + rawValues () { + return this.headersMap.values() + } + + get entriesList () { + const headers = [] + + if (this.headersMap.size !== 0) { + for (const { 0: lowerName, 1: { name, value } } of this.headersMap) { + if (lowerName === 'set-cookie') { + for (const cookie of this.cookies) { + headers.push([name, cookie]) + } + } else { + headers.push([name, value]) + } + } + } + + return headers + } + + // https://fetch.spec.whatwg.org/#convert-header-names-to-a-sorted-lowercase-set + toSortedArray () { + const size = this.headersMap.size + const array = new Array(size) + // In most cases, you will use the fast-path. + // fast-path: Use binary insertion sort for small arrays. + if (size <= 32) { + if (size === 0) { + // If empty, it is an empty array. To avoid the first index assignment. + return array + } + // Improve performance by unrolling loop and avoiding double-loop. + // Double-loop-less version of the binary insertion sort. + const iterator = this.headersMap[Symbol.iterator]() + const firstValue = iterator.next().value + // set [name, value] to first index. + array[0] = [firstValue[0], firstValue[1].value] + // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine + // 3.2.2. Assert: value is non-null. + assert(firstValue[1].value !== null) + for ( + let i = 1, j = 0, right = 0, left = 0, pivot = 0, x, value; + i < size; + ++i + ) { + // get next value + value = iterator.next().value + // set [name, value] to current index. + x = array[i] = [value[0], value[1].value] + // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine + // 3.2.2. Assert: value is non-null. + assert(x[1] !== null) + left = 0 + right = i + // binary search + while (left < right) { + // middle index + pivot = left + ((right - left) >> 1) + // compare header name + if (array[pivot][0] <= x[0]) { + left = pivot + 1 + } else { + right = pivot + } + } + if (i !== pivot) { + j = i + while (j > left) { + array[j] = array[--j] + } + array[left] = x + } + } + /* c8 ignore next 4 */ + if (!iterator.next().done) { + // This is for debugging and will never be called. + throw new TypeError('Unreachable') + } + return array + } else { + // This case would be a rare occurrence. + // slow-path: fallback + let i = 0 + for (const { 0: name, 1: { value } } of this.headersMap) { + array[i++] = [name, value] + // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine + // 3.2.2. Assert: value is non-null. + assert(value !== null) + } + return array.sort(compareHeaderName) + } + } +} + +// https://fetch.spec.whatwg.org/#headers-class +class Headers { + #guard + /** + * @type {HeadersList} + */ + #headersList + + /** + * @param {HeadersInit|Symbol} [init] + * @returns + */ + constructor (init = undefined) { + webidl.util.markAsUncloneable(this) + + if (init === kConstruct) { + return + } + + this.#headersList = new HeadersList() + + // The new Headers(init) constructor steps are: + + // 1. Set this’s guard to "none". + this.#guard = 'none' + + // 2. If init is given, then fill this with init. + if (init !== undefined) { + init = webidl.converters.HeadersInit(init, 'Headers constructor', 'init') + fill(this, init) + } + } + + // https://fetch.spec.whatwg.org/#dom-headers-append + append (name, value) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 2, 'Headers.append') + + const prefix = 'Headers.append' + name = webidl.converters.ByteString(name, prefix, 'name') + value = webidl.converters.ByteString(value, prefix, 'value') + + return appendHeader(this, name, value) + } + + // https://fetch.spec.whatwg.org/#dom-headers-delete + delete (name) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 1, 'Headers.delete') + + const prefix = 'Headers.delete' + name = webidl.converters.ByteString(name, prefix, 'name') + + // 1. If name is not a header name, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.delete', + value: name, + type: 'header name' + }) + } + + // 2. If this’s guard is "immutable", then throw a TypeError. + // 3. Otherwise, if this’s guard is "request" and name is a + // forbidden header name, return. + // 4. Otherwise, if this’s guard is "request-no-cors", name + // is not a no-CORS-safelisted request-header name, and + // name is not a privileged no-CORS request-header name, + // return. + // 5. Otherwise, if this’s guard is "response" and name is + // a forbidden response-header name, return. + // Note: undici does not implement forbidden header names + if (this.#guard === 'immutable') { + throw new TypeError('immutable') + } + + // 6. If this’s header list does not contain name, then + // return. + if (!this.#headersList.contains(name, false)) { + return + } + + // 7. Delete name from this’s header list. + // 8. If this’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from this. + this.#headersList.delete(name, false) + } + + // https://fetch.spec.whatwg.org/#dom-headers-get + get (name) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 1, 'Headers.get') + + const prefix = 'Headers.get' + name = webidl.converters.ByteString(name, prefix, 'name') + + // 1. If name is not a header name, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix, + value: name, + type: 'header name' + }) + } + + // 2. Return the result of getting name from this’s header + // list. + return this.#headersList.get(name, false) + } + + // https://fetch.spec.whatwg.org/#dom-headers-has + has (name) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 1, 'Headers.has') + + const prefix = 'Headers.has' + name = webidl.converters.ByteString(name, prefix, 'name') + + // 1. If name is not a header name, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix, + value: name, + type: 'header name' + }) + } + + // 2. Return true if this’s header list contains name; + // otherwise false. + return this.#headersList.contains(name, false) + } + + // https://fetch.spec.whatwg.org/#dom-headers-set + set (name, value) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 2, 'Headers.set') + + const prefix = 'Headers.set' + name = webidl.converters.ByteString(name, prefix, 'name') + value = webidl.converters.ByteString(value, prefix, 'value') + + // 1. Normalize value. + value = headerValueNormalize(value) + + // 2. If name is not a header name or value is not a + // header value, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix, + value: name, + type: 'header name' + }) + } else if (!isValidHeaderValue(value)) { + throw webidl.errors.invalidArgument({ + prefix, + value, + type: 'header value' + }) + } + + // 3. If this’s guard is "immutable", then throw a TypeError. + // 4. Otherwise, if this’s guard is "request" and name is a + // forbidden header name, return. + // 5. Otherwise, if this’s guard is "request-no-cors" and + // name/value is not a no-CORS-safelisted request-header, + // return. + // 6. Otherwise, if this’s guard is "response" and name is a + // forbidden response-header name, return. + // Note: undici does not implement forbidden header names + if (this.#guard === 'immutable') { + throw new TypeError('immutable') + } + + // 7. Set (name, value) in this’s header list. + // 8. If this’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from this + this.#headersList.set(name, value, false) + } + + // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie + getSetCookie () { + webidl.brandCheck(this, Headers) + + // 1. If this’s header list does not contain `Set-Cookie`, then return « ». + // 2. Return the values of all headers in this’s header list whose name is + // a byte-case-insensitive match for `Set-Cookie`, in order. + + const list = this.#headersList.cookies + + if (list) { + return [...list] + } + + return [] + } + + [util.inspect.custom] (depth, options) { + options.depth ??= depth + + return `Headers ${util.formatWithOptions(options, this.#headersList.entries)}` + } + + static getHeadersGuard (o) { + return o.#guard + } + + static setHeadersGuard (o, guard) { + o.#guard = guard + } + + /** + * @param {Headers} o + */ + static getHeadersList (o) { + return o.#headersList + } + + /** + * @param {Headers} target + * @param {HeadersList} list + */ + static setHeadersList (target, list) { + target.#headersList = list + } +} + +const { getHeadersGuard, setHeadersGuard, getHeadersList, setHeadersList } = Headers +Reflect.deleteProperty(Headers, 'getHeadersGuard') +Reflect.deleteProperty(Headers, 'setHeadersGuard') +Reflect.deleteProperty(Headers, 'getHeadersList') +Reflect.deleteProperty(Headers, 'setHeadersList') + +iteratorMixin('Headers', Headers, headersListSortAndCombine, 0, 1) + +Object.defineProperties(Headers.prototype, { + append: kEnumerableProperty, + delete: kEnumerableProperty, + get: kEnumerableProperty, + has: kEnumerableProperty, + set: kEnumerableProperty, + getSetCookie: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'Headers', + configurable: true + }, + [util.inspect.custom]: { + enumerable: false + } +}) + +webidl.converters.HeadersInit = function (V, prefix, argument) { + if (webidl.util.Type(V) === webidl.util.Types.OBJECT) { + const iterator = Reflect.get(V, Symbol.iterator) + + // A work-around to ensure we send the properly-cased Headers when V is a Headers object. + // Read https://github.com/nodejs/undici/pull/3159#issuecomment-2075537226 before touching, please. + if (!util.types.isProxy(V) && iterator === Headers.prototype.entries) { // Headers object + try { + return getHeadersList(V).entriesList + } catch { + // fall-through + } + } + + if (typeof iterator === 'function') { + return webidl.converters['sequence>'](V, prefix, argument, iterator.bind(V)) + } + + return webidl.converters['record'](V, prefix, argument) + } + + throw webidl.errors.conversionFailed({ + prefix: 'Headers constructor', + argument: 'Argument 1', + types: ['sequence>', 'record'] + }) +} + +module.exports = { + fill, + // for test. + compareHeaderName, + Headers, + HeadersList, + getHeadersGuard, + setHeadersGuard, + setHeadersList, + getHeadersList +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/fetch/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/fetch/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d7bb32e47c10b8673319fe7f0330e745cd966a09 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/fetch/index.js @@ -0,0 +1,2260 @@ +// https://github.com/Ethan-Arrowood/undici-fetch + +'use strict' + +const { + makeNetworkError, + makeAppropriateNetworkError, + filterResponse, + makeResponse, + fromInnerResponse, + getResponseState +} = require('./response') +const { HeadersList } = require('./headers') +const { Request, cloneRequest, getRequestDispatcher, getRequestState } = require('./request') +const zlib = require('node:zlib') +const { + makePolicyContainer, + clonePolicyContainer, + requestBadPort, + TAOCheck, + appendRequestOriginHeader, + responseLocationURL, + requestCurrentURL, + setRequestReferrerPolicyOnRedirect, + tryUpgradeRequestToAPotentiallyTrustworthyURL, + createOpaqueTimingInfo, + appendFetchMetadata, + corsCheck, + crossOriginResourcePolicyCheck, + determineRequestsReferrer, + coarsenedSharedCurrentTime, + sameOrigin, + isCancelled, + isAborted, + isErrorLike, + fullyReadBody, + readableStreamClose, + isomorphicEncode, + urlIsLocal, + urlIsHttpHttpsScheme, + urlHasHttpsScheme, + clampAndCoarsenConnectionTimingInfo, + simpleRangeHeaderValue, + buildContentRange, + createInflate, + extractMimeType +} = require('./util') +const assert = require('node:assert') +const { safelyExtractBody, extractBody } = require('./body') +const { + redirectStatusSet, + nullBodyStatus, + safeMethodsSet, + requestBodyHeader, + subresourceSet +} = require('./constants') +const EE = require('node:events') +const { Readable, pipeline, finished, isErrored, isReadable } = require('node:stream') +const { addAbortListener, bufferToLowerCasedHeaderName } = require('../../core/util') +const { dataURLProcessor, serializeAMimeType, minimizeSupportedMimeType } = require('./data-url') +const { getGlobalDispatcher } = require('../../global') +const { webidl } = require('../webidl') +const { STATUS_CODES } = require('node:http') +const { bytesMatch } = require('../subresource-integrity/subresource-integrity') +const { createDeferredPromise } = require('../../util/promise') +const GET_OR_HEAD = ['GET', 'HEAD'] + +const defaultUserAgent = typeof __UNDICI_IS_NODE__ !== 'undefined' || typeof esbuildDetection !== 'undefined' + ? 'node' + : 'undici' + +/** @type {import('buffer').resolveObjectURL} */ +let resolveObjectURL + +class Fetch extends EE { + constructor (dispatcher) { + super() + + this.dispatcher = dispatcher + this.connection = null + this.dump = false + this.state = 'ongoing' + } + + terminate (reason) { + if (this.state !== 'ongoing') { + return + } + + this.state = 'terminated' + this.connection?.destroy(reason) + this.emit('terminated', reason) + } + + // https://fetch.spec.whatwg.org/#fetch-controller-abort + abort (error) { + if (this.state !== 'ongoing') { + return + } + + // 1. Set controller’s state to "aborted". + this.state = 'aborted' + + // 2. Let fallbackError be an "AbortError" DOMException. + // 3. Set error to fallbackError if it is not given. + if (!error) { + error = new DOMException('The operation was aborted.', 'AbortError') + } + + // 4. Let serializedError be StructuredSerialize(error). + // If that threw an exception, catch it, and let + // serializedError be StructuredSerialize(fallbackError). + + // 5. Set controller’s serialized abort reason to serializedError. + this.serializedAbortReason = error + + this.connection?.destroy(error) + this.emit('terminated', error) + } +} + +function handleFetchDone (response) { + finalizeAndReportTiming(response, 'fetch') +} + +// https://fetch.spec.whatwg.org/#fetch-method +function fetch (input, init = undefined) { + webidl.argumentLengthCheck(arguments, 1, 'globalThis.fetch') + + // 1. Let p be a new promise. + let p = createDeferredPromise() + + // 2. Let requestObject be the result of invoking the initial value of + // Request as constructor with input and init as arguments. If this throws + // an exception, reject p with it and return p. + let requestObject + + try { + requestObject = new Request(input, init) + } catch (e) { + p.reject(e) + return p.promise + } + + // 3. Let request be requestObject’s request. + const request = getRequestState(requestObject) + + // 4. If requestObject’s signal’s aborted flag is set, then: + if (requestObject.signal.aborted) { + // 1. Abort the fetch() call with p, request, null, and + // requestObject’s signal’s abort reason. + abortFetch(p, request, null, requestObject.signal.reason) + + // 2. Return p. + return p.promise + } + + // 5. Let globalObject be request’s client’s global object. + const globalObject = request.client.globalObject + + // 6. If globalObject is a ServiceWorkerGlobalScope object, then set + // request’s service-workers mode to "none". + if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') { + request.serviceWorkers = 'none' + } + + // 7. Let responseObject be null. + let responseObject = null + + // 8. Let relevantRealm be this’s relevant Realm. + + // 9. Let locallyAborted be false. + let locallyAborted = false + + // 10. Let controller be null. + let controller = null + + // 11. Add the following abort steps to requestObject’s signal: + addAbortListener( + requestObject.signal, + () => { + // 1. Set locallyAborted to true. + locallyAborted = true + + // 2. Assert: controller is non-null. + assert(controller != null) + + // 3. Abort controller with requestObject’s signal’s abort reason. + controller.abort(requestObject.signal.reason) + + const realResponse = responseObject?.deref() + + // 4. Abort the fetch() call with p, request, responseObject, + // and requestObject’s signal’s abort reason. + abortFetch(p, request, realResponse, requestObject.signal.reason) + } + ) + + // 12. Let handleFetchDone given response response be to finalize and + // report timing with response, globalObject, and "fetch". + // see function handleFetchDone + + // 13. Set controller to the result of calling fetch given request, + // with processResponseEndOfBody set to handleFetchDone, and processResponse + // given response being these substeps: + + const processResponse = (response) => { + // 1. If locallyAborted is true, terminate these substeps. + if (locallyAborted) { + return + } + + // 2. If response’s aborted flag is set, then: + if (response.aborted) { + // 1. Let deserializedError be the result of deserialize a serialized + // abort reason given controller’s serialized abort reason and + // relevantRealm. + + // 2. Abort the fetch() call with p, request, responseObject, and + // deserializedError. + + abortFetch(p, request, responseObject, controller.serializedAbortReason) + return + } + + // 3. If response is a network error, then reject p with a TypeError + // and terminate these substeps. + if (response.type === 'error') { + p.reject(new TypeError('fetch failed', { cause: response.error })) + return + } + + // 4. Set responseObject to the result of creating a Response object, + // given response, "immutable", and relevantRealm. + responseObject = new WeakRef(fromInnerResponse(response, 'immutable')) + + // 5. Resolve p with responseObject. + p.resolve(responseObject.deref()) + p = null + } + + controller = fetching({ + request, + processResponseEndOfBody: handleFetchDone, + processResponse, + dispatcher: getRequestDispatcher(requestObject) // undici + }) + + // 14. Return p. + return p.promise +} + +// https://fetch.spec.whatwg.org/#finalize-and-report-timing +function finalizeAndReportTiming (response, initiatorType = 'other') { + // 1. If response is an aborted network error, then return. + if (response.type === 'error' && response.aborted) { + return + } + + // 2. If response’s URL list is null or empty, then return. + if (!response.urlList?.length) { + return + } + + // 3. Let originalURL be response’s URL list[0]. + const originalURL = response.urlList[0] + + // 4. Let timingInfo be response’s timing info. + let timingInfo = response.timingInfo + + // 5. Let cacheState be response’s cache state. + let cacheState = response.cacheState + + // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return. + if (!urlIsHttpHttpsScheme(originalURL)) { + return + } + + // 7. If timingInfo is null, then return. + if (timingInfo === null) { + return + } + + // 8. If response’s timing allow passed flag is not set, then: + if (!response.timingAllowPassed) { + // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo. + timingInfo = createOpaqueTimingInfo({ + startTime: timingInfo.startTime + }) + + // 2. Set cacheState to the empty string. + cacheState = '' + } + + // 9. Set timingInfo’s end time to the coarsened shared current time + // given global’s relevant settings object’s cross-origin isolated + // capability. + // TODO: given global’s relevant settings object’s cross-origin isolated + // capability? + timingInfo.endTime = coarsenedSharedCurrentTime() + + // 10. Set response’s timing info to timingInfo. + response.timingInfo = timingInfo + + // 11. Mark resource timing for timingInfo, originalURL, initiatorType, + // global, and cacheState. + markResourceTiming( + timingInfo, + originalURL.href, + initiatorType, + globalThis, + cacheState, + '', // bodyType + response.status + ) +} + +// https://w3c.github.io/resource-timing/#dfn-mark-resource-timing +const markResourceTiming = performance.markResourceTiming + +// https://fetch.spec.whatwg.org/#abort-fetch +function abortFetch (p, request, responseObject, error) { + // 1. Reject promise with error. + if (p) { + // We might have already resolved the promise at this stage + p.reject(error) + } + + // 2. If request’s body is not null and is readable, then cancel request’s + // body with error. + if (request.body?.stream != null && isReadable(request.body.stream)) { + request.body.stream.cancel(error).catch((err) => { + if (err.code === 'ERR_INVALID_STATE') { + // Node bug? + return + } + throw err + }) + } + + // 3. If responseObject is null, then return. + if (responseObject == null) { + return + } + + // 4. Let response be responseObject’s response. + const response = getResponseState(responseObject) + + // 5. If response’s body is not null and is readable, then error response’s + // body with error. + if (response.body?.stream != null && isReadable(response.body.stream)) { + response.body.stream.cancel(error).catch((err) => { + if (err.code === 'ERR_INVALID_STATE') { + // Node bug? + return + } + throw err + }) + } +} + +// https://fetch.spec.whatwg.org/#fetching +function fetching ({ + request, + processRequestBodyChunkLength, + processRequestEndOfBody, + processResponse, + processResponseEndOfBody, + processResponseConsumeBody, + useParallelQueue = false, + dispatcher = getGlobalDispatcher() // undici +}) { + // Ensure that the dispatcher is set accordingly + assert(dispatcher) + + // 1. Let taskDestination be null. + let taskDestination = null + + // 2. Let crossOriginIsolatedCapability be false. + let crossOriginIsolatedCapability = false + + // 3. If request’s client is non-null, then: + if (request.client != null) { + // 1. Set taskDestination to request’s client’s global object. + taskDestination = request.client.globalObject + + // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin + // isolated capability. + crossOriginIsolatedCapability = + request.client.crossOriginIsolatedCapability + } + + // 4. If useParallelQueue is true, then set taskDestination to the result of + // starting a new parallel queue. + // TODO + + // 5. Let timingInfo be a new fetch timing info whose start time and + // post-redirect start time are the coarsened shared current time given + // crossOriginIsolatedCapability. + const currentTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability) + const timingInfo = createOpaqueTimingInfo({ + startTime: currentTime + }) + + // 6. Let fetchParams be a new fetch params whose + // request is request, + // timing info is timingInfo, + // process request body chunk length is processRequestBodyChunkLength, + // process request end-of-body is processRequestEndOfBody, + // process response is processResponse, + // process response consume body is processResponseConsumeBody, + // process response end-of-body is processResponseEndOfBody, + // task destination is taskDestination, + // and cross-origin isolated capability is crossOriginIsolatedCapability. + const fetchParams = { + controller: new Fetch(dispatcher), + request, + timingInfo, + processRequestBodyChunkLength, + processRequestEndOfBody, + processResponse, + processResponseConsumeBody, + processResponseEndOfBody, + taskDestination, + crossOriginIsolatedCapability + } + + // 7. If request’s body is a byte sequence, then set request’s body to + // request’s body as a body. + // NOTE: Since fetching is only called from fetch, body should already be + // extracted. + assert(!request.body || request.body.stream) + + // 8. If request’s window is "client", then set request’s window to request’s + // client, if request’s client’s global object is a Window object; otherwise + // "no-window". + if (request.window === 'client') { + // TODO: What if request.client is null? + request.window = + request.client?.globalObject?.constructor?.name === 'Window' + ? request.client + : 'no-window' + } + + // 9. If request’s origin is "client", then set request’s origin to request’s + // client’s origin. + if (request.origin === 'client') { + request.origin = request.client.origin + } + + // 10. If all of the following conditions are true: + // TODO + + // 11. If request’s policy container is "client", then: + if (request.policyContainer === 'client') { + // 1. If request’s client is non-null, then set request’s policy + // container to a clone of request’s client’s policy container. [HTML] + if (request.client != null) { + request.policyContainer = clonePolicyContainer( + request.client.policyContainer + ) + } else { + // 2. Otherwise, set request’s policy container to a new policy + // container. + request.policyContainer = makePolicyContainer() + } + } + + // 12. If request’s header list does not contain `Accept`, then: + if (!request.headersList.contains('accept', true)) { + // 1. Let value be `*/*`. + const value = '*/*' + + // 2. A user agent should set value to the first matching statement, if + // any, switching on request’s destination: + // "document" + // "frame" + // "iframe" + // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8` + // "image" + // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5` + // "style" + // `text/css,*/*;q=0.1` + // TODO + + // 3. Append `Accept`/value to request’s header list. + request.headersList.append('accept', value, true) + } + + // 13. If request’s header list does not contain `Accept-Language`, then + // user agents should append `Accept-Language`/an appropriate value to + // request’s header list. + if (!request.headersList.contains('accept-language', true)) { + request.headersList.append('accept-language', '*', true) + } + + // 14. If request’s priority is null, then use request’s initiator and + // destination appropriately in setting request’s priority to a + // user-agent-defined object. + if (request.priority === null) { + // TODO + } + + // 15. If request is a subresource request, then: + if (subresourceSet.has(request.destination)) { + // TODO + } + + // 16. Run main fetch given fetchParams. + mainFetch(fetchParams, false) + + // 17. Return fetchParam's controller + return fetchParams.controller +} + +// https://fetch.spec.whatwg.org/#concept-main-fetch +async function mainFetch (fetchParams, recursive) { + try { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let response be null. + let response = null + + // 3. If request’s local-URLs-only flag is set and request’s current URL is + // not local, then set response to a network error. + if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) { + response = makeNetworkError('local URLs only') + } + + // 4. Run report Content Security Policy violations for request. + // TODO + + // 5. Upgrade request to a potentially trustworthy URL, if appropriate. + tryUpgradeRequestToAPotentiallyTrustworthyURL(request) + + // 6. If should request be blocked due to a bad port, should fetching request + // be blocked as mixed content, or should request be blocked by Content + // Security Policy returns blocked, then set response to a network error. + if (requestBadPort(request) === 'blocked') { + response = makeNetworkError('bad port') + } + // TODO: should fetching request be blocked as mixed content? + // TODO: should request be blocked by Content Security Policy? + + // 7. If request’s referrer policy is the empty string, then set request’s + // referrer policy to request’s policy container’s referrer policy. + if (request.referrerPolicy === '') { + request.referrerPolicy = request.policyContainer.referrerPolicy + } + + // 8. If request’s referrer is not "no-referrer", then set request’s + // referrer to the result of invoking determine request’s referrer. + if (request.referrer !== 'no-referrer') { + request.referrer = determineRequestsReferrer(request) + } + + // 9. Set request’s current URL’s scheme to "https" if all of the following + // conditions are true: + // - request’s current URL’s scheme is "http" + // - request’s current URL’s host is a domain + // - Matching request’s current URL’s host per Known HSTS Host Domain Name + // Matching results in either a superdomain match with an asserted + // includeSubDomains directive or a congruent match (with or without an + // asserted includeSubDomains directive). [HSTS] + // TODO + + // 10. If recursive is false, then run the remaining steps in parallel. + // TODO + + // 11. If response is null, then set response to the result of running + // the steps corresponding to the first matching statement: + if (response === null) { + const currentURL = requestCurrentURL(request) + if ( + // - request’s current URL’s origin is same origin with request’s origin, + // and request’s response tainting is "basic" + (sameOrigin(currentURL, request.url) && request.responseTainting === 'basic') || + // request’s current URL’s scheme is "data" + (currentURL.protocol === 'data:') || + // - request’s mode is "navigate" or "websocket" + (request.mode === 'navigate' || request.mode === 'websocket') + ) { + // 1. Set request’s response tainting to "basic". + request.responseTainting = 'basic' + + // 2. Return the result of running scheme fetch given fetchParams. + response = await schemeFetch(fetchParams) + + // request’s mode is "same-origin" + } else if (request.mode === 'same-origin') { + // 1. Return a network error. + response = makeNetworkError('request mode cannot be "same-origin"') + + // request’s mode is "no-cors" + } else if (request.mode === 'no-cors') { + // 1. If request’s redirect mode is not "follow", then return a network + // error. + if (request.redirect !== 'follow') { + response = makeNetworkError( + 'redirect mode cannot be "follow" for "no-cors" request' + ) + } else { + // 2. Set request’s response tainting to "opaque". + request.responseTainting = 'opaque' + + // 3. Return the result of running scheme fetch given fetchParams. + response = await schemeFetch(fetchParams) + } + // request’s current URL’s scheme is not an HTTP(S) scheme + } else if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) { + // Return a network error. + response = makeNetworkError('URL scheme must be a HTTP(S) scheme') + + // - request’s use-CORS-preflight flag is set + // - request’s unsafe-request flag is set and either request’s method is + // not a CORS-safelisted method or CORS-unsafe request-header names with + // request’s header list is not empty + // 1. Set request’s response tainting to "cors". + // 2. Let corsWithPreflightResponse be the result of running HTTP fetch + // given fetchParams and true. + // 3. If corsWithPreflightResponse is a network error, then clear cache + // entries using request. + // 4. Return corsWithPreflightResponse. + // TODO + + // Otherwise + } else { + // 1. Set request’s response tainting to "cors". + request.responseTainting = 'cors' + + // 2. Return the result of running HTTP fetch given fetchParams. + response = await httpFetch(fetchParams) + } + } + + // 12. If recursive is true, then return response. + if (recursive) { + return response + } + + // 13. If response is not a network error and response is not a filtered + // response, then: + if (response.status !== 0 && !response.internalResponse) { + // If request’s response tainting is "cors", then: + if (request.responseTainting === 'cors') { + // 1. Let headerNames be the result of extracting header list values + // given `Access-Control-Expose-Headers` and response’s header list. + // TODO + // 2. If request’s credentials mode is not "include" and headerNames + // contains `*`, then set response’s CORS-exposed header-name list to + // all unique header names in response’s header list. + // TODO + // 3. Otherwise, if headerNames is not null or failure, then set + // response’s CORS-exposed header-name list to headerNames. + // TODO + } + + // Set response to the following filtered response with response as its + // internal response, depending on request’s response tainting: + if (request.responseTainting === 'basic') { + response = filterResponse(response, 'basic') + } else if (request.responseTainting === 'cors') { + response = filterResponse(response, 'cors') + } else if (request.responseTainting === 'opaque') { + response = filterResponse(response, 'opaque') + } else { + assert(false) + } + } + + // 14. Let internalResponse be response, if response is a network error, + // and response’s internal response otherwise. + let internalResponse = + response.status === 0 ? response : response.internalResponse + + // 15. If internalResponse’s URL list is empty, then set it to a clone of + // request’s URL list. + if (internalResponse.urlList.length === 0) { + internalResponse.urlList.push(...request.urlList) + } + + // 16. If request’s timing allow failed flag is unset, then set + // internalResponse’s timing allow passed flag. + if (!request.timingAllowFailed) { + response.timingAllowPassed = true + } + + // 17. If response is not a network error and any of the following returns + // blocked + // - should internalResponse to request be blocked as mixed content + // - should internalResponse to request be blocked by Content Security Policy + // - should internalResponse to request be blocked due to its MIME type + // - should internalResponse to request be blocked due to nosniff + // TODO + + // 18. If response’s type is "opaque", internalResponse’s status is 206, + // internalResponse’s range-requested flag is set, and request’s header + // list does not contain `Range`, then set response and internalResponse + // to a network error. + if ( + response.type === 'opaque' && + internalResponse.status === 206 && + internalResponse.rangeRequested && + !request.headers.contains('range', true) + ) { + response = internalResponse = makeNetworkError() + } + + // 19. If response is not a network error and either request’s method is + // `HEAD` or `CONNECT`, or internalResponse’s status is a null body status, + // set internalResponse’s body to null and disregard any enqueuing toward + // it (if any). + if ( + response.status !== 0 && + (request.method === 'HEAD' || + request.method === 'CONNECT' || + nullBodyStatus.includes(internalResponse.status)) + ) { + internalResponse.body = null + fetchParams.controller.dump = true + } + + // 20. If request’s integrity metadata is not the empty string, then: + if (request.integrity) { + // 1. Let processBodyError be this step: run fetch finale given fetchParams + // and a network error. + const processBodyError = (reason) => + fetchFinale(fetchParams, makeNetworkError(reason)) + + // 2. If request’s response tainting is "opaque", or response’s body is null, + // then run processBodyError and abort these steps. + if (request.responseTainting === 'opaque' || response.body == null) { + processBodyError(response.error) + return + } + + // 3. Let processBody given bytes be these steps: + const processBody = (bytes) => { + // 1. If bytes do not match request’s integrity metadata, + // then run processBodyError and abort these steps. [SRI] + if (!bytesMatch(bytes, request.integrity)) { + processBodyError('integrity mismatch') + return + } + + // 2. Set response’s body to bytes as a body. + response.body = safelyExtractBody(bytes)[0] + + // 3. Run fetch finale given fetchParams and response. + fetchFinale(fetchParams, response) + } + + // 4. Fully read response’s body given processBody and processBodyError. + fullyReadBody(response.body, processBody, processBodyError) + } else { + // 21. Otherwise, run fetch finale given fetchParams and response. + fetchFinale(fetchParams, response) + } + } catch (err) { + fetchParams.controller.terminate(err) + } +} + +// https://fetch.spec.whatwg.org/#concept-scheme-fetch +// given a fetch params fetchParams +function schemeFetch (fetchParams) { + // Note: since the connection is destroyed on redirect, which sets fetchParams to a + // cancelled state, we do not want this condition to trigger *unless* there have been + // no redirects. See https://github.com/nodejs/undici/issues/1776 + // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) { + return Promise.resolve(makeAppropriateNetworkError(fetchParams)) + } + + // 2. Let request be fetchParams’s request. + const { request } = fetchParams + + const { protocol: scheme } = requestCurrentURL(request) + + // 3. Switch on request’s current URL’s scheme and run the associated steps: + switch (scheme) { + case 'about:': { + // If request’s current URL’s path is the string "blank", then return a new response + // whose status message is `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) », + // and body is the empty byte sequence as a body. + + // Otherwise, return a network error. + return Promise.resolve(makeNetworkError('about scheme is not supported')) + } + case 'blob:': { + if (!resolveObjectURL) { + resolveObjectURL = require('node:buffer').resolveObjectURL + } + + // 1. Let blobURLEntry be request’s current URL’s blob URL entry. + const blobURLEntry = requestCurrentURL(request) + + // https://github.com/web-platform-tests/wpt/blob/7b0ebaccc62b566a1965396e5be7bb2bc06f841f/FileAPI/url/resources/fetch-tests.js#L52-L56 + // Buffer.resolveObjectURL does not ignore URL queries. + if (blobURLEntry.search.length !== 0) { + return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.')) + } + + const blob = resolveObjectURL(blobURLEntry.toString()) + + // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s + // object is not a Blob object, then return a network error. + if (request.method !== 'GET' || !webidl.is.Blob(blob)) { + return Promise.resolve(makeNetworkError('invalid method')) + } + + // 3. Let blob be blobURLEntry’s object. + // Note: done above + + // 4. Let response be a new response. + const response = makeResponse() + + // 5. Let fullLength be blob’s size. + const fullLength = blob.size + + // 6. Let serializedFullLength be fullLength, serialized and isomorphic encoded. + const serializedFullLength = isomorphicEncode(`${fullLength}`) + + // 7. Let type be blob’s type. + const type = blob.type + + // 8. If request’s header list does not contain `Range`: + // 9. Otherwise: + if (!request.headersList.contains('range', true)) { + // 1. Let bodyWithType be the result of safely extracting blob. + // Note: in the FileAPI a blob "object" is a Blob *or* a MediaSource. + // In node, this can only ever be a Blob. Therefore we can safely + // use extractBody directly. + const bodyWithType = extractBody(blob) + + // 2. Set response’s status message to `OK`. + response.statusText = 'OK' + + // 3. Set response’s body to bodyWithType’s body. + response.body = bodyWithType[0] + + // 4. Set response’s header list to « (`Content-Length`, serializedFullLength), (`Content-Type`, type) ». + response.headersList.set('content-length', serializedFullLength, true) + response.headersList.set('content-type', type, true) + } else { + // 1. Set response’s range-requested flag. + response.rangeRequested = true + + // 2. Let rangeHeader be the result of getting `Range` from request’s header list. + const rangeHeader = request.headersList.get('range', true) + + // 3. Let rangeValue be the result of parsing a single range header value given rangeHeader and true. + const rangeValue = simpleRangeHeaderValue(rangeHeader, true) + + // 4. If rangeValue is failure, then return a network error. + if (rangeValue === 'failure') { + return Promise.resolve(makeNetworkError('failed to fetch the data URL')) + } + + // 5. Let (rangeStart, rangeEnd) be rangeValue. + let { rangeStartValue: rangeStart, rangeEndValue: rangeEnd } = rangeValue + + // 6. If rangeStart is null: + // 7. Otherwise: + if (rangeStart === null) { + // 1. Set rangeStart to fullLength − rangeEnd. + rangeStart = fullLength - rangeEnd + + // 2. Set rangeEnd to rangeStart + rangeEnd − 1. + rangeEnd = rangeStart + rangeEnd - 1 + } else { + // 1. If rangeStart is greater than or equal to fullLength, then return a network error. + if (rangeStart >= fullLength) { + return Promise.resolve(makeNetworkError('Range start is greater than the blob\'s size.')) + } + + // 2. If rangeEnd is null or rangeEnd is greater than or equal to fullLength, then set + // rangeEnd to fullLength − 1. + if (rangeEnd === null || rangeEnd >= fullLength) { + rangeEnd = fullLength - 1 + } + } + + // 8. Let slicedBlob be the result of invoking slice blob given blob, rangeStart, + // rangeEnd + 1, and type. + const slicedBlob = blob.slice(rangeStart, rangeEnd, type) + + // 9. Let slicedBodyWithType be the result of safely extracting slicedBlob. + // Note: same reason as mentioned above as to why we use extractBody + const slicedBodyWithType = extractBody(slicedBlob) + + // 10. Set response’s body to slicedBodyWithType’s body. + response.body = slicedBodyWithType[0] + + // 11. Let serializedSlicedLength be slicedBlob’s size, serialized and isomorphic encoded. + const serializedSlicedLength = isomorphicEncode(`${slicedBlob.size}`) + + // 12. Let contentRange be the result of invoking build a content range given rangeStart, + // rangeEnd, and fullLength. + const contentRange = buildContentRange(rangeStart, rangeEnd, fullLength) + + // 13. Set response’s status to 206. + response.status = 206 + + // 14. Set response’s status message to `Partial Content`. + response.statusText = 'Partial Content' + + // 15. Set response’s header list to « (`Content-Length`, serializedSlicedLength), + // (`Content-Type`, type), (`Content-Range`, contentRange) ». + response.headersList.set('content-length', serializedSlicedLength, true) + response.headersList.set('content-type', type, true) + response.headersList.set('content-range', contentRange, true) + } + + // 10. Return response. + return Promise.resolve(response) + } + case 'data:': { + // 1. Let dataURLStruct be the result of running the + // data: URL processor on request’s current URL. + const currentURL = requestCurrentURL(request) + const dataURLStruct = dataURLProcessor(currentURL) + + // 2. If dataURLStruct is failure, then return a + // network error. + if (dataURLStruct === 'failure') { + return Promise.resolve(makeNetworkError('failed to fetch the data URL')) + } + + // 3. Let mimeType be dataURLStruct’s MIME type, serialized. + const mimeType = serializeAMimeType(dataURLStruct.mimeType) + + // 4. Return a response whose status message is `OK`, + // header list is « (`Content-Type`, mimeType) », + // and body is dataURLStruct’s body as a body. + return Promise.resolve(makeResponse({ + statusText: 'OK', + headersList: [ + ['content-type', { name: 'Content-Type', value: mimeType }] + ], + body: safelyExtractBody(dataURLStruct.body)[0] + })) + } + case 'file:': { + // For now, unfortunate as it is, file URLs are left as an exercise for the reader. + // When in doubt, return a network error. + return Promise.resolve(makeNetworkError('not implemented... yet...')) + } + case 'http:': + case 'https:': { + // Return the result of running HTTP fetch given fetchParams. + + return httpFetch(fetchParams) + .catch((err) => makeNetworkError(err)) + } + default: { + return Promise.resolve(makeNetworkError('unknown scheme')) + } + } +} + +// https://fetch.spec.whatwg.org/#finalize-response +function finalizeResponse (fetchParams, response) { + // 1. Set fetchParams’s request’s done flag. + fetchParams.request.done = true + + // 2, If fetchParams’s process response done is not null, then queue a fetch + // task to run fetchParams’s process response done given response, with + // fetchParams’s task destination. + if (fetchParams.processResponseDone != null) { + queueMicrotask(() => fetchParams.processResponseDone(response)) + } +} + +// https://fetch.spec.whatwg.org/#fetch-finale +function fetchFinale (fetchParams, response) { + // 1. Let timingInfo be fetchParams’s timing info. + let timingInfo = fetchParams.timingInfo + + // 2. If response is not a network error and fetchParams’s request’s client is a secure context, + // then set timingInfo’s server-timing headers to the result of getting, decoding, and splitting + // `Server-Timing` from response’s internal response’s header list. + // TODO + + // 3. Let processResponseEndOfBody be the following steps: + const processResponseEndOfBody = () => { + // 1. Let unsafeEndTime be the unsafe shared current time. + const unsafeEndTime = Date.now() // ? + + // 2. If fetchParams’s request’s destination is "document", then set fetchParams’s controller’s + // full timing info to fetchParams’s timing info. + if (fetchParams.request.destination === 'document') { + fetchParams.controller.fullTimingInfo = timingInfo + } + + // 3. Set fetchParams’s controller’s report timing steps to the following steps given a global object global: + fetchParams.controller.reportTimingSteps = () => { + // 1. If fetchParams’s request’s URL’s scheme is not an HTTP(S) scheme, then return. + if (!urlIsHttpHttpsScheme(fetchParams.request.url)) { + return + } + + // 2. Set timingInfo’s end time to the relative high resolution time given unsafeEndTime and global. + timingInfo.endTime = unsafeEndTime + + // 3. Let cacheState be response’s cache state. + let cacheState = response.cacheState + + // 4. Let bodyInfo be response’s body info. + const bodyInfo = response.bodyInfo + + // 5. If response’s timing allow passed flag is not set, then set timingInfo to the result of creating an + // opaque timing info for timingInfo and set cacheState to the empty string. + if (!response.timingAllowPassed) { + timingInfo = createOpaqueTimingInfo(timingInfo) + + cacheState = '' + } + + // 6. Let responseStatus be 0. + let responseStatus = 0 + + // 7. If fetchParams’s request’s mode is not "navigate" or response’s has-cross-origin-redirects is false: + if (fetchParams.request.mode !== 'navigator' || !response.hasCrossOriginRedirects) { + // 1. Set responseStatus to response’s status. + responseStatus = response.status + + // 2. Let mimeType be the result of extracting a MIME type from response’s header list. + const mimeType = extractMimeType(response.headersList) + + // 3. If mimeType is not failure, then set bodyInfo’s content type to the result of minimizing a supported MIME type given mimeType. + if (mimeType !== 'failure') { + bodyInfo.contentType = minimizeSupportedMimeType(mimeType) + } + } + + // 8. If fetchParams’s request’s initiator type is non-null, then mark resource timing given timingInfo, + // fetchParams’s request’s URL, fetchParams’s request’s initiator type, global, cacheState, bodyInfo, + // and responseStatus. + if (fetchParams.request.initiatorType != null) { + markResourceTiming(timingInfo, fetchParams.request.url.href, fetchParams.request.initiatorType, globalThis, cacheState, bodyInfo, responseStatus) + } + } + + // 4. Let processResponseEndOfBodyTask be the following steps: + const processResponseEndOfBodyTask = () => { + // 1. Set fetchParams’s request’s done flag. + fetchParams.request.done = true + + // 2. If fetchParams’s process response end-of-body is non-null, then run fetchParams’s process + // response end-of-body given response. + if (fetchParams.processResponseEndOfBody != null) { + queueMicrotask(() => fetchParams.processResponseEndOfBody(response)) + } + + // 3. If fetchParams’s request’s initiator type is non-null and fetchParams’s request’s client’s + // global object is fetchParams’s task destination, then run fetchParams’s controller’s report + // timing steps given fetchParams’s request’s client’s global object. + if (fetchParams.request.initiatorType != null) { + fetchParams.controller.reportTimingSteps() + } + } + + // 5. Queue a fetch task to run processResponseEndOfBodyTask with fetchParams’s task destination + queueMicrotask(() => processResponseEndOfBodyTask()) + } + + // 4. If fetchParams’s process response is non-null, then queue a fetch task to run fetchParams’s + // process response given response, with fetchParams’s task destination. + if (fetchParams.processResponse != null) { + queueMicrotask(() => { + fetchParams.processResponse(response) + fetchParams.processResponse = null + }) + } + + // 5. Let internalResponse be response, if response is a network error; otherwise response’s internal response. + const internalResponse = response.type === 'error' ? response : (response.internalResponse ?? response) + + // 6. If internalResponse’s body is null, then run processResponseEndOfBody. + // 7. Otherwise: + if (internalResponse.body == null) { + processResponseEndOfBody() + } else { + // mcollina: all the following steps of the specs are skipped. + // The internal transform stream is not needed. + // See https://github.com/nodejs/undici/pull/3093#issuecomment-2050198541 + + // 1. Let transformStream be a new TransformStream. + // 2. Let identityTransformAlgorithm be an algorithm which, given chunk, enqueues chunk in transformStream. + // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm and flushAlgorithm + // set to processResponseEndOfBody. + // 4. Set internalResponse’s body’s stream to the result of internalResponse’s body’s stream piped through transformStream. + + finished(internalResponse.body.stream, () => { + processResponseEndOfBody() + }) + } +} + +// https://fetch.spec.whatwg.org/#http-fetch +async function httpFetch (fetchParams) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let response be null. + let response = null + + // 3. Let actualResponse be null. + let actualResponse = null + + // 4. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo + + // 5. If request’s service-workers mode is "all", then: + if (request.serviceWorkers === 'all') { + // TODO + } + + // 6. If response is null, then: + if (response === null) { + // 1. If makeCORSPreflight is true and one of these conditions is true: + // TODO + + // 2. If request’s redirect mode is "follow", then set request’s + // service-workers mode to "none". + if (request.redirect === 'follow') { + request.serviceWorkers = 'none' + } + + // 3. Set response and actualResponse to the result of running + // HTTP-network-or-cache fetch given fetchParams. + actualResponse = response = await httpNetworkOrCacheFetch(fetchParams) + + // 4. If request’s response tainting is "cors" and a CORS check + // for request and response returns failure, then return a network error. + if ( + request.responseTainting === 'cors' && + corsCheck(request, response) === 'failure' + ) { + return makeNetworkError('cors failure') + } + + // 5. If the TAO check for request and response returns failure, then set + // request’s timing allow failed flag. + if (TAOCheck(request, response) === 'failure') { + request.timingAllowFailed = true + } + } + + // 7. If either request’s response tainting or response’s type + // is "opaque", and the cross-origin resource policy check with + // request’s origin, request’s client, request’s destination, + // and actualResponse returns blocked, then return a network error. + if ( + (request.responseTainting === 'opaque' || response.type === 'opaque') && + crossOriginResourcePolicyCheck( + request.origin, + request.client, + request.destination, + actualResponse + ) === 'blocked' + ) { + return makeNetworkError('blocked') + } + + // 8. If actualResponse’s status is a redirect status, then: + if (redirectStatusSet.has(actualResponse.status)) { + // 1. If actualResponse’s status is not 303, request’s body is not null, + // and the connection uses HTTP/2, then user agents may, and are even + // encouraged to, transmit an RST_STREAM frame. + // See, https://github.com/whatwg/fetch/issues/1288 + if (request.redirect !== 'manual') { + fetchParams.controller.connection.destroy(undefined, false) + } + + // 2. Switch on request’s redirect mode: + if (request.redirect === 'error') { + // Set response to a network error. + response = makeNetworkError('unexpected redirect') + } else if (request.redirect === 'manual') { + // Set response to an opaque-redirect filtered response whose internal + // response is actualResponse. + // NOTE(spec): On the web this would return an `opaqueredirect` response, + // but that doesn't make sense server side. + // See https://github.com/nodejs/undici/issues/1193. + response = actualResponse + } else if (request.redirect === 'follow') { + // Set response to the result of running HTTP-redirect fetch given + // fetchParams and response. + response = await httpRedirectFetch(fetchParams, response) + } else { + assert(false) + } + } + + // 9. Set response’s timing info to timingInfo. + response.timingInfo = timingInfo + + // 10. Return response. + return response +} + +// https://fetch.spec.whatwg.org/#http-redirect-fetch +function httpRedirectFetch (fetchParams, response) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let actualResponse be response, if response is not a filtered response, + // and response’s internal response otherwise. + const actualResponse = response.internalResponse + ? response.internalResponse + : response + + // 3. Let locationURL be actualResponse’s location URL given request’s current + // URL’s fragment. + let locationURL + + try { + locationURL = responseLocationURL( + actualResponse, + requestCurrentURL(request).hash + ) + + // 4. If locationURL is null, then return response. + if (locationURL == null) { + return response + } + } catch (err) { + // 5. If locationURL is failure, then return a network error. + return Promise.resolve(makeNetworkError(err)) + } + + // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network + // error. + if (!urlIsHttpHttpsScheme(locationURL)) { + return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme')) + } + + // 7. If request’s redirect count is 20, then return a network error. + if (request.redirectCount === 20) { + return Promise.resolve(makeNetworkError('redirect count exceeded')) + } + + // 8. Increase request’s redirect count by 1. + request.redirectCount += 1 + + // 9. If request’s mode is "cors", locationURL includes credentials, and + // request’s origin is not same origin with locationURL’s origin, then return + // a network error. + if ( + request.mode === 'cors' && + (locationURL.username || locationURL.password) && + !sameOrigin(request, locationURL) + ) { + return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"')) + } + + // 10. If request’s response tainting is "cors" and locationURL includes + // credentials, then return a network error. + if ( + request.responseTainting === 'cors' && + (locationURL.username || locationURL.password) + ) { + return Promise.resolve(makeNetworkError( + 'URL cannot contain credentials for request mode "cors"' + )) + } + + // 11. If actualResponse’s status is not 303, request’s body is non-null, + // and request’s body’s source is null, then return a network error. + if ( + actualResponse.status !== 303 && + request.body != null && + request.body.source == null + ) { + return Promise.resolve(makeNetworkError()) + } + + // 12. If one of the following is true + // - actualResponse’s status is 301 or 302 and request’s method is `POST` + // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD` + if ( + ([301, 302].includes(actualResponse.status) && request.method === 'POST') || + (actualResponse.status === 303 && + !GET_OR_HEAD.includes(request.method)) + ) { + // then: + // 1. Set request’s method to `GET` and request’s body to null. + request.method = 'GET' + request.body = null + + // 2. For each headerName of request-body-header name, delete headerName from + // request’s header list. + for (const headerName of requestBodyHeader) { + request.headersList.delete(headerName) + } + } + + // 13. If request’s current URL’s origin is not same origin with locationURL’s + // origin, then for each headerName of CORS non-wildcard request-header name, + // delete headerName from request’s header list. + if (!sameOrigin(requestCurrentURL(request), locationURL)) { + // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name + request.headersList.delete('authorization', true) + + // https://fetch.spec.whatwg.org/#authentication-entries + request.headersList.delete('proxy-authorization', true) + + // "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement. + request.headersList.delete('cookie', true) + request.headersList.delete('host', true) + } + + // 14. If request’s body is non-null, then set request’s body to the first return + // value of safely extracting request’s body’s source. + if (request.body != null) { + assert(request.body.source != null) + request.body = safelyExtractBody(request.body.source)[0] + } + + // 15. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo + + // 16. Set timingInfo’s redirect end time and post-redirect start time to the + // coarsened shared current time given fetchParams’s cross-origin isolated + // capability. + timingInfo.redirectEndTime = timingInfo.postRedirectStartTime = + coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability) + + // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s + // redirect start time to timingInfo’s start time. + if (timingInfo.redirectStartTime === 0) { + timingInfo.redirectStartTime = timingInfo.startTime + } + + // 18. Append locationURL to request’s URL list. + request.urlList.push(locationURL) + + // 19. Invoke set request’s referrer policy on redirect on request and + // actualResponse. + setRequestReferrerPolicyOnRedirect(request, actualResponse) + + // 20. Return the result of running main fetch given fetchParams and true. + return mainFetch(fetchParams, true) +} + +// https://fetch.spec.whatwg.org/#http-network-or-cache-fetch +async function httpNetworkOrCacheFetch ( + fetchParams, + isAuthenticationFetch = false, + isNewConnectionFetch = false +) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let httpFetchParams be null. + let httpFetchParams = null + + // 3. Let httpRequest be null. + let httpRequest = null + + // 4. Let response be null. + let response = null + + // 5. Let storedResponse be null. + // TODO: cache + + // 6. Let httpCache be null. + const httpCache = null + + // 7. Let the revalidatingFlag be unset. + const revalidatingFlag = false + + // 8. Run these steps, but abort when the ongoing fetch is terminated: + + // 1. If request’s window is "no-window" and request’s redirect mode is + // "error", then set httpFetchParams to fetchParams and httpRequest to + // request. + if (request.window === 'no-window' && request.redirect === 'error') { + httpFetchParams = fetchParams + httpRequest = request + } else { + // Otherwise: + + // 1. Set httpRequest to a clone of request. + httpRequest = cloneRequest(request) + + // 2. Set httpFetchParams to a copy of fetchParams. + httpFetchParams = { ...fetchParams } + + // 3. Set httpFetchParams’s request to httpRequest. + httpFetchParams.request = httpRequest + } + + // 3. Let includeCredentials be true if one of + const includeCredentials = + request.credentials === 'include' || + (request.credentials === 'same-origin' && + request.responseTainting === 'basic') + + // 4. Let contentLength be httpRequest’s body’s length, if httpRequest’s + // body is non-null; otherwise null. + const contentLength = httpRequest.body ? httpRequest.body.length : null + + // 5. Let contentLengthHeaderValue be null. + let contentLengthHeaderValue = null + + // 6. If httpRequest’s body is null and httpRequest’s method is `POST` or + // `PUT`, then set contentLengthHeaderValue to `0`. + if ( + httpRequest.body == null && + ['POST', 'PUT'].includes(httpRequest.method) + ) { + contentLengthHeaderValue = '0' + } + + // 7. If contentLength is non-null, then set contentLengthHeaderValue to + // contentLength, serialized and isomorphic encoded. + if (contentLength != null) { + contentLengthHeaderValue = isomorphicEncode(`${contentLength}`) + } + + // 8. If contentLengthHeaderValue is non-null, then append + // `Content-Length`/contentLengthHeaderValue to httpRequest’s header + // list. + if (contentLengthHeaderValue != null) { + httpRequest.headersList.append('content-length', contentLengthHeaderValue, true) + } + + // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`, + // contentLengthHeaderValue) to httpRequest’s header list. + + // 10. If contentLength is non-null and httpRequest’s keepalive is true, + // then: + if (contentLength != null && httpRequest.keepalive) { + // NOTE: keepalive is a noop outside of browser context. + } + + // 11. If httpRequest’s referrer is a URL, then append + // `Referer`/httpRequest’s referrer, serialized and isomorphic encoded, + // to httpRequest’s header list. + if (webidl.is.URL(httpRequest.referrer)) { + httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href), true) + } + + // 12. Append a request `Origin` header for httpRequest. + appendRequestOriginHeader(httpRequest) + + // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA] + appendFetchMetadata(httpRequest) + + // 14. If httpRequest’s header list does not contain `User-Agent`, then + // user agents should append `User-Agent`/default `User-Agent` value to + // httpRequest’s header list. + if (!httpRequest.headersList.contains('user-agent', true)) { + httpRequest.headersList.append('user-agent', defaultUserAgent, true) + } + + // 15. If httpRequest’s cache mode is "default" and httpRequest’s header + // list contains `If-Modified-Since`, `If-None-Match`, + // `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set + // httpRequest’s cache mode to "no-store". + if ( + httpRequest.cache === 'default' && + (httpRequest.headersList.contains('if-modified-since', true) || + httpRequest.headersList.contains('if-none-match', true) || + httpRequest.headersList.contains('if-unmodified-since', true) || + httpRequest.headersList.contains('if-match', true) || + httpRequest.headersList.contains('if-range', true)) + ) { + httpRequest.cache = 'no-store' + } + + // 16. If httpRequest’s cache mode is "no-cache", httpRequest’s prevent + // no-cache cache-control header modification flag is unset, and + // httpRequest’s header list does not contain `Cache-Control`, then append + // `Cache-Control`/`max-age=0` to httpRequest’s header list. + if ( + httpRequest.cache === 'no-cache' && + !httpRequest.preventNoCacheCacheControlHeaderModification && + !httpRequest.headersList.contains('cache-control', true) + ) { + httpRequest.headersList.append('cache-control', 'max-age=0', true) + } + + // 17. If httpRequest’s cache mode is "no-store" or "reload", then: + if (httpRequest.cache === 'no-store' || httpRequest.cache === 'reload') { + // 1. If httpRequest’s header list does not contain `Pragma`, then append + // `Pragma`/`no-cache` to httpRequest’s header list. + if (!httpRequest.headersList.contains('pragma', true)) { + httpRequest.headersList.append('pragma', 'no-cache', true) + } + + // 2. If httpRequest’s header list does not contain `Cache-Control`, + // then append `Cache-Control`/`no-cache` to httpRequest’s header list. + if (!httpRequest.headersList.contains('cache-control', true)) { + httpRequest.headersList.append('cache-control', 'no-cache', true) + } + } + + // 18. If httpRequest’s header list contains `Range`, then append + // `Accept-Encoding`/`identity` to httpRequest’s header list. + if (httpRequest.headersList.contains('range', true)) { + httpRequest.headersList.append('accept-encoding', 'identity', true) + } + + // 19. Modify httpRequest’s header list per HTTP. Do not append a given + // header if httpRequest’s header list contains that header’s name. + // TODO: https://github.com/whatwg/fetch/issues/1285#issuecomment-896560129 + if (!httpRequest.headersList.contains('accept-encoding', true)) { + if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) { + httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate', true) + } else { + httpRequest.headersList.append('accept-encoding', 'gzip, deflate', true) + } + } + + httpRequest.headersList.delete('host', true) + + // 20. If includeCredentials is true, then: + if (includeCredentials) { + // 1. If the user agent is not configured to block cookies for httpRequest + // (see section 7 of [COOKIES]), then: + // TODO: credentials + // 2. If httpRequest’s header list does not contain `Authorization`, then: + // TODO: credentials + } + + // 21. If there’s a proxy-authentication entry, use it as appropriate. + // TODO: proxy-authentication + + // 22. Set httpCache to the result of determining the HTTP cache + // partition, given httpRequest. + // TODO: cache + + // 23. If httpCache is null, then set httpRequest’s cache mode to + // "no-store". + if (httpCache == null) { + httpRequest.cache = 'no-store' + } + + // 24. If httpRequest’s cache mode is neither "no-store" nor "reload", + // then: + if (httpRequest.cache !== 'no-store' && httpRequest.cache !== 'reload') { + // TODO: cache + } + + // 9. If aborted, then return the appropriate network error for fetchParams. + // TODO + + // 10. If response is null, then: + if (response == null) { + // 1. If httpRequest’s cache mode is "only-if-cached", then return a + // network error. + if (httpRequest.cache === 'only-if-cached') { + return makeNetworkError('only if cached') + } + + // 2. Let forwardResponse be the result of running HTTP-network fetch + // given httpFetchParams, includeCredentials, and isNewConnectionFetch. + const forwardResponse = await httpNetworkFetch( + httpFetchParams, + includeCredentials, + isNewConnectionFetch + ) + + // 3. If httpRequest’s method is unsafe and forwardResponse’s status is + // in the range 200 to 399, inclusive, invalidate appropriate stored + // responses in httpCache, as per the "Invalidation" chapter of HTTP + // Caching, and set storedResponse to null. [HTTP-CACHING] + if ( + !safeMethodsSet.has(httpRequest.method) && + forwardResponse.status >= 200 && + forwardResponse.status <= 399 + ) { + // TODO: cache + } + + // 4. If the revalidatingFlag is set and forwardResponse’s status is 304, + // then: + if (revalidatingFlag && forwardResponse.status === 304) { + // TODO: cache + } + + // 5. If response is null, then: + if (response == null) { + // 1. Set response to forwardResponse. + response = forwardResponse + + // 2. Store httpRequest and forwardResponse in httpCache, as per the + // "Storing Responses in Caches" chapter of HTTP Caching. [HTTP-CACHING] + // TODO: cache + } + } + + // 11. Set response’s URL list to a clone of httpRequest’s URL list. + response.urlList = [...httpRequest.urlList] + + // 12. If httpRequest’s header list contains `Range`, then set response’s + // range-requested flag. + if (httpRequest.headersList.contains('range', true)) { + response.rangeRequested = true + } + + // 13. Set response’s request-includes-credentials to includeCredentials. + response.requestIncludesCredentials = includeCredentials + + // 14. If response’s status is 401, httpRequest’s response tainting is not + // "cors", includeCredentials is true, and request’s window is an environment + // settings object, then: + // TODO + + // 15. If response’s status is 407, then: + if (response.status === 407) { + // 1. If request’s window is "no-window", then return a network error. + if (request.window === 'no-window') { + return makeNetworkError() + } + + // 2. ??? + + // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams)) { + return makeAppropriateNetworkError(fetchParams) + } + + // 4. Prompt the end user as appropriate in request’s window and store + // the result as a proxy-authentication entry. [HTTP-AUTH] + // TODO: Invoke some kind of callback? + + // 5. Set response to the result of running HTTP-network-or-cache fetch given + // fetchParams. + // TODO + return makeNetworkError('proxy authentication required') + } + + // 16. If all of the following are true + if ( + // response’s status is 421 + response.status === 421 && + // isNewConnectionFetch is false + !isNewConnectionFetch && + // request’s body is null, or request’s body is non-null and request’s body’s source is non-null + (request.body == null || request.body.source != null) + ) { + // then: + + // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams)) { + return makeAppropriateNetworkError(fetchParams) + } + + // 2. Set response to the result of running HTTP-network-or-cache + // fetch given fetchParams, isAuthenticationFetch, and true. + + // TODO (spec): The spec doesn't specify this but we need to cancel + // the active response before we can start a new one. + // https://github.com/whatwg/fetch/issues/1293 + fetchParams.controller.connection.destroy() + + response = await httpNetworkOrCacheFetch( + fetchParams, + isAuthenticationFetch, + true + ) + } + + // 17. If isAuthenticationFetch is true, then create an authentication entry + if (isAuthenticationFetch) { + // TODO + } + + // 18. Return response. + return response +} + +// https://fetch.spec.whatwg.org/#http-network-fetch +async function httpNetworkFetch ( + fetchParams, + includeCredentials = false, + forceNewConnection = false +) { + assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed) + + fetchParams.controller.connection = { + abort: null, + destroyed: false, + destroy (err, abort = true) { + if (!this.destroyed) { + this.destroyed = true + if (abort) { + this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError')) + } + } + } + } + + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let response be null. + let response = null + + // 3. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo + + // 4. Let httpCache be the result of determining the HTTP cache partition, + // given request. + // TODO: cache + const httpCache = null + + // 5. If httpCache is null, then set request’s cache mode to "no-store". + if (httpCache == null) { + request.cache = 'no-store' + } + + // 6. Let networkPartitionKey be the result of determining the network + // partition key given request. + // TODO + + // 7. Let newConnection be "yes" if forceNewConnection is true; otherwise + // "no". + const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars + + // 8. Switch on request’s mode: + if (request.mode === 'websocket') { + // Let connection be the result of obtaining a WebSocket connection, + // given request’s current URL. + // TODO + } else { + // Let connection be the result of obtaining a connection, given + // networkPartitionKey, request’s current URL’s origin, + // includeCredentials, and forceNewConnection. + // TODO + } + + // 9. Run these steps, but abort when the ongoing fetch is terminated: + + // 1. If connection is failure, then return a network error. + + // 2. Set timingInfo’s final connection timing info to the result of + // calling clamp and coarsen connection timing info with connection’s + // timing info, timingInfo’s post-redirect start time, and fetchParams’s + // cross-origin isolated capability. + + // 3. If connection is not an HTTP/2 connection, request’s body is non-null, + // and request’s body’s source is null, then append (`Transfer-Encoding`, + // `chunked`) to request’s header list. + + // 4. Set timingInfo’s final network-request start time to the coarsened + // shared current time given fetchParams’s cross-origin isolated + // capability. + + // 5. Set response to the result of making an HTTP request over connection + // using request with the following caveats: + + // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS] + // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH] + + // - If request’s body is non-null, and request’s body’s source is null, + // then the user agent may have a buffer of up to 64 kibibytes and store + // a part of request’s body in that buffer. If the user agent reads from + // request’s body beyond that buffer’s size and the user agent needs to + // resend request, then instead return a network error. + + // - Set timingInfo’s final network-response start time to the coarsened + // shared current time given fetchParams’s cross-origin isolated capability, + // immediately after the user agent’s HTTP parser receives the first byte + // of the response (e.g., frame header bytes for HTTP/2 or response status + // line for HTTP/1.x). + + // - Wait until all the headers are transmitted. + + // - Any responses whose status is in the range 100 to 199, inclusive, + // and is not 101, are to be ignored, except for the purposes of setting + // timingInfo’s final network-response start time above. + + // - If request’s header list contains `Transfer-Encoding`/`chunked` and + // response is transferred via HTTP/1.0 or older, then return a network + // error. + + // - If the HTTP request results in a TLS client certificate dialog, then: + + // 1. If request’s window is an environment settings object, make the + // dialog available in request’s window. + + // 2. Otherwise, return a network error. + + // To transmit request’s body body, run these steps: + let requestBody = null + // 1. If body is null and fetchParams’s process request end-of-body is + // non-null, then queue a fetch task given fetchParams’s process request + // end-of-body and fetchParams’s task destination. + if (request.body == null && fetchParams.processRequestEndOfBody) { + queueMicrotask(() => fetchParams.processRequestEndOfBody()) + } else if (request.body != null) { + // 2. Otherwise, if body is non-null: + + // 1. Let processBodyChunk given bytes be these steps: + const processBodyChunk = async function * (bytes) { + // 1. If the ongoing fetch is terminated, then abort these steps. + if (isCancelled(fetchParams)) { + return + } + + // 2. Run this step in parallel: transmit bytes. + yield bytes + + // 3. If fetchParams’s process request body is non-null, then run + // fetchParams’s process request body given bytes’s length. + fetchParams.processRequestBodyChunkLength?.(bytes.byteLength) + } + + // 2. Let processEndOfBody be these steps: + const processEndOfBody = () => { + // 1. If fetchParams is canceled, then abort these steps. + if (isCancelled(fetchParams)) { + return + } + + // 2. If fetchParams’s process request end-of-body is non-null, + // then run fetchParams’s process request end-of-body. + if (fetchParams.processRequestEndOfBody) { + fetchParams.processRequestEndOfBody() + } + } + + // 3. Let processBodyError given e be these steps: + const processBodyError = (e) => { + // 1. If fetchParams is canceled, then abort these steps. + if (isCancelled(fetchParams)) { + return + } + + // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller. + if (e.name === 'AbortError') { + fetchParams.controller.abort() + } else { + fetchParams.controller.terminate(e) + } + } + + // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody, + // processBodyError, and fetchParams’s task destination. + requestBody = (async function * () { + try { + for await (const bytes of request.body.stream) { + yield * processBodyChunk(bytes) + } + processEndOfBody() + } catch (err) { + processBodyError(err) + } + })() + } + + try { + // socket is only provided for websockets + const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody }) + + if (socket) { + response = makeResponse({ status, statusText, headersList, socket }) + } else { + const iterator = body[Symbol.asyncIterator]() + fetchParams.controller.next = () => iterator.next() + + response = makeResponse({ status, statusText, headersList }) + } + } catch (err) { + // 10. If aborted, then: + if (err.name === 'AbortError') { + // 1. If connection uses HTTP/2, then transmit an RST_STREAM frame. + fetchParams.controller.connection.destroy() + + // 2. Return the appropriate network error for fetchParams. + return makeAppropriateNetworkError(fetchParams, err) + } + + return makeNetworkError(err) + } + + // 11. Let pullAlgorithm be an action that resumes the ongoing fetch + // if it is suspended. + const pullAlgorithm = () => { + return fetchParams.controller.resume() + } + + // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s + // controller with reason, given reason. + const cancelAlgorithm = (reason) => { + // If the aborted fetch was already terminated, then we do not + // need to do anything. + if (!isCancelled(fetchParams)) { + fetchParams.controller.abort(reason) + } + } + + // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by + // the user agent. + // TODO + + // 14. Let sizeAlgorithm be an algorithm that accepts a chunk object + // and returns a non-negative, non-NaN, non-infinite number, chosen by the user agent. + // TODO + + // 15. Let stream be a new ReadableStream. + // 16. Set up stream with byte reading support with pullAlgorithm set to pullAlgorithm, + // cancelAlgorithm set to cancelAlgorithm. + const stream = new ReadableStream( + { + start (controller) { + fetchParams.controller.controller = controller + }, + pull: pullAlgorithm, + cancel: cancelAlgorithm, + type: 'bytes' + } + ) + + // 17. Run these steps, but abort when the ongoing fetch is terminated: + + // 1. Set response’s body to a new body whose stream is stream. + response.body = { stream, source: null, length: null } + + // 2. If response is not a network error and request’s cache mode is + // not "no-store", then update response in httpCache for request. + // TODO + + // 3. If includeCredentials is true and the user agent is not configured + // to block cookies for request (see section 7 of [COOKIES]), then run the + // "set-cookie-string" parsing algorithm (see section 5.2 of [COOKIES]) on + // the value of each header whose name is a byte-case-insensitive match for + // `Set-Cookie` in response’s header list, if any, and request’s current URL. + // TODO + + // 18. If aborted, then: + // TODO + + // 19. Run these steps in parallel: + + // 1. Run these steps, but abort when fetchParams is canceled: + if (!fetchParams.controller.resume) { + fetchParams.controller.on('terminated', onAborted) + } + + fetchParams.controller.resume = async () => { + // 1. While true + while (true) { + // 1-3. See onData... + + // 4. Set bytes to the result of handling content codings given + // codings and bytes. + let bytes + let isFailure + try { + const { done, value } = await fetchParams.controller.next() + + if (isAborted(fetchParams)) { + break + } + + bytes = done ? undefined : value + } catch (err) { + if (fetchParams.controller.ended && !timingInfo.encodedBodySize) { + // zlib doesn't like empty streams. + bytes = undefined + } else { + bytes = err + + // err may be propagated from the result of calling readablestream.cancel, + // which might not be an error. https://github.com/nodejs/undici/issues/2009 + isFailure = true + } + } + + if (bytes === undefined) { + // 2. Otherwise, if the bytes transmission for response’s message + // body is done normally and stream is readable, then close + // stream, finalize response for fetchParams and response, and + // abort these in-parallel steps. + readableStreamClose(fetchParams.controller.controller) + + finalizeResponse(fetchParams, response) + + return + } + + // 5. Increase timingInfo’s decoded body size by bytes’s length. + timingInfo.decodedBodySize += bytes?.byteLength ?? 0 + + // 6. If bytes is failure, then terminate fetchParams’s controller. + if (isFailure) { + fetchParams.controller.terminate(bytes) + return + } + + // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes + // into stream. + const buffer = new Uint8Array(bytes) + if (buffer.byteLength) { + fetchParams.controller.controller.enqueue(buffer) + } + + // 8. If stream is errored, then terminate the ongoing fetch. + if (isErrored(stream)) { + fetchParams.controller.terminate() + return + } + + // 9. If stream doesn’t need more data ask the user agent to suspend + // the ongoing fetch. + if (fetchParams.controller.controller.desiredSize <= 0) { + return + } + } + } + + // 2. If aborted, then: + function onAborted (reason) { + // 2. If fetchParams is aborted, then: + if (isAborted(fetchParams)) { + // 1. Set response’s aborted flag. + response.aborted = true + + // 2. If stream is readable, then error stream with the result of + // deserialize a serialized abort reason given fetchParams’s + // controller’s serialized abort reason and an + // implementation-defined realm. + if (isReadable(stream)) { + fetchParams.controller.controller.error( + fetchParams.controller.serializedAbortReason + ) + } + } else { + // 3. Otherwise, if stream is readable, error stream with a TypeError. + if (isReadable(stream)) { + fetchParams.controller.controller.error(new TypeError('terminated', { + cause: isErrorLike(reason) ? reason : undefined + })) + } + } + + // 4. If connection uses HTTP/2, then transmit an RST_STREAM frame. + // 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so. + fetchParams.controller.connection.destroy() + } + + // 20. Return response. + return response + + function dispatch ({ body }) { + const url = requestCurrentURL(request) + /** @type {import('../../..').Agent} */ + const agent = fetchParams.controller.dispatcher + + return new Promise((resolve, reject) => agent.dispatch( + { + path: url.pathname + url.search, + origin: url.origin, + method: request.method, + body: agent.isMockActive ? request.body && (request.body.source || request.body.stream) : body, + headers: request.headersList.entries, + maxRedirections: 0, + upgrade: request.mode === 'websocket' ? 'websocket' : undefined + }, + { + body: null, + abort: null, + + onConnect (abort) { + // TODO (fix): Do we need connection here? + const { connection } = fetchParams.controller + + // Set timingInfo’s final connection timing info to the result of calling clamp and coarsen + // connection timing info with connection’s timing info, timingInfo’s post-redirect start + // time, and fetchParams’s cross-origin isolated capability. + // TODO: implement connection timing + timingInfo.finalConnectionTimingInfo = clampAndCoarsenConnectionTimingInfo(undefined, timingInfo.postRedirectStartTime, fetchParams.crossOriginIsolatedCapability) + + if (connection.destroyed) { + abort(new DOMException('The operation was aborted.', 'AbortError')) + } else { + fetchParams.controller.on('terminated', abort) + this.abort = connection.abort = abort + } + + // Set timingInfo’s final network-request start time to the coarsened shared current time given + // fetchParams’s cross-origin isolated capability. + timingInfo.finalNetworkRequestStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability) + }, + + onResponseStarted () { + // Set timingInfo’s final network-response start time to the coarsened shared current + // time given fetchParams’s cross-origin isolated capability, immediately after the + // user agent’s HTTP parser receives the first byte of the response (e.g., frame header + // bytes for HTTP/2 or response status line for HTTP/1.x). + timingInfo.finalNetworkResponseStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability) + }, + + onHeaders (status, rawHeaders, resume, statusText) { + if (status < 200) { + return false + } + + /** @type {string[]} */ + let codings = [] + + const headersList = new HeadersList() + + for (let i = 0; i < rawHeaders.length; i += 2) { + headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString('latin1'), true) + } + const contentEncoding = headersList.get('content-encoding', true) + if (contentEncoding) { + // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1 + // "All content-coding values are case-insensitive..." + codings = contentEncoding.toLowerCase().split(',').map((x) => x.trim()) + } + const location = headersList.get('location', true) + + this.body = new Readable({ read: resume }) + + const decoders = [] + + const willFollow = location && request.redirect === 'follow' && + redirectStatusSet.has(status) + + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding + if (codings.length !== 0 && request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) { + for (let i = codings.length - 1; i >= 0; --i) { + const coding = codings[i] + // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2 + if (coding === 'x-gzip' || coding === 'gzip') { + decoders.push(zlib.createGunzip({ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + flush: zlib.constants.Z_SYNC_FLUSH, + finishFlush: zlib.constants.Z_SYNC_FLUSH + })) + } else if (coding === 'deflate') { + decoders.push(createInflate({ + flush: zlib.constants.Z_SYNC_FLUSH, + finishFlush: zlib.constants.Z_SYNC_FLUSH + })) + } else if (coding === 'br') { + decoders.push(zlib.createBrotliDecompress({ + flush: zlib.constants.BROTLI_OPERATION_FLUSH, + finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH + })) + } else if (coding === 'zstd' && typeof zlib.createZstdDecompress === 'function') { + // Node.js v23.8.0+ and v22.15.0+ supports Zstandard + decoders.push(zlib.createZstdDecompress({ + flush: zlib.constants.ZSTD_e_continue, + finishFlush: zlib.constants.ZSTD_e_end + })) + } else { + decoders.length = 0 + break + } + } + } + + const onError = this.onError.bind(this) + + resolve({ + status, + statusText, + headersList, + body: decoders.length + ? pipeline(this.body, ...decoders, (err) => { + if (err) { + this.onError(err) + } + }).on('error', onError) + : this.body.on('error', onError) + }) + + return true + }, + + onData (chunk) { + if (fetchParams.controller.dump) { + return + } + + // 1. If one or more bytes have been transmitted from response’s + // message body, then: + + // 1. Let bytes be the transmitted bytes. + const bytes = chunk + + // 2. Let codings be the result of extracting header list values + // given `Content-Encoding` and response’s header list. + // See pullAlgorithm. + + // 3. Increase timingInfo’s encoded body size by bytes’s length. + timingInfo.encodedBodySize += bytes.byteLength + + // 4. See pullAlgorithm... + + return this.body.push(bytes) + }, + + onComplete () { + if (this.abort) { + fetchParams.controller.off('terminated', this.abort) + } + + fetchParams.controller.ended = true + + this.body.push(null) + }, + + onError (error) { + if (this.abort) { + fetchParams.controller.off('terminated', this.abort) + } + + this.body?.destroy(error) + + fetchParams.controller.terminate(error) + + reject(error) + }, + + onUpgrade (status, rawHeaders, socket) { + if (status !== 101) { + return + } + + const headersList = new HeadersList() + + for (let i = 0; i < rawHeaders.length; i += 2) { + headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString('latin1'), true) + } + + resolve({ + status, + statusText: STATUS_CODES[status], + headersList, + socket + }) + + return true + } + } + )) + } +} + +module.exports = { + fetch, + Fetch, + fetching, + finalizeAndReportTiming +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/fetch/request.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/fetch/request.js new file mode 100644 index 0000000000000000000000000000000000000000..02a52b00f85f7b44de3a9bb544f88adf60dede8f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/fetch/request.js @@ -0,0 +1,1107 @@ +/* globals AbortController */ + +'use strict' + +const { extractBody, mixinBody, cloneBody, bodyUnusable } = require('./body') +const { Headers, fill: fillHeaders, HeadersList, setHeadersGuard, getHeadersGuard, setHeadersList, getHeadersList } = require('./headers') +const util = require('../../core/util') +const nodeUtil = require('node:util') +const { + isValidHTTPToken, + sameOrigin, + environmentSettingsObject +} = require('./util') +const { + forbiddenMethodsSet, + corsSafeListedMethodsSet, + referrerPolicy, + requestRedirect, + requestMode, + requestCredentials, + requestCache, + requestDuplex +} = require('./constants') +const { kEnumerableProperty, normalizedMethodRecordsBase, normalizedMethodRecords } = util +const { webidl } = require('../webidl') +const { URLSerializer } = require('./data-url') +const { kConstruct } = require('../../core/symbols') +const assert = require('node:assert') +const { getMaxListeners, setMaxListeners, defaultMaxListeners } = require('node:events') + +const kAbortController = Symbol('abortController') + +const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => { + signal.removeEventListener('abort', abort) +}) + +const dependentControllerMap = new WeakMap() + +let abortSignalHasEventHandlerLeakWarning + +try { + abortSignalHasEventHandlerLeakWarning = getMaxListeners(new AbortController().signal) > 0 +} catch { + abortSignalHasEventHandlerLeakWarning = false +} + +function buildAbort (acRef) { + return abort + + function abort () { + const ac = acRef.deref() + if (ac !== undefined) { + // Currently, there is a problem with FinalizationRegistry. + // https://github.com/nodejs/node/issues/49344 + // https://github.com/nodejs/node/issues/47748 + // In the case of abort, the first step is to unregister from it. + // If the controller can refer to it, it is still registered. + // It will be removed in the future. + requestFinalizer.unregister(abort) + + // Unsubscribe a listener. + // FinalizationRegistry will no longer be called, so this must be done. + this.removeEventListener('abort', abort) + + ac.abort(this.reason) + + const controllerList = dependentControllerMap.get(ac.signal) + + if (controllerList !== undefined) { + if (controllerList.size !== 0) { + for (const ref of controllerList) { + const ctrl = ref.deref() + if (ctrl !== undefined) { + ctrl.abort(this.reason) + } + } + controllerList.clear() + } + dependentControllerMap.delete(ac.signal) + } + } + } +} + +let patchMethodWarning = false + +// https://fetch.spec.whatwg.org/#request-class +class Request { + /** @type {AbortSignal} */ + #signal + + /** @type {import('../../dispatcher/dispatcher')} */ + #dispatcher + + /** @type {Headers} */ + #headers + + #state + + // https://fetch.spec.whatwg.org/#dom-request + constructor (input, init = undefined) { + webidl.util.markAsUncloneable(this) + + if (input === kConstruct) { + return + } + + const prefix = 'Request constructor' + webidl.argumentLengthCheck(arguments, 1, prefix) + + input = webidl.converters.RequestInfo(input) + init = webidl.converters.RequestInit(init) + + // 1. Let request be null. + let request = null + + // 2. Let fallbackMode be null. + let fallbackMode = null + + // 3. Let baseURL be this’s relevant settings object’s API base URL. + const baseUrl = environmentSettingsObject.settingsObject.baseUrl + + // 4. Let signal be null. + let signal = null + + // 5. If input is a string, then: + if (typeof input === 'string') { + this.#dispatcher = init.dispatcher + + // 1. Let parsedURL be the result of parsing input with baseURL. + // 2. If parsedURL is failure, then throw a TypeError. + let parsedURL + try { + parsedURL = new URL(input, baseUrl) + } catch (err) { + throw new TypeError('Failed to parse URL from ' + input, { cause: err }) + } + + // 3. If parsedURL includes credentials, then throw a TypeError. + if (parsedURL.username || parsedURL.password) { + throw new TypeError( + 'Request cannot be constructed from a URL that includes credentials: ' + + input + ) + } + + // 4. Set request to a new request whose URL is parsedURL. + request = makeRequest({ urlList: [parsedURL] }) + + // 5. Set fallbackMode to "cors". + fallbackMode = 'cors' + } else { + // 6. Otherwise: + + // 7. Assert: input is a Request object. + assert(webidl.is.Request(input)) + + // 8. Set request to input’s request. + request = input.#state + + // 9. Set signal to input’s signal. + signal = input.#signal + + this.#dispatcher = init.dispatcher || input.#dispatcher + } + + // 7. Let origin be this’s relevant settings object’s origin. + const origin = environmentSettingsObject.settingsObject.origin + + // 8. Let window be "client". + let window = 'client' + + // 9. If request’s window is an environment settings object and its origin + // is same origin with origin, then set window to request’s window. + if ( + request.window?.constructor?.name === 'EnvironmentSettingsObject' && + sameOrigin(request.window, origin) + ) { + window = request.window + } + + // 10. If init["window"] exists and is non-null, then throw a TypeError. + if (init.window != null) { + throw new TypeError(`'window' option '${window}' must be null`) + } + + // 11. If init["window"] exists, then set window to "no-window". + if ('window' in init) { + window = 'no-window' + } + + // 12. Set request to a new request with the following properties: + request = makeRequest({ + // URL request’s URL. + // undici implementation note: this is set as the first item in request's urlList in makeRequest + // method request’s method. + method: request.method, + // header list A copy of request’s header list. + // undici implementation note: headersList is cloned in makeRequest + headersList: request.headersList, + // unsafe-request flag Set. + unsafeRequest: request.unsafeRequest, + // client This’s relevant settings object. + client: environmentSettingsObject.settingsObject, + // window window. + window, + // priority request’s priority. + priority: request.priority, + // origin request’s origin. The propagation of the origin is only significant for navigation requests + // being handled by a service worker. In this scenario a request can have an origin that is different + // from the current client. + origin: request.origin, + // referrer request’s referrer. + referrer: request.referrer, + // referrer policy request’s referrer policy. + referrerPolicy: request.referrerPolicy, + // mode request’s mode. + mode: request.mode, + // credentials mode request’s credentials mode. + credentials: request.credentials, + // cache mode request’s cache mode. + cache: request.cache, + // redirect mode request’s redirect mode. + redirect: request.redirect, + // integrity metadata request’s integrity metadata. + integrity: request.integrity, + // keepalive request’s keepalive. + keepalive: request.keepalive, + // reload-navigation flag request’s reload-navigation flag. + reloadNavigation: request.reloadNavigation, + // history-navigation flag request’s history-navigation flag. + historyNavigation: request.historyNavigation, + // URL list A clone of request’s URL list. + urlList: [...request.urlList] + }) + + const initHasKey = Object.keys(init).length !== 0 + + // 13. If init is not empty, then: + if (initHasKey) { + // 1. If request’s mode is "navigate", then set it to "same-origin". + if (request.mode === 'navigate') { + request.mode = 'same-origin' + } + + // 2. Unset request’s reload-navigation flag. + request.reloadNavigation = false + + // 3. Unset request’s history-navigation flag. + request.historyNavigation = false + + // 4. Set request’s origin to "client". + request.origin = 'client' + + // 5. Set request’s referrer to "client" + request.referrer = 'client' + + // 6. Set request’s referrer policy to the empty string. + request.referrerPolicy = '' + + // 7. Set request’s URL to request’s current URL. + request.url = request.urlList[request.urlList.length - 1] + + // 8. Set request’s URL list to « request’s URL ». + request.urlList = [request.url] + } + + // 14. If init["referrer"] exists, then: + if (init.referrer !== undefined) { + // 1. Let referrer be init["referrer"]. + const referrer = init.referrer + + // 2. If referrer is the empty string, then set request’s referrer to "no-referrer". + if (referrer === '') { + request.referrer = 'no-referrer' + } else { + // 1. Let parsedReferrer be the result of parsing referrer with + // baseURL. + // 2. If parsedReferrer is failure, then throw a TypeError. + let parsedReferrer + try { + parsedReferrer = new URL(referrer, baseUrl) + } catch (err) { + throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err }) + } + + // 3. If one of the following is true + // - parsedReferrer’s scheme is "about" and path is the string "client" + // - parsedReferrer’s origin is not same origin with origin + // then set request’s referrer to "client". + if ( + (parsedReferrer.protocol === 'about:' && parsedReferrer.hostname === 'client') || + (origin && !sameOrigin(parsedReferrer, environmentSettingsObject.settingsObject.baseUrl)) + ) { + request.referrer = 'client' + } else { + // 4. Otherwise, set request’s referrer to parsedReferrer. + request.referrer = parsedReferrer + } + } + } + + // 15. If init["referrerPolicy"] exists, then set request’s referrer policy + // to it. + if (init.referrerPolicy !== undefined) { + request.referrerPolicy = init.referrerPolicy + } + + // 16. Let mode be init["mode"] if it exists, and fallbackMode otherwise. + let mode + if (init.mode !== undefined) { + mode = init.mode + } else { + mode = fallbackMode + } + + // 17. If mode is "navigate", then throw a TypeError. + if (mode === 'navigate') { + throw webidl.errors.exception({ + header: 'Request constructor', + message: 'invalid request mode navigate.' + }) + } + + // 18. If mode is non-null, set request’s mode to mode. + if (mode != null) { + request.mode = mode + } + + // 19. If init["credentials"] exists, then set request’s credentials mode + // to it. + if (init.credentials !== undefined) { + request.credentials = init.credentials + } + + // 18. If init["cache"] exists, then set request’s cache mode to it. + if (init.cache !== undefined) { + request.cache = init.cache + } + + // 21. If request’s cache mode is "only-if-cached" and request’s mode is + // not "same-origin", then throw a TypeError. + if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') { + throw new TypeError( + "'only-if-cached' can be set only with 'same-origin' mode" + ) + } + + // 22. If init["redirect"] exists, then set request’s redirect mode to it. + if (init.redirect !== undefined) { + request.redirect = init.redirect + } + + // 23. If init["integrity"] exists, then set request’s integrity metadata to it. + if (init.integrity != null) { + request.integrity = String(init.integrity) + } + + // 24. If init["keepalive"] exists, then set request’s keepalive to it. + if (init.keepalive !== undefined) { + request.keepalive = Boolean(init.keepalive) + } + + // 25. If init["method"] exists, then: + if (init.method !== undefined) { + // 1. Let method be init["method"]. + let method = init.method + + const mayBeNormalized = normalizedMethodRecords[method] + + if (mayBeNormalized !== undefined) { + // Note: Bypass validation DELETE, GET, HEAD, OPTIONS, POST, PUT, PATCH and these lowercase ones + request.method = mayBeNormalized + } else { + // 2. If method is not a method or method is a forbidden method, then + // throw a TypeError. + if (!isValidHTTPToken(method)) { + throw new TypeError(`'${method}' is not a valid HTTP method.`) + } + + const upperCase = method.toUpperCase() + + if (forbiddenMethodsSet.has(upperCase)) { + throw new TypeError(`'${method}' HTTP method is unsupported.`) + } + + // 3. Normalize method. + // https://fetch.spec.whatwg.org/#concept-method-normalize + // Note: must be in uppercase + method = normalizedMethodRecordsBase[upperCase] ?? method + + // 4. Set request’s method to method. + request.method = method + } + + if (!patchMethodWarning && request.method === 'patch') { + process.emitWarning('Using `patch` is highly likely to result in a `405 Method Not Allowed`. `PATCH` is much more likely to succeed.', { + code: 'UNDICI-FETCH-patch' + }) + + patchMethodWarning = true + } + } + + // 26. If init["signal"] exists, then set signal to it. + if (init.signal !== undefined) { + signal = init.signal + } + + // 27. Set this’s request to request. + this.#state = request + + // 28. Set this’s signal to a new AbortSignal object with this’s relevant + // Realm. + // TODO: could this be simplified with AbortSignal.any + // (https://dom.spec.whatwg.org/#dom-abortsignal-any) + const ac = new AbortController() + this.#signal = ac.signal + + // 29. If signal is not null, then make this’s signal follow signal. + if (signal != null) { + if (signal.aborted) { + ac.abort(signal.reason) + } else { + // Keep a strong ref to ac while request object + // is alive. This is needed to prevent AbortController + // from being prematurely garbage collected. + // See, https://github.com/nodejs/undici/issues/1926. + this[kAbortController] = ac + + const acRef = new WeakRef(ac) + const abort = buildAbort(acRef) + + // If the max amount of listeners is equal to the default, increase it + if (abortSignalHasEventHandlerLeakWarning && getMaxListeners(signal) === defaultMaxListeners) { + setMaxListeners(1500, signal) + } + + util.addAbortListener(signal, abort) + // The third argument must be a registry key to be unregistered. + // Without it, you cannot unregister. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry + // abort is used as the unregister key. (because it is unique) + requestFinalizer.register(ac, { signal, abort }, abort) + } + } + + // 30. Set this’s headers to a new Headers object with this’s relevant + // Realm, whose header list is request’s header list and guard is + // "request". + this.#headers = new Headers(kConstruct) + setHeadersList(this.#headers, request.headersList) + setHeadersGuard(this.#headers, 'request') + + // 31. If this’s request’s mode is "no-cors", then: + if (mode === 'no-cors') { + // 1. If this’s request’s method is not a CORS-safelisted method, + // then throw a TypeError. + if (!corsSafeListedMethodsSet.has(request.method)) { + throw new TypeError( + `'${request.method} is unsupported in no-cors mode.` + ) + } + + // 2. Set this’s headers’s guard to "request-no-cors". + setHeadersGuard(this.#headers, 'request-no-cors') + } + + // 32. If init is not empty, then: + if (initHasKey) { + /** @type {HeadersList} */ + const headersList = getHeadersList(this.#headers) + // 1. Let headers be a copy of this’s headers and its associated header + // list. + // 2. If init["headers"] exists, then set headers to init["headers"]. + const headers = init.headers !== undefined ? init.headers : new HeadersList(headersList) + + // 3. Empty this’s headers’s header list. + headersList.clear() + + // 4. If headers is a Headers object, then for each header in its header + // list, append header’s name/header’s value to this’s headers. + if (headers instanceof HeadersList) { + for (const { name, value } of headers.rawValues()) { + headersList.append(name, value, false) + } + // Note: Copy the `set-cookie` meta-data. + headersList.cookies = headers.cookies + } else { + // 5. Otherwise, fill this’s headers with headers. + fillHeaders(this.#headers, headers) + } + } + + // 33. Let inputBody be input’s request’s body if input is a Request + // object; otherwise null. + const inputBody = webidl.is.Request(input) ? input.#state.body : null + + // 34. If either init["body"] exists and is non-null or inputBody is + // non-null, and request’s method is `GET` or `HEAD`, then throw a + // TypeError. + if ( + (init.body != null || inputBody != null) && + (request.method === 'GET' || request.method === 'HEAD') + ) { + throw new TypeError('Request with GET/HEAD method cannot have body.') + } + + // 35. Let initBody be null. + let initBody = null + + // 36. If init["body"] exists and is non-null, then: + if (init.body != null) { + // 1. Let Content-Type be null. + // 2. Set initBody and Content-Type to the result of extracting + // init["body"], with keepalive set to request’s keepalive. + const [extractedBody, contentType] = extractBody( + init.body, + request.keepalive + ) + initBody = extractedBody + + // 3, If Content-Type is non-null and this’s headers’s header list does + // not contain `Content-Type`, then append `Content-Type`/Content-Type to + // this’s headers. + if (contentType && !getHeadersList(this.#headers).contains('content-type', true)) { + this.#headers.append('content-type', contentType, true) + } + } + + // 37. Let inputOrInitBody be initBody if it is non-null; otherwise + // inputBody. + const inputOrInitBody = initBody ?? inputBody + + // 38. If inputOrInitBody is non-null and inputOrInitBody’s source is + // null, then: + if (inputOrInitBody != null && inputOrInitBody.source == null) { + // 1. If initBody is non-null and init["duplex"] does not exist, + // then throw a TypeError. + if (initBody != null && init.duplex == null) { + throw new TypeError('RequestInit: duplex option is required when sending a body.') + } + + // 2. If this’s request’s mode is neither "same-origin" nor "cors", + // then throw a TypeError. + if (request.mode !== 'same-origin' && request.mode !== 'cors') { + throw new TypeError( + 'If request is made from ReadableStream, mode should be "same-origin" or "cors"' + ) + } + + // 3. Set this’s request’s use-CORS-preflight flag. + request.useCORSPreflightFlag = true + } + + // 39. Let finalBody be inputOrInitBody. + let finalBody = inputOrInitBody + + // 40. If initBody is null and inputBody is non-null, then: + if (initBody == null && inputBody != null) { + // 1. If input is unusable, then throw a TypeError. + if (bodyUnusable(input.#state)) { + throw new TypeError( + 'Cannot construct a Request with a Request object that has already been used.' + ) + } + + // 2. Set finalBody to the result of creating a proxy for inputBody. + // https://streams.spec.whatwg.org/#readablestream-create-a-proxy + const identityTransform = new TransformStream() + inputBody.stream.pipeThrough(identityTransform) + finalBody = { + source: inputBody.source, + length: inputBody.length, + stream: identityTransform.readable + } + } + + // 41. Set this’s request’s body to finalBody. + this.#state.body = finalBody + } + + // Returns request’s HTTP method, which is "GET" by default. + get method () { + webidl.brandCheck(this, Request) + + // The method getter steps are to return this’s request’s method. + return this.#state.method + } + + // Returns the URL of request as a string. + get url () { + webidl.brandCheck(this, Request) + + // The url getter steps are to return this’s request’s URL, serialized. + return URLSerializer(this.#state.url) + } + + // Returns a Headers object consisting of the headers associated with request. + // Note that headers added in the network layer by the user agent will not + // be accounted for in this object, e.g., the "Host" header. + get headers () { + webidl.brandCheck(this, Request) + + // The headers getter steps are to return this’s headers. + return this.#headers + } + + // Returns the kind of resource requested by request, e.g., "document" + // or "script". + get destination () { + webidl.brandCheck(this, Request) + + // The destination getter are to return this’s request’s destination. + return this.#state.destination + } + + // Returns the referrer of request. Its value can be a same-origin URL if + // explicitly set in init, the empty string to indicate no referrer, and + // "about:client" when defaulting to the global’s default. This is used + // during fetching to determine the value of the `Referer` header of the + // request being made. + get referrer () { + webidl.brandCheck(this, Request) + + // 1. If this’s request’s referrer is "no-referrer", then return the + // empty string. + if (this.#state.referrer === 'no-referrer') { + return '' + } + + // 2. If this’s request’s referrer is "client", then return + // "about:client". + if (this.#state.referrer === 'client') { + return 'about:client' + } + + // Return this’s request’s referrer, serialized. + return this.#state.referrer.toString() + } + + // Returns the referrer policy associated with request. + // This is used during fetching to compute the value of the request’s + // referrer. + get referrerPolicy () { + webidl.brandCheck(this, Request) + + // The referrerPolicy getter steps are to return this’s request’s referrer policy. + return this.#state.referrerPolicy + } + + // Returns the mode associated with request, which is a string indicating + // whether the request will use CORS, or will be restricted to same-origin + // URLs. + get mode () { + webidl.brandCheck(this, Request) + + // The mode getter steps are to return this’s request’s mode. + return this.#state.mode + } + + // Returns the credentials mode associated with request, + // which is a string indicating whether credentials will be sent with the + // request always, never, or only when sent to a same-origin URL. + get credentials () { + webidl.brandCheck(this, Request) + + // The credentials getter steps are to return this’s request’s credentials mode. + return this.#state.credentials + } + + // Returns the cache mode associated with request, + // which is a string indicating how the request will + // interact with the browser’s cache when fetching. + get cache () { + webidl.brandCheck(this, Request) + + // The cache getter steps are to return this’s request’s cache mode. + return this.#state.cache + } + + // Returns the redirect mode associated with request, + // which is a string indicating how redirects for the + // request will be handled during fetching. A request + // will follow redirects by default. + get redirect () { + webidl.brandCheck(this, Request) + + // The redirect getter steps are to return this’s request’s redirect mode. + return this.#state.redirect + } + + // Returns request’s subresource integrity metadata, which is a + // cryptographic hash of the resource being fetched. Its value + // consists of multiple hashes separated by whitespace. [SRI] + get integrity () { + webidl.brandCheck(this, Request) + + // The integrity getter steps are to return this’s request’s integrity + // metadata. + return this.#state.integrity + } + + // Returns a boolean indicating whether or not request can outlive the + // global in which it was created. + get keepalive () { + webidl.brandCheck(this, Request) + + // The keepalive getter steps are to return this’s request’s keepalive. + return this.#state.keepalive + } + + // Returns a boolean indicating whether or not request is for a reload + // navigation. + get isReloadNavigation () { + webidl.brandCheck(this, Request) + + // The isReloadNavigation getter steps are to return true if this’s + // request’s reload-navigation flag is set; otherwise false. + return this.#state.reloadNavigation + } + + // Returns a boolean indicating whether or not request is for a history + // navigation (a.k.a. back-forward navigation). + get isHistoryNavigation () { + webidl.brandCheck(this, Request) + + // The isHistoryNavigation getter steps are to return true if this’s request’s + // history-navigation flag is set; otherwise false. + return this.#state.historyNavigation + } + + // Returns the signal associated with request, which is an AbortSignal + // object indicating whether or not request has been aborted, and its + // abort event handler. + get signal () { + webidl.brandCheck(this, Request) + + // The signal getter steps are to return this’s signal. + return this.#signal + } + + get body () { + webidl.brandCheck(this, Request) + + return this.#state.body ? this.#state.body.stream : null + } + + get bodyUsed () { + webidl.brandCheck(this, Request) + + return !!this.#state.body && util.isDisturbed(this.#state.body.stream) + } + + get duplex () { + webidl.brandCheck(this, Request) + + return 'half' + } + + // Returns a clone of request. + clone () { + webidl.brandCheck(this, Request) + + // 1. If this is unusable, then throw a TypeError. + if (bodyUnusable(this.#state)) { + throw new TypeError('unusable') + } + + // 2. Let clonedRequest be the result of cloning this’s request. + const clonedRequest = cloneRequest(this.#state) + + // 3. Let clonedRequestObject be the result of creating a Request object, + // given clonedRequest, this’s headers’s guard, and this’s relevant Realm. + // 4. Make clonedRequestObject’s signal follow this’s signal. + const ac = new AbortController() + if (this.signal.aborted) { + ac.abort(this.signal.reason) + } else { + let list = dependentControllerMap.get(this.signal) + if (list === undefined) { + list = new Set() + dependentControllerMap.set(this.signal, list) + } + const acRef = new WeakRef(ac) + list.add(acRef) + util.addAbortListener( + ac.signal, + buildAbort(acRef) + ) + } + + // 4. Return clonedRequestObject. + return fromInnerRequest(clonedRequest, this.#dispatcher, ac.signal, getHeadersGuard(this.#headers)) + } + + [nodeUtil.inspect.custom] (depth, options) { + if (options.depth === null) { + options.depth = 2 + } + + options.colors ??= true + + const properties = { + method: this.method, + url: this.url, + headers: this.headers, + destination: this.destination, + referrer: this.referrer, + referrerPolicy: this.referrerPolicy, + mode: this.mode, + credentials: this.credentials, + cache: this.cache, + redirect: this.redirect, + integrity: this.integrity, + keepalive: this.keepalive, + isReloadNavigation: this.isReloadNavigation, + isHistoryNavigation: this.isHistoryNavigation, + signal: this.signal + } + + return `Request ${nodeUtil.formatWithOptions(options, properties)}` + } + + /** + * @param {Request} request + * @param {AbortSignal} newSignal + */ + static setRequestSignal (request, newSignal) { + request.#signal = newSignal + return request + } + + /** + * @param {Request} request + */ + static getRequestDispatcher (request) { + return request.#dispatcher + } + + /** + * @param {Request} request + * @param {import('../../dispatcher/dispatcher')} newDispatcher + */ + static setRequestDispatcher (request, newDispatcher) { + request.#dispatcher = newDispatcher + } + + /** + * @param {Request} request + * @param {Headers} newHeaders + */ + static setRequestHeaders (request, newHeaders) { + request.#headers = newHeaders + } + + /** + * @param {Request} request + */ + static getRequestState (request) { + return request.#state + } + + /** + * @param {Request} request + * @param {any} newState + */ + static setRequestState (request, newState) { + request.#state = newState + } +} + +const { setRequestSignal, getRequestDispatcher, setRequestDispatcher, setRequestHeaders, getRequestState, setRequestState } = Request +Reflect.deleteProperty(Request, 'setRequestSignal') +Reflect.deleteProperty(Request, 'getRequestDispatcher') +Reflect.deleteProperty(Request, 'setRequestDispatcher') +Reflect.deleteProperty(Request, 'setRequestHeaders') +Reflect.deleteProperty(Request, 'getRequestState') +Reflect.deleteProperty(Request, 'setRequestState') + +mixinBody(Request, getRequestState) + +// https://fetch.spec.whatwg.org/#requests +function makeRequest (init) { + return { + method: init.method ?? 'GET', + localURLsOnly: init.localURLsOnly ?? false, + unsafeRequest: init.unsafeRequest ?? false, + body: init.body ?? null, + client: init.client ?? null, + reservedClient: init.reservedClient ?? null, + replacesClientId: init.replacesClientId ?? '', + window: init.window ?? 'client', + keepalive: init.keepalive ?? false, + serviceWorkers: init.serviceWorkers ?? 'all', + initiator: init.initiator ?? '', + destination: init.destination ?? '', + priority: init.priority ?? null, + origin: init.origin ?? 'client', + policyContainer: init.policyContainer ?? 'client', + referrer: init.referrer ?? 'client', + referrerPolicy: init.referrerPolicy ?? '', + mode: init.mode ?? 'no-cors', + useCORSPreflightFlag: init.useCORSPreflightFlag ?? false, + credentials: init.credentials ?? 'same-origin', + useCredentials: init.useCredentials ?? false, + cache: init.cache ?? 'default', + redirect: init.redirect ?? 'follow', + integrity: init.integrity ?? '', + cryptoGraphicsNonceMetadata: init.cryptoGraphicsNonceMetadata ?? '', + parserMetadata: init.parserMetadata ?? '', + reloadNavigation: init.reloadNavigation ?? false, + historyNavigation: init.historyNavigation ?? false, + userActivation: init.userActivation ?? false, + taintedOrigin: init.taintedOrigin ?? false, + redirectCount: init.redirectCount ?? 0, + responseTainting: init.responseTainting ?? 'basic', + preventNoCacheCacheControlHeaderModification: init.preventNoCacheCacheControlHeaderModification ?? false, + done: init.done ?? false, + timingAllowFailed: init.timingAllowFailed ?? false, + urlList: init.urlList, + url: init.urlList[0], + headersList: init.headersList + ? new HeadersList(init.headersList) + : new HeadersList() + } +} + +// https://fetch.spec.whatwg.org/#concept-request-clone +function cloneRequest (request) { + // To clone a request request, run these steps: + + // 1. Let newRequest be a copy of request, except for its body. + const newRequest = makeRequest({ ...request, body: null }) + + // 2. If request’s body is non-null, set newRequest’s body to the + // result of cloning request’s body. + if (request.body != null) { + newRequest.body = cloneBody(request.body) + } + + // 3. Return newRequest. + return newRequest +} + +/** + * @see https://fetch.spec.whatwg.org/#request-create + * @param {any} innerRequest + * @param {import('../../dispatcher/agent')} dispatcher + * @param {AbortSignal} signal + * @param {'request' | 'immutable' | 'request-no-cors' | 'response' | 'none'} guard + * @returns {Request} + */ +function fromInnerRequest (innerRequest, dispatcher, signal, guard) { + const request = new Request(kConstruct) + setRequestState(request, innerRequest) + setRequestDispatcher(request, dispatcher) + setRequestSignal(request, signal) + const headers = new Headers(kConstruct) + setRequestHeaders(request, headers) + setHeadersList(headers, innerRequest.headersList) + setHeadersGuard(headers, guard) + return request +} + +Object.defineProperties(Request.prototype, { + method: kEnumerableProperty, + url: kEnumerableProperty, + headers: kEnumerableProperty, + redirect: kEnumerableProperty, + clone: kEnumerableProperty, + signal: kEnumerableProperty, + duplex: kEnumerableProperty, + destination: kEnumerableProperty, + body: kEnumerableProperty, + bodyUsed: kEnumerableProperty, + isHistoryNavigation: kEnumerableProperty, + isReloadNavigation: kEnumerableProperty, + keepalive: kEnumerableProperty, + integrity: kEnumerableProperty, + cache: kEnumerableProperty, + credentials: kEnumerableProperty, + attribute: kEnumerableProperty, + referrerPolicy: kEnumerableProperty, + referrer: kEnumerableProperty, + mode: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'Request', + configurable: true + } +}) + +webidl.is.Request = webidl.util.MakeTypeAssertion(Request) + +/** + * @param {*} V + * @returns {import('../../../types/fetch').Request|string} + * + * @see https://fetch.spec.whatwg.org/#requestinfo + */ +webidl.converters.RequestInfo = function (V) { + if (typeof V === 'string') { + return webidl.converters.USVString(V) + } + + if (webidl.is.Request(V)) { + return V + } + + return webidl.converters.USVString(V) +} + +/** + * @param {*} V + * @returns {import('../../../types/fetch').RequestInit} + * @see https://fetch.spec.whatwg.org/#requestinit + */ +webidl.converters.RequestInit = webidl.dictionaryConverter([ + { + key: 'method', + converter: webidl.converters.ByteString + }, + { + key: 'headers', + converter: webidl.converters.HeadersInit + }, + { + key: 'body', + converter: webidl.nullableConverter( + webidl.converters.BodyInit + ) + }, + { + key: 'referrer', + converter: webidl.converters.USVString + }, + { + key: 'referrerPolicy', + converter: webidl.converters.DOMString, + // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy + allowedValues: referrerPolicy + }, + { + key: 'mode', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#concept-request-mode + allowedValues: requestMode + }, + { + key: 'credentials', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#requestcredentials + allowedValues: requestCredentials + }, + { + key: 'cache', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#requestcache + allowedValues: requestCache + }, + { + key: 'redirect', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#requestredirect + allowedValues: requestRedirect + }, + { + key: 'integrity', + converter: webidl.converters.DOMString + }, + { + key: 'keepalive', + converter: webidl.converters.boolean + }, + { + key: 'signal', + converter: webidl.nullableConverter( + (signal) => webidl.converters.AbortSignal( + signal, + 'RequestInit', + 'signal' + ) + ) + }, + { + key: 'window', + converter: webidl.converters.any + }, + { + key: 'duplex', + converter: webidl.converters.DOMString, + allowedValues: requestDuplex + }, + { + key: 'dispatcher', // undici specific option + converter: webidl.converters.any + } +]) + +module.exports = { + Request, + makeRequest, + fromInnerRequest, + cloneRequest, + getRequestDispatcher, + getRequestState +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/fetch/response.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/fetch/response.js new file mode 100644 index 0000000000000000000000000000000000000000..5f11f449477f8bfef099af77a9b51b3ba67a2284 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/fetch/response.js @@ -0,0 +1,642 @@ +'use strict' + +const { Headers, HeadersList, fill, getHeadersGuard, setHeadersGuard, setHeadersList } = require('./headers') +const { extractBody, cloneBody, mixinBody, streamRegistry, bodyUnusable } = require('./body') +const util = require('../../core/util') +const nodeUtil = require('node:util') +const { kEnumerableProperty } = util +const { + isValidReasonPhrase, + isCancelled, + isAborted, + serializeJavascriptValueToJSONString, + isErrorLike, + isomorphicEncode, + environmentSettingsObject: relevantRealm +} = require('./util') +const { + redirectStatusSet, + nullBodyStatus +} = require('./constants') +const { webidl } = require('../webidl') +const { URLSerializer } = require('./data-url') +const { kConstruct } = require('../../core/symbols') +const assert = require('node:assert') + +const { isArrayBuffer } = nodeUtil.types + +const textEncoder = new TextEncoder('utf-8') + +// https://fetch.spec.whatwg.org/#response-class +class Response { + /** @type {Headers} */ + #headers + + #state + + // Creates network error Response. + static error () { + // The static error() method steps are to return the result of creating a + // Response object, given a new network error, "immutable", and this’s + // relevant Realm. + const responseObject = fromInnerResponse(makeNetworkError(), 'immutable') + + return responseObject + } + + // https://fetch.spec.whatwg.org/#dom-response-json + static json (data, init = undefined) { + webidl.argumentLengthCheck(arguments, 1, 'Response.json') + + if (init !== null) { + init = webidl.converters.ResponseInit(init) + } + + // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data. + const bytes = textEncoder.encode( + serializeJavascriptValueToJSONString(data) + ) + + // 2. Let body be the result of extracting bytes. + const body = extractBody(bytes) + + // 3. Let responseObject be the result of creating a Response object, given a new response, + // "response", and this’s relevant Realm. + const responseObject = fromInnerResponse(makeResponse({}), 'response') + + // 4. Perform initialize a response given responseObject, init, and (body, "application/json"). + initializeResponse(responseObject, init, { body: body[0], type: 'application/json' }) + + // 5. Return responseObject. + return responseObject + } + + // Creates a redirect Response that redirects to url with status status. + static redirect (url, status = 302) { + webidl.argumentLengthCheck(arguments, 1, 'Response.redirect') + + url = webidl.converters.USVString(url) + status = webidl.converters['unsigned short'](status) + + // 1. Let parsedURL be the result of parsing url with current settings + // object’s API base URL. + // 2. If parsedURL is failure, then throw a TypeError. + // TODO: base-URL? + let parsedURL + try { + parsedURL = new URL(url, relevantRealm.settingsObject.baseUrl) + } catch (err) { + throw new TypeError(`Failed to parse URL from ${url}`, { cause: err }) + } + + // 3. If status is not a redirect status, then throw a RangeError. + if (!redirectStatusSet.has(status)) { + throw new RangeError(`Invalid status code ${status}`) + } + + // 4. Let responseObject be the result of creating a Response object, + // given a new response, "immutable", and this’s relevant Realm. + const responseObject = fromInnerResponse(makeResponse({}), 'immutable') + + // 5. Set responseObject’s response’s status to status. + responseObject.#state.status = status + + // 6. Let value be parsedURL, serialized and isomorphic encoded. + const value = isomorphicEncode(URLSerializer(parsedURL)) + + // 7. Append `Location`/value to responseObject’s response’s header list. + responseObject.#state.headersList.append('location', value, true) + + // 8. Return responseObject. + return responseObject + } + + // https://fetch.spec.whatwg.org/#dom-response + constructor (body = null, init = undefined) { + webidl.util.markAsUncloneable(this) + + if (body === kConstruct) { + return + } + + if (body !== null) { + body = webidl.converters.BodyInit(body) + } + + init = webidl.converters.ResponseInit(init) + + // 1. Set this’s response to a new response. + this.#state = makeResponse({}) + + // 2. Set this’s headers to a new Headers object with this’s relevant + // Realm, whose header list is this’s response’s header list and guard + // is "response". + this.#headers = new Headers(kConstruct) + setHeadersGuard(this.#headers, 'response') + setHeadersList(this.#headers, this.#state.headersList) + + // 3. Let bodyWithType be null. + let bodyWithType = null + + // 4. If body is non-null, then set bodyWithType to the result of extracting body. + if (body != null) { + const [extractedBody, type] = extractBody(body) + bodyWithType = { body: extractedBody, type } + } + + // 5. Perform initialize a response given this, init, and bodyWithType. + initializeResponse(this, init, bodyWithType) + } + + // Returns response’s type, e.g., "cors". + get type () { + webidl.brandCheck(this, Response) + + // The type getter steps are to return this’s response’s type. + return this.#state.type + } + + // Returns response’s URL, if it has one; otherwise the empty string. + get url () { + webidl.brandCheck(this, Response) + + const urlList = this.#state.urlList + + // The url getter steps are to return the empty string if this’s + // response’s URL is null; otherwise this’s response’s URL, + // serialized with exclude fragment set to true. + const url = urlList[urlList.length - 1] ?? null + + if (url === null) { + return '' + } + + return URLSerializer(url, true) + } + + // Returns whether response was obtained through a redirect. + get redirected () { + webidl.brandCheck(this, Response) + + // The redirected getter steps are to return true if this’s response’s URL + // list has more than one item; otherwise false. + return this.#state.urlList.length > 1 + } + + // Returns response’s status. + get status () { + webidl.brandCheck(this, Response) + + // The status getter steps are to return this’s response’s status. + return this.#state.status + } + + // Returns whether response’s status is an ok status. + get ok () { + webidl.brandCheck(this, Response) + + // The ok getter steps are to return true if this’s response’s status is an + // ok status; otherwise false. + return this.#state.status >= 200 && this.#state.status <= 299 + } + + // Returns response’s status message. + get statusText () { + webidl.brandCheck(this, Response) + + // The statusText getter steps are to return this’s response’s status + // message. + return this.#state.statusText + } + + // Returns response’s headers as Headers. + get headers () { + webidl.brandCheck(this, Response) + + // The headers getter steps are to return this’s headers. + return this.#headers + } + + get body () { + webidl.brandCheck(this, Response) + + return this.#state.body ? this.#state.body.stream : null + } + + get bodyUsed () { + webidl.brandCheck(this, Response) + + return !!this.#state.body && util.isDisturbed(this.#state.body.stream) + } + + // Returns a clone of response. + clone () { + webidl.brandCheck(this, Response) + + // 1. If this is unusable, then throw a TypeError. + if (bodyUnusable(this.#state)) { + throw webidl.errors.exception({ + header: 'Response.clone', + message: 'Body has already been consumed.' + }) + } + + // 2. Let clonedResponse be the result of cloning this’s response. + const clonedResponse = cloneResponse(this.#state) + + // Note: To re-register because of a new stream. + if (this.#state.body?.stream) { + streamRegistry.register(this, new WeakRef(this.#state.body.stream)) + } + + // 3. Return the result of creating a Response object, given + // clonedResponse, this’s headers’s guard, and this’s relevant Realm. + return fromInnerResponse(clonedResponse, getHeadersGuard(this.#headers)) + } + + [nodeUtil.inspect.custom] (depth, options) { + if (options.depth === null) { + options.depth = 2 + } + + options.colors ??= true + + const properties = { + status: this.status, + statusText: this.statusText, + headers: this.headers, + body: this.body, + bodyUsed: this.bodyUsed, + ok: this.ok, + redirected: this.redirected, + type: this.type, + url: this.url + } + + return `Response ${nodeUtil.formatWithOptions(options, properties)}` + } + + /** + * @param {Response} response + */ + static getResponseHeaders (response) { + return response.#headers + } + + /** + * @param {Response} response + * @param {Headers} newHeaders + */ + static setResponseHeaders (response, newHeaders) { + response.#headers = newHeaders + } + + /** + * @param {Response} response + */ + static getResponseState (response) { + return response.#state + } + + /** + * @param {Response} response + * @param {any} newState + */ + static setResponseState (response, newState) { + response.#state = newState + } +} + +const { getResponseHeaders, setResponseHeaders, getResponseState, setResponseState } = Response +Reflect.deleteProperty(Response, 'getResponseHeaders') +Reflect.deleteProperty(Response, 'setResponseHeaders') +Reflect.deleteProperty(Response, 'getResponseState') +Reflect.deleteProperty(Response, 'setResponseState') + +mixinBody(Response, getResponseState) + +Object.defineProperties(Response.prototype, { + type: kEnumerableProperty, + url: kEnumerableProperty, + status: kEnumerableProperty, + ok: kEnumerableProperty, + redirected: kEnumerableProperty, + statusText: kEnumerableProperty, + headers: kEnumerableProperty, + clone: kEnumerableProperty, + body: kEnumerableProperty, + bodyUsed: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'Response', + configurable: true + } +}) + +Object.defineProperties(Response, { + json: kEnumerableProperty, + redirect: kEnumerableProperty, + error: kEnumerableProperty +}) + +// https://fetch.spec.whatwg.org/#concept-response-clone +function cloneResponse (response) { + // To clone a response response, run these steps: + + // 1. If response is a filtered response, then return a new identical + // filtered response whose internal response is a clone of response’s + // internal response. + if (response.internalResponse) { + return filterResponse( + cloneResponse(response.internalResponse), + response.type + ) + } + + // 2. Let newResponse be a copy of response, except for its body. + const newResponse = makeResponse({ ...response, body: null }) + + // 3. If response’s body is non-null, then set newResponse’s body to the + // result of cloning response’s body. + if (response.body != null) { + newResponse.body = cloneBody(response.body) + } + + // 4. Return newResponse. + return newResponse +} + +function makeResponse (init) { + return { + aborted: false, + rangeRequested: false, + timingAllowPassed: false, + requestIncludesCredentials: false, + type: 'default', + status: 200, + timingInfo: null, + cacheState: '', + statusText: '', + ...init, + headersList: init?.headersList + ? new HeadersList(init?.headersList) + : new HeadersList(), + urlList: init?.urlList ? [...init.urlList] : [] + } +} + +function makeNetworkError (reason) { + const isError = isErrorLike(reason) + return makeResponse({ + type: 'error', + status: 0, + error: isError + ? reason + : new Error(reason ? String(reason) : reason), + aborted: reason && reason.name === 'AbortError' + }) +} + +// @see https://fetch.spec.whatwg.org/#concept-network-error +function isNetworkError (response) { + return ( + // A network error is a response whose type is "error", + response.type === 'error' && + // status is 0 + response.status === 0 + ) +} + +function makeFilteredResponse (response, state) { + state = { + internalResponse: response, + ...state + } + + return new Proxy(response, { + get (target, p) { + return p in state ? state[p] : target[p] + }, + set (target, p, value) { + assert(!(p in state)) + target[p] = value + return true + } + }) +} + +// https://fetch.spec.whatwg.org/#concept-filtered-response +function filterResponse (response, type) { + // Set response to the following filtered response with response as its + // internal response, depending on request’s response tainting: + if (type === 'basic') { + // A basic filtered response is a filtered response whose type is "basic" + // and header list excludes any headers in internal response’s header list + // whose name is a forbidden response-header name. + + // Note: undici does not implement forbidden response-header names + return makeFilteredResponse(response, { + type: 'basic', + headersList: response.headersList + }) + } else if (type === 'cors') { + // A CORS filtered response is a filtered response whose type is "cors" + // and header list excludes any headers in internal response’s header + // list whose name is not a CORS-safelisted response-header name, given + // internal response’s CORS-exposed header-name list. + + // Note: undici does not implement CORS-safelisted response-header names + return makeFilteredResponse(response, { + type: 'cors', + headersList: response.headersList + }) + } else if (type === 'opaque') { + // An opaque filtered response is a filtered response whose type is + // "opaque", URL list is the empty list, status is 0, status message + // is the empty byte sequence, header list is empty, and body is null. + + return makeFilteredResponse(response, { + type: 'opaque', + urlList: Object.freeze([]), + status: 0, + statusText: '', + body: null + }) + } else if (type === 'opaqueredirect') { + // An opaque-redirect filtered response is a filtered response whose type + // is "opaqueredirect", status is 0, status message is the empty byte + // sequence, header list is empty, and body is null. + + return makeFilteredResponse(response, { + type: 'opaqueredirect', + status: 0, + statusText: '', + headersList: [], + body: null + }) + } else { + assert(false) + } +} + +// https://fetch.spec.whatwg.org/#appropriate-network-error +function makeAppropriateNetworkError (fetchParams, err = null) { + // 1. Assert: fetchParams is canceled. + assert(isCancelled(fetchParams)) + + // 2. Return an aborted network error if fetchParams is aborted; + // otherwise return a network error. + return isAborted(fetchParams) + ? makeNetworkError(Object.assign(new DOMException('The operation was aborted.', 'AbortError'), { cause: err })) + : makeNetworkError(Object.assign(new DOMException('Request was cancelled.'), { cause: err })) +} + +// https://whatpr.org/fetch/1392.html#initialize-a-response +function initializeResponse (response, init, body) { + // 1. If init["status"] is not in the range 200 to 599, inclusive, then + // throw a RangeError. + if (init.status !== null && (init.status < 200 || init.status > 599)) { + throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.') + } + + // 2. If init["statusText"] does not match the reason-phrase token production, + // then throw a TypeError. + if ('statusText' in init && init.statusText != null) { + // See, https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2: + // reason-phrase = *( HTAB / SP / VCHAR / obs-text ) + if (!isValidReasonPhrase(String(init.statusText))) { + throw new TypeError('Invalid statusText') + } + } + + // 3. Set response’s response’s status to init["status"]. + if ('status' in init && init.status != null) { + getResponseState(response).status = init.status + } + + // 4. Set response’s response’s status message to init["statusText"]. + if ('statusText' in init && init.statusText != null) { + getResponseState(response).statusText = init.statusText + } + + // 5. If init["headers"] exists, then fill response’s headers with init["headers"]. + if ('headers' in init && init.headers != null) { + fill(getResponseHeaders(response), init.headers) + } + + // 6. If body was given, then: + if (body) { + // 1. If response's status is a null body status, then throw a TypeError. + if (nullBodyStatus.includes(response.status)) { + throw webidl.errors.exception({ + header: 'Response constructor', + message: `Invalid response status code ${response.status}` + }) + } + + // 2. Set response's body to body's body. + getResponseState(response).body = body.body + + // 3. If body's type is non-null and response's header list does not contain + // `Content-Type`, then append (`Content-Type`, body's type) to response's header list. + if (body.type != null && !getResponseState(response).headersList.contains('content-type', true)) { + getResponseState(response).headersList.append('content-type', body.type, true) + } + } +} + +/** + * @see https://fetch.spec.whatwg.org/#response-create + * @param {any} innerResponse + * @param {'request' | 'immutable' | 'request-no-cors' | 'response' | 'none'} guard + * @returns {Response} + */ +function fromInnerResponse (innerResponse, guard) { + const response = new Response(kConstruct) + setResponseState(response, innerResponse) + const headers = new Headers(kConstruct) + setResponseHeaders(response, headers) + setHeadersList(headers, innerResponse.headersList) + setHeadersGuard(headers, guard) + + if (innerResponse.body?.stream) { + // If the target (response) is reclaimed, the cleanup callback may be called at some point with + // the held value provided for it (innerResponse.body.stream). The held value can be any value: + // a primitive or an object, even undefined. If the held value is an object, the registry keeps + // a strong reference to it (so it can pass it to the cleanup callback later). Reworded from + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry + streamRegistry.register(response, new WeakRef(innerResponse.body.stream)) + } + + return response +} + +// https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit +webidl.converters.XMLHttpRequestBodyInit = function (V, prefix, name) { + if (typeof V === 'string') { + return webidl.converters.USVString(V, prefix, name) + } + + if (webidl.is.Blob(V)) { + return V + } + + if (ArrayBuffer.isView(V) || isArrayBuffer(V)) { + return V + } + + if (webidl.is.FormData(V)) { + return V + } + + if (webidl.is.URLSearchParams(V)) { + return V + } + + return webidl.converters.DOMString(V, prefix, name) +} + +// https://fetch.spec.whatwg.org/#bodyinit +webidl.converters.BodyInit = function (V, prefix, argument) { + if (webidl.is.ReadableStream(V)) { + return V + } + + // Note: the spec doesn't include async iterables, + // this is an undici extension. + if (V?.[Symbol.asyncIterator]) { + return V + } + + return webidl.converters.XMLHttpRequestBodyInit(V, prefix, argument) +} + +webidl.converters.ResponseInit = webidl.dictionaryConverter([ + { + key: 'status', + converter: webidl.converters['unsigned short'], + defaultValue: () => 200 + }, + { + key: 'statusText', + converter: webidl.converters.ByteString, + defaultValue: () => '' + }, + { + key: 'headers', + converter: webidl.converters.HeadersInit + } +]) + +webidl.is.Response = webidl.util.MakeTypeAssertion(Response) + +module.exports = { + isNetworkError, + makeNetworkError, + makeResponse, + makeAppropriateNetworkError, + filterResponse, + Response, + cloneResponse, + fromInnerResponse, + getResponseState +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/fetch/util.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/fetch/util.js new file mode 100644 index 0000000000000000000000000000000000000000..d71126ca88300c5d020641d85b2097e411fcc3d5 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/fetch/util.js @@ -0,0 +1,1564 @@ +'use strict' + +const { Transform } = require('node:stream') +const zlib = require('node:zlib') +const { redirectStatusSet, referrerPolicyTokens, badPortsSet } = require('./constants') +const { getGlobalOrigin } = require('./global') +const { collectASequenceOfCodePoints, collectAnHTTPQuotedString, removeChars, parseMIMEType } = require('./data-url') +const { performance } = require('node:perf_hooks') +const { ReadableStreamFrom, isValidHTTPToken, normalizedMethodRecordsBase } = require('../../core/util') +const assert = require('node:assert') +const { isUint8Array } = require('node:util/types') +const { webidl } = require('../webidl') + +function responseURL (response) { + // https://fetch.spec.whatwg.org/#responses + // A response has an associated URL. It is a pointer to the last URL + // in response’s URL list and null if response’s URL list is empty. + const urlList = response.urlList + const length = urlList.length + return length === 0 ? null : urlList[length - 1].toString() +} + +// https://fetch.spec.whatwg.org/#concept-response-location-url +function responseLocationURL (response, requestFragment) { + // 1. If response’s status is not a redirect status, then return null. + if (!redirectStatusSet.has(response.status)) { + return null + } + + // 2. Let location be the result of extracting header list values given + // `Location` and response’s header list. + let location = response.headersList.get('location', true) + + // 3. If location is a header value, then set location to the result of + // parsing location with response’s URL. + if (location !== null && isValidHeaderValue(location)) { + if (!isValidEncodedURL(location)) { + // Some websites respond location header in UTF-8 form without encoding them as ASCII + // and major browsers redirect them to correctly UTF-8 encoded addresses. + // Here, we handle that behavior in the same way. + location = normalizeBinaryStringToUtf8(location) + } + location = new URL(location, responseURL(response)) + } + + // 4. If location is a URL whose fragment is null, then set location’s + // fragment to requestFragment. + if (location && !location.hash) { + location.hash = requestFragment + } + + // 5. Return location. + return location +} + +/** + * @see https://www.rfc-editor.org/rfc/rfc1738#section-2.2 + * @param {string} url + * @returns {boolean} + */ +function isValidEncodedURL (url) { + for (let i = 0; i < url.length; ++i) { + const code = url.charCodeAt(i) + + if ( + code > 0x7E || // Non-US-ASCII + DEL + code < 0x20 // Control characters NUL - US + ) { + return false + } + } + return true +} + +/** + * If string contains non-ASCII characters, assumes it's UTF-8 encoded and decodes it. + * Since UTF-8 is a superset of ASCII, this will work for ASCII strings as well. + * @param {string} value + * @returns {string} + */ +function normalizeBinaryStringToUtf8 (value) { + return Buffer.from(value, 'binary').toString('utf8') +} + +/** @returns {URL} */ +function requestCurrentURL (request) { + return request.urlList[request.urlList.length - 1] +} + +function requestBadPort (request) { + // 1. Let url be request’s current URL. + const url = requestCurrentURL(request) + + // 2. If url’s scheme is an HTTP(S) scheme and url’s port is a bad port, + // then return blocked. + if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) { + return 'blocked' + } + + // 3. Return allowed. + return 'allowed' +} + +function isErrorLike (object) { + return object instanceof Error || ( + object?.constructor?.name === 'Error' || + object?.constructor?.name === 'DOMException' + ) +} + +// Check whether |statusText| is a ByteString and +// matches the Reason-Phrase token production. +// RFC 2616: https://tools.ietf.org/html/rfc2616 +// RFC 7230: https://tools.ietf.org/html/rfc7230 +// "reason-phrase = *( HTAB / SP / VCHAR / obs-text )" +// https://github.com/chromium/chromium/blob/94.0.4604.1/third_party/blink/renderer/core/fetch/response.cc#L116 +function isValidReasonPhrase (statusText) { + for (let i = 0; i < statusText.length; ++i) { + const c = statusText.charCodeAt(i) + if ( + !( + ( + c === 0x09 || // HTAB + (c >= 0x20 && c <= 0x7e) || // SP / VCHAR + (c >= 0x80 && c <= 0xff) + ) // obs-text + ) + ) { + return false + } + } + return true +} + +/** + * @see https://fetch.spec.whatwg.org/#header-name + * @param {string} potentialValue + */ +const isValidHeaderName = isValidHTTPToken + +/** + * @see https://fetch.spec.whatwg.org/#header-value + * @param {string} potentialValue + */ +function isValidHeaderValue (potentialValue) { + // - Has no leading or trailing HTTP tab or space bytes. + // - Contains no 0x00 (NUL) or HTTP newline bytes. + return ( + potentialValue[0] === '\t' || + potentialValue[0] === ' ' || + potentialValue[potentialValue.length - 1] === '\t' || + potentialValue[potentialValue.length - 1] === ' ' || + potentialValue.includes('\n') || + potentialValue.includes('\r') || + potentialValue.includes('\0') + ) === false +} + +/** + * Parse a referrer policy from a Referrer-Policy header + * @see https://w3c.github.io/webappsec-referrer-policy/#parse-referrer-policy-from-header + */ +function parseReferrerPolicy (actualResponse) { + // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` and response’s header list. + const policyHeader = (actualResponse.headersList.get('referrer-policy', true) ?? '').split(',') + + // 2. Let policy be the empty string. + let policy = '' + + // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty string, then set policy to token. + + // Note: As the referrer-policy can contain multiple policies + // separated by comma, we need to loop through all of them + // and pick the first valid one. + // Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#specify_a_fallback_policy + if (policyHeader.length) { + // The right-most policy takes precedence. + // The left-most policy is the fallback. + for (let i = policyHeader.length; i !== 0; i--) { + const token = policyHeader[i - 1].trim() + if (referrerPolicyTokens.has(token)) { + policy = token + break + } + } + } + + // 4. Return policy. + return policy +} + +/** + * Given a request request and a response actualResponse, this algorithm + * updates request’s referrer policy according to the Referrer-Policy + * header (if any) in actualResponse. + * @see https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect + * @param {import('./request').Request} request + * @param {import('./response').Response} actualResponse + */ +function setRequestReferrerPolicyOnRedirect (request, actualResponse) { + // 1. Let policy be the result of executing § 8.1 Parse a referrer policy + // from a Referrer-Policy header on actualResponse. + const policy = parseReferrerPolicy(actualResponse) + + // 2. If policy is not the empty string, then set request’s referrer policy to policy. + if (policy !== '') { + request.referrerPolicy = policy + } +} + +// https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check +function crossOriginResourcePolicyCheck () { + // TODO + return 'allowed' +} + +// https://fetch.spec.whatwg.org/#concept-cors-check +function corsCheck () { + // TODO + return 'success' +} + +// https://fetch.spec.whatwg.org/#concept-tao-check +function TAOCheck () { + // TODO + return 'success' +} + +function appendFetchMetadata (httpRequest) { + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header + // TODO + + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header + + // 1. Assert: r’s url is a potentially trustworthy URL. + // TODO + + // 2. Let header be a Structured Header whose value is a token. + let header = null + + // 3. Set header’s value to r’s mode. + header = httpRequest.mode + + // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list. + httpRequest.headersList.set('sec-fetch-mode', header, true) + + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header + // TODO + + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header + // TODO +} + +// https://fetch.spec.whatwg.org/#append-a-request-origin-header +function appendRequestOriginHeader (request) { + // 1. Let serializedOrigin be the result of byte-serializing a request origin + // with request. + // TODO: implement "byte-serializing a request origin" + let serializedOrigin = request.origin + + // - "'client' is changed to an origin during fetching." + // This doesn't happen in undici (in most cases) because undici, by default, + // has no concept of origin. + // - request.origin can also be set to request.client.origin (client being + // an environment settings object), which is undefined without using + // setGlobalOrigin. + if (serializedOrigin === 'client' || serializedOrigin === undefined) { + return + } + + // 2. If request’s response tainting is "cors" or request’s mode is "websocket", + // then append (`Origin`, serializedOrigin) to request’s header list. + // 3. Otherwise, if request’s method is neither `GET` nor `HEAD`, then: + if (request.responseTainting === 'cors' || request.mode === 'websocket') { + request.headersList.append('origin', serializedOrigin, true) + } else if (request.method !== 'GET' && request.method !== 'HEAD') { + // 1. Switch on request’s referrer policy: + switch (request.referrerPolicy) { + case 'no-referrer': + // Set serializedOrigin to `null`. + serializedOrigin = null + break + case 'no-referrer-when-downgrade': + case 'strict-origin': + case 'strict-origin-when-cross-origin': + // If request’s origin is a tuple origin, its scheme is "https", and + // request’s current URL’s scheme is not "https", then set + // serializedOrigin to `null`. + if (request.origin && urlHasHttpsScheme(request.origin) && !urlHasHttpsScheme(requestCurrentURL(request))) { + serializedOrigin = null + } + break + case 'same-origin': + // If request’s origin is not same origin with request’s current URL’s + // origin, then set serializedOrigin to `null`. + if (!sameOrigin(request, requestCurrentURL(request))) { + serializedOrigin = null + } + break + default: + // Do nothing. + } + + // 2. Append (`Origin`, serializedOrigin) to request’s header list. + request.headersList.append('origin', serializedOrigin, true) + } +} + +// https://w3c.github.io/hr-time/#dfn-coarsen-time +function coarsenTime (timestamp, crossOriginIsolatedCapability) { + // TODO + return timestamp +} + +// https://fetch.spec.whatwg.org/#clamp-and-coarsen-connection-timing-info +function clampAndCoarsenConnectionTimingInfo (connectionTimingInfo, defaultStartTime, crossOriginIsolatedCapability) { + if (!connectionTimingInfo?.startTime || connectionTimingInfo.startTime < defaultStartTime) { + return { + domainLookupStartTime: defaultStartTime, + domainLookupEndTime: defaultStartTime, + connectionStartTime: defaultStartTime, + connectionEndTime: defaultStartTime, + secureConnectionStartTime: defaultStartTime, + ALPNNegotiatedProtocol: connectionTimingInfo?.ALPNNegotiatedProtocol + } + } + + return { + domainLookupStartTime: coarsenTime(connectionTimingInfo.domainLookupStartTime, crossOriginIsolatedCapability), + domainLookupEndTime: coarsenTime(connectionTimingInfo.domainLookupEndTime, crossOriginIsolatedCapability), + connectionStartTime: coarsenTime(connectionTimingInfo.connectionStartTime, crossOriginIsolatedCapability), + connectionEndTime: coarsenTime(connectionTimingInfo.connectionEndTime, crossOriginIsolatedCapability), + secureConnectionStartTime: coarsenTime(connectionTimingInfo.secureConnectionStartTime, crossOriginIsolatedCapability), + ALPNNegotiatedProtocol: connectionTimingInfo.ALPNNegotiatedProtocol + } +} + +// https://w3c.github.io/hr-time/#dfn-coarsened-shared-current-time +function coarsenedSharedCurrentTime (crossOriginIsolatedCapability) { + return coarsenTime(performance.now(), crossOriginIsolatedCapability) +} + +// https://fetch.spec.whatwg.org/#create-an-opaque-timing-info +function createOpaqueTimingInfo (timingInfo) { + return { + startTime: timingInfo.startTime ?? 0, + redirectStartTime: 0, + redirectEndTime: 0, + postRedirectStartTime: timingInfo.startTime ?? 0, + finalServiceWorkerStartTime: 0, + finalNetworkResponseStartTime: 0, + finalNetworkRequestStartTime: 0, + endTime: 0, + encodedBodySize: 0, + decodedBodySize: 0, + finalConnectionTimingInfo: null + } +} + +// https://html.spec.whatwg.org/multipage/origin.html#policy-container +function makePolicyContainer () { + // Note: the fetch spec doesn't make use of embedder policy or CSP list + return { + referrerPolicy: 'strict-origin-when-cross-origin' + } +} + +// https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container +function clonePolicyContainer (policyContainer) { + return { + referrerPolicy: policyContainer.referrerPolicy + } +} + +/** + * Determine request’s Referrer + * + * @see https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer + */ +function determineRequestsReferrer (request) { + // Given a request request, we can determine the correct referrer information + // to send by examining its referrer policy as detailed in the following + // steps, which return either no referrer or a URL: + + // 1. Let policy be request's referrer policy. + const policy = request.referrerPolicy + + // Note: policy cannot (shouldn't) be null or an empty string. + assert(policy) + + // 2. Let environment be request’s client. + + let referrerSource = null + + // 3. Switch on request’s referrer: + + // "client" + if (request.referrer === 'client') { + // Note: node isn't a browser and doesn't implement document/iframes, + // so we bypass this step and replace it with our own. + + const globalOrigin = getGlobalOrigin() + + if (!globalOrigin || globalOrigin.origin === 'null') { + return 'no-referrer' + } + + // Note: we need to clone it as it's mutated + referrerSource = new URL(globalOrigin) + // a URL + } else if (webidl.is.URL(request.referrer)) { + // Let referrerSource be request’s referrer. + referrerSource = request.referrer + } + + // 4. Let request’s referrerURL be the result of stripping referrerSource for + // use as a referrer. + let referrerURL = stripURLForReferrer(referrerSource) + + // 5. Let referrerOrigin be the result of stripping referrerSource for use as + // a referrer, with the origin-only flag set to true. + const referrerOrigin = stripURLForReferrer(referrerSource, true) + + // 6. If the result of serializing referrerURL is a string whose length is + // greater than 4096, set referrerURL to referrerOrigin. + if (referrerURL.toString().length > 4096) { + referrerURL = referrerOrigin + } + + // 7. The user agent MAY alter referrerURL or referrerOrigin at this point + // to enforce arbitrary policy considerations in the interests of minimizing + // data leakage. For example, the user agent could strip the URL down to an + // origin, modify its host, replace it with an empty string, etc. + + // 8. Execute the switch statements corresponding to the value of policy: + switch (policy) { + case 'no-referrer': + // Return no referrer + return 'no-referrer' + case 'origin': + // Return referrerOrigin + if (referrerOrigin != null) { + return referrerOrigin + } + return stripURLForReferrer(referrerSource, true) + case 'unsafe-url': + // Return referrerURL. + return referrerURL + case 'strict-origin': { + const currentURL = requestCurrentURL(request) + + // 1. If referrerURL is a potentially trustworthy URL and request’s + // current URL is not a potentially trustworthy URL, then return no + // referrer. + if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) { + return 'no-referrer' + } + // 2. Return referrerOrigin + return referrerOrigin + } + case 'strict-origin-when-cross-origin': { + const currentURL = requestCurrentURL(request) + + // 1. If the origin of referrerURL and the origin of request’s current + // URL are the same, then return referrerURL. + if (sameOrigin(referrerURL, currentURL)) { + return referrerURL + } + + // 2. If referrerURL is a potentially trustworthy URL and request’s + // current URL is not a potentially trustworthy URL, then return no + // referrer. + if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) { + return 'no-referrer' + } + + // 3. Return referrerOrigin. + return referrerOrigin + } + case 'same-origin': + // 1. If the origin of referrerURL and the origin of request’s current + // URL are the same, then return referrerURL. + if (sameOrigin(request, referrerURL)) { + return referrerURL + } + // 2. Return no referrer. + return 'no-referrer' + case 'origin-when-cross-origin': + // 1. If the origin of referrerURL and the origin of request’s current + // URL are the same, then return referrerURL. + if (sameOrigin(request, referrerURL)) { + return referrerURL + } + // 2. Return referrerOrigin. + return referrerOrigin + case 'no-referrer-when-downgrade': { + const currentURL = requestCurrentURL(request) + + // 1. If referrerURL is a potentially trustworthy URL and request’s + // current URL is not a potentially trustworthy URL, then return no + // referrer. + if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) { + return 'no-referrer' + } + // 2. Return referrerOrigin + return referrerOrigin + } + } +} + +/** + * Certain portions of URLs must not be included when sending a URL as the + * value of a `Referer` header: a URLs fragment, username, and password + * components must be stripped from the URL before it’s sent out. This + * algorithm accepts a origin-only flag, which defaults to false. If set to + * true, the algorithm will additionally remove the URL’s path and query + * components, leaving only the scheme, host, and port. + * + * @see https://w3c.github.io/webappsec-referrer-policy/#strip-url + * @param {URL} url + * @param {boolean} [originOnly=false] + */ +function stripURLForReferrer (url, originOnly = false) { + // 1. Assert: url is a URL. + assert(webidl.is.URL(url)) + + // Note: Create a new URL instance to avoid mutating the original URL. + url = new URL(url) + + // 2. If url’s scheme is a local scheme, then return no referrer. + if (urlIsLocal(url)) { + return 'no-referrer' + } + + // 3. Set url’s username to the empty string. + url.username = '' + + // 4. Set url’s password to the empty string. + url.password = '' + + // 5. Set url’s fragment to null. + url.hash = '' + + // 6. If the origin-only flag is true, then: + if (originOnly === true) { + // 1. Set url’s path to « the empty string ». + url.pathname = '' + + // 2. Set url’s query to null. + url.search = '' + } + + // 7. Return url. + return url +} + +const potentialleTrustworthyIPv4RegExp = new RegExp('^(?:' + + '(?:127\\.)' + + '(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){2}' + + '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])' + +')$') + +const potentialleTrustworthyIPv6RegExp = new RegExp('^(?:' + + '(?:(?:0{1,4}):){7}(?:(?:0{0,3}1))|' + + '(?:(?:0{1,4}):){1,6}(?::(?:0{0,3}1))|' + + '(?:::(?:0{0,3}1))|' + +')$') + +/** + * Check if host matches one of the CIDR notations 127.0.0.0/8 or ::1/128. + * + * @param {string} origin + * @returns {boolean} + */ +function isOriginIPPotentiallyTrustworthy (origin) { + // IPv6 + if (origin.includes(':')) { + // Remove brackets from IPv6 addresses + if (origin[0] === '[' && origin[origin.length - 1] === ']') { + origin = origin.slice(1, -1) + } + return potentialleTrustworthyIPv6RegExp.test(origin) + } + + // IPv4 + return potentialleTrustworthyIPv4RegExp.test(origin) +} + +/** + * A potentially trustworthy origin is one which a user agent can generally + * trust as delivering data securely. + * + * Return value `true` means `Potentially Trustworthy`. + * Return value `false` means `Not Trustworthy`. + * + * @see https://w3c.github.io/webappsec-secure-contexts/#is-origin-trustworthy + * @param {string} origin + * @returns {boolean} + */ +function isOriginPotentiallyTrustworthy (origin) { + // 1. If origin is an opaque origin, return "Not Trustworthy". + if (origin == null || origin === 'null') { + return false + } + + // 2. Assert: origin is a tuple origin. + origin = new URL(origin) + + // 3. If origin’s scheme is either "https" or "wss", + // return "Potentially Trustworthy". + if (origin.protocol === 'https:' || origin.protocol === 'wss:') { + return true + } + + // 4. If origin’s host matches one of the CIDR notations 127.0.0.0/8 or + // ::1/128 [RFC4632], return "Potentially Trustworthy". + if (isOriginIPPotentiallyTrustworthy(origin.hostname)) { + return true + } + + // 5. If the user agent conforms to the name resolution rules in + // [let-localhost-be-localhost] and one of the following is true: + + // origin’s host is "localhost" or "localhost." + if (origin.hostname === 'localhost' || origin.hostname === 'localhost.') { + return true + } + + // origin’s host ends with ".localhost" or ".localhost." + if (origin.hostname.endsWith('.localhost') || origin.hostname.endsWith('.localhost.')) { + return true + } + + // 6. If origin’s scheme is "file", return "Potentially Trustworthy". + if (origin.protocol === 'file:') { + return true + } + + // 7. If origin’s scheme component is one which the user agent considers to + // be authenticated, return "Potentially Trustworthy". + + // 8. If origin has been configured as a trustworthy origin, return + // "Potentially Trustworthy". + + // 9. Return "Not Trustworthy". + return false +} + +/** + * A potentially trustworthy URL is one which either inherits context from its + * creator (about:blank, about:srcdoc, data) or one whose origin is a + * potentially trustworthy origin. + * + * Return value `true` means `Potentially Trustworthy`. + * Return value `false` means `Not Trustworthy`. + * + * @see https://www.w3.org/TR/secure-contexts/#is-url-trustworthy + * @param {URL} url + * @returns {boolean} + */ +function isURLPotentiallyTrustworthy (url) { + // Given a URL record (url), the following algorithm returns "Potentially + // Trustworthy" or "Not Trustworthy" as appropriate: + if (!webidl.is.URL(url)) { + return false + } + + // 1. If url is "about:blank" or "about:srcdoc", + // return "Potentially Trustworthy". + if (url.href === 'about:blank' || url.href === 'about:srcdoc') { + return true + } + + // 2. If url’s scheme is "data", return "Potentially Trustworthy". + if (url.protocol === 'data:') return true + + // Note: The origin of blob: URLs is the origin of the context in which they + // were created. Therefore, blobs created in a trustworthy origin will + // themselves be potentially trustworthy. + if (url.protocol === 'blob:') return true + + // 3. Return the result of executing § 3.1 Is origin potentially trustworthy? + // on url’s origin. + return isOriginPotentiallyTrustworthy(url.origin) +} + +// https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request +function tryUpgradeRequestToAPotentiallyTrustworthyURL (request) { + // TODO +} + +/** + * @link {https://html.spec.whatwg.org/multipage/origin.html#same-origin} + * @param {URL} A + * @param {URL} B + */ +function sameOrigin (A, B) { + // 1. If A and B are the same opaque origin, then return true. + if (A.origin === B.origin && A.origin === 'null') { + return true + } + + // 2. If A and B are both tuple origins and their schemes, + // hosts, and port are identical, then return true. + if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) { + return true + } + + // 3. Return false. + return false +} + +function isAborted (fetchParams) { + return fetchParams.controller.state === 'aborted' +} + +function isCancelled (fetchParams) { + return fetchParams.controller.state === 'aborted' || + fetchParams.controller.state === 'terminated' +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-method-normalize + * @param {string} method + */ +function normalizeMethod (method) { + return normalizedMethodRecordsBase[method.toLowerCase()] ?? method +} + +// https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string +function serializeJavascriptValueToJSONString (value) { + // 1. Let result be ? Call(%JSON.stringify%, undefined, « value »). + const result = JSON.stringify(value) + + // 2. If result is undefined, then throw a TypeError. + if (result === undefined) { + throw new TypeError('Value is not JSON serializable') + } + + // 3. Assert: result is a string. + assert(typeof result === 'string') + + // 4. Return result. + return result +} + +// https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object +const esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())) + +/** + * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object + * @param {string} name name of the instance + * @param {((target: any) => any)} kInternalIterator + * @param {string | number} [keyIndex] + * @param {string | number} [valueIndex] + */ +function createIterator (name, kInternalIterator, keyIndex = 0, valueIndex = 1) { + class FastIterableIterator { + /** @type {any} */ + #target + /** @type {'key' | 'value' | 'key+value'} */ + #kind + /** @type {number} */ + #index + + /** + * @see https://webidl.spec.whatwg.org/#dfn-default-iterator-object + * @param {unknown} target + * @param {'key' | 'value' | 'key+value'} kind + */ + constructor (target, kind) { + this.#target = target + this.#kind = kind + this.#index = 0 + } + + next () { + // 1. Let interface be the interface for which the iterator prototype object exists. + // 2. Let thisValue be the this value. + // 3. Let object be ? ToObject(thisValue). + // 4. If object is a platform object, then perform a security + // check, passing: + // 5. If object is not a default iterator object for interface, + // then throw a TypeError. + if (typeof this !== 'object' || this === null || !(#target in this)) { + throw new TypeError( + `'next' called on an object that does not implement interface ${name} Iterator.` + ) + } + + // 6. Let index be object’s index. + // 7. Let kind be object’s kind. + // 8. Let values be object’s target's value pairs to iterate over. + const index = this.#index + const values = kInternalIterator(this.#target) + + // 9. Let len be the length of values. + const len = values.length + + // 10. If index is greater than or equal to len, then return + // CreateIterResultObject(undefined, true). + if (index >= len) { + return { + value: undefined, + done: true + } + } + + // 11. Let pair be the entry in values at index index. + const { [keyIndex]: key, [valueIndex]: value } = values[index] + + // 12. Set object’s index to index + 1. + this.#index = index + 1 + + // 13. Return the iterator result for pair and kind. + + // https://webidl.spec.whatwg.org/#iterator-result + + // 1. Let result be a value determined by the value of kind: + let result + switch (this.#kind) { + case 'key': + // 1. Let idlKey be pair’s key. + // 2. Let key be the result of converting idlKey to an + // ECMAScript value. + // 3. result is key. + result = key + break + case 'value': + // 1. Let idlValue be pair’s value. + // 2. Let value be the result of converting idlValue to + // an ECMAScript value. + // 3. result is value. + result = value + break + case 'key+value': + // 1. Let idlKey be pair’s key. + // 2. Let idlValue be pair’s value. + // 3. Let key be the result of converting idlKey to an + // ECMAScript value. + // 4. Let value be the result of converting idlValue to + // an ECMAScript value. + // 5. Let array be ! ArrayCreate(2). + // 6. Call ! CreateDataProperty(array, "0", key). + // 7. Call ! CreateDataProperty(array, "1", value). + // 8. result is array. + result = [key, value] + break + } + + // 2. Return CreateIterResultObject(result, false). + return { + value: result, + done: false + } + } + } + + // https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object + // @ts-ignore + delete FastIterableIterator.prototype.constructor + + Object.setPrototypeOf(FastIterableIterator.prototype, esIteratorPrototype) + + Object.defineProperties(FastIterableIterator.prototype, { + [Symbol.toStringTag]: { + writable: false, + enumerable: false, + configurable: true, + value: `${name} Iterator` + }, + next: { writable: true, enumerable: true, configurable: true } + }) + + /** + * @param {unknown} target + * @param {'key' | 'value' | 'key+value'} kind + * @returns {IterableIterator} + */ + return function (target, kind) { + return new FastIterableIterator(target, kind) + } +} + +/** + * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object + * @param {string} name name of the instance + * @param {any} object class + * @param {(target: any) => any} kInternalIterator + * @param {string | number} [keyIndex] + * @param {string | number} [valueIndex] + */ +function iteratorMixin (name, object, kInternalIterator, keyIndex = 0, valueIndex = 1) { + const makeIterator = createIterator(name, kInternalIterator, keyIndex, valueIndex) + + const properties = { + keys: { + writable: true, + enumerable: true, + configurable: true, + value: function keys () { + webidl.brandCheck(this, object) + return makeIterator(this, 'key') + } + }, + values: { + writable: true, + enumerable: true, + configurable: true, + value: function values () { + webidl.brandCheck(this, object) + return makeIterator(this, 'value') + } + }, + entries: { + writable: true, + enumerable: true, + configurable: true, + value: function entries () { + webidl.brandCheck(this, object) + return makeIterator(this, 'key+value') + } + }, + forEach: { + writable: true, + enumerable: true, + configurable: true, + value: function forEach (callbackfn, thisArg = globalThis) { + webidl.brandCheck(this, object) + webidl.argumentLengthCheck(arguments, 1, `${name}.forEach`) + if (typeof callbackfn !== 'function') { + throw new TypeError( + `Failed to execute 'forEach' on '${name}': parameter 1 is not of type 'Function'.` + ) + } + for (const { 0: key, 1: value } of makeIterator(this, 'key+value')) { + callbackfn.call(thisArg, value, key, this) + } + } + } + } + + return Object.defineProperties(object.prototype, { + ...properties, + [Symbol.iterator]: { + writable: true, + enumerable: false, + configurable: true, + value: properties.entries.value + } + }) +} + +/** + * @param {import('./body').ExtractBodyResult} body + * @param {(bytes: Uint8Array) => void} processBody + * @param {(error: Error) => void} processBodyError + * @returns {void} + * + * @see https://fetch.spec.whatwg.org/#body-fully-read + */ +function fullyReadBody (body, processBody, processBodyError) { + // 1. If taskDestination is null, then set taskDestination to + // the result of starting a new parallel queue. + + // 2. Let successSteps given a byte sequence bytes be to queue a + // fetch task to run processBody given bytes, with taskDestination. + const successSteps = processBody + + // 3. Let errorSteps be to queue a fetch task to run processBodyError, + // with taskDestination. + const errorSteps = processBodyError + + try { + // 4. Let reader be the result of getting a reader for body’s stream. + // If that threw an exception, then run errorSteps with that + // exception and return. + const reader = body.stream.getReader() + + // 5. Read all bytes from reader, given successSteps and errorSteps. + readAllBytes(reader, successSteps, errorSteps) + } catch (e) { + errorSteps(e) + } +} + +/** + * @param {ReadableStreamController} controller + */ +function readableStreamClose (controller) { + try { + controller.close() + controller.byobRequest?.respond(0) + } catch (err) { + // TODO: add comment explaining why this error occurs. + if (!err.message.includes('Controller is already closed') && !err.message.includes('ReadableStream is already closed')) { + throw err + } + } +} + +const invalidIsomorphicEncodeValueRegex = /[^\x00-\xFF]/ // eslint-disable-line + +/** + * @see https://infra.spec.whatwg.org/#isomorphic-encode + * @param {string} input + */ +function isomorphicEncode (input) { + // 1. Assert: input contains no code points greater than U+00FF. + assert(!invalidIsomorphicEncodeValueRegex.test(input)) + + // 2. Return a byte sequence whose length is equal to input’s code + // point length and whose bytes have the same values as the + // values of input’s code points, in the same order + return input +} + +/** + * @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes + * @see https://streams.spec.whatwg.org/#read-loop + * @param {ReadableStream>} reader + * @param {(bytes: Uint8Array) => void} successSteps + * @param {(error: Error) => void} failureSteps + * @returns {Promise} + */ +async function readAllBytes (reader, successSteps, failureSteps) { + try { + const bytes = [] + let byteLength = 0 + + do { + const { done, value: chunk } = await reader.read() + + if (done) { + // 1. Call successSteps with bytes. + successSteps(Buffer.concat(bytes, byteLength)) + return + } + + // 1. If chunk is not a Uint8Array object, call failureSteps + // with a TypeError and abort these steps. + if (!isUint8Array(chunk)) { + failureSteps(new TypeError('Received non-Uint8Array chunk')) + return + } + + // 2. Append the bytes represented by chunk to bytes. + bytes.push(chunk) + byteLength += chunk.length + + // 3. Read-loop given reader, bytes, successSteps, and failureSteps. + } while (true) + } catch (e) { + // 1. Call failureSteps with e. + failureSteps(e) + } +} + +/** + * @see https://fetch.spec.whatwg.org/#is-local + * @param {URL} url + * @returns {boolean} + */ +function urlIsLocal (url) { + assert('protocol' in url) // ensure it's a url object + + const protocol = url.protocol + + // A URL is local if its scheme is a local scheme. + // A local scheme is "about", "blob", or "data". + return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:' +} + +/** + * @param {string|URL} url + * @returns {boolean} + */ +function urlHasHttpsScheme (url) { + return ( + ( + typeof url === 'string' && + url[5] === ':' && + url[0] === 'h' && + url[1] === 't' && + url[2] === 't' && + url[3] === 'p' && + url[4] === 's' + ) || + url.protocol === 'https:' + ) +} + +/** + * @see https://fetch.spec.whatwg.org/#http-scheme + * @param {URL} url + */ +function urlIsHttpHttpsScheme (url) { + assert('protocol' in url) // ensure it's a url object + + const protocol = url.protocol + + return protocol === 'http:' || protocol === 'https:' +} + +/** + * @typedef {Object} RangeHeaderValue + * @property {number|null} rangeStartValue + * @property {number|null} rangeEndValue + */ + +/** + * @see https://fetch.spec.whatwg.org/#simple-range-header-value + * @param {string} value + * @param {boolean} allowWhitespace + * @return {RangeHeaderValue|'failure'} + */ +function simpleRangeHeaderValue (value, allowWhitespace) { + // 1. Let data be the isomorphic decoding of value. + // Note: isomorphic decoding takes a sequence of bytes (ie. a Uint8Array) and turns it into a string, + // nothing more. We obviously don't need to do that if value is a string already. + const data = value + + // 2. If data does not start with "bytes", then return failure. + if (!data.startsWith('bytes')) { + return 'failure' + } + + // 3. Let position be a position variable for data, initially pointing at the 5th code point of data. + const position = { position: 5 } + + // 4. If allowWhitespace is true, collect a sequence of code points that are HTTP tab or space, + // from data given position. + if (allowWhitespace) { + collectASequenceOfCodePoints( + (char) => char === '\t' || char === ' ', + data, + position + ) + } + + // 5. If the code point at position within data is not U+003D (=), then return failure. + if (data.charCodeAt(position.position) !== 0x3D) { + return 'failure' + } + + // 6. Advance position by 1. + position.position++ + + // 7. If allowWhitespace is true, collect a sequence of code points that are HTTP tab or space, from + // data given position. + if (allowWhitespace) { + collectASequenceOfCodePoints( + (char) => char === '\t' || char === ' ', + data, + position + ) + } + + // 8. Let rangeStart be the result of collecting a sequence of code points that are ASCII digits, + // from data given position. + const rangeStart = collectASequenceOfCodePoints( + (char) => { + const code = char.charCodeAt(0) + + return code >= 0x30 && code <= 0x39 + }, + data, + position + ) + + // 9. Let rangeStartValue be rangeStart, interpreted as decimal number, if rangeStart is not the + // empty string; otherwise null. + const rangeStartValue = rangeStart.length ? Number(rangeStart) : null + + // 10. If allowWhitespace is true, collect a sequence of code points that are HTTP tab or space, + // from data given position. + if (allowWhitespace) { + collectASequenceOfCodePoints( + (char) => char === '\t' || char === ' ', + data, + position + ) + } + + // 11. If the code point at position within data is not U+002D (-), then return failure. + if (data.charCodeAt(position.position) !== 0x2D) { + return 'failure' + } + + // 12. Advance position by 1. + position.position++ + + // 13. If allowWhitespace is true, collect a sequence of code points that are HTTP tab + // or space, from data given position. + // Note from Khafra: its the same step as in #8 again lol + if (allowWhitespace) { + collectASequenceOfCodePoints( + (char) => char === '\t' || char === ' ', + data, + position + ) + } + + // 14. Let rangeEnd be the result of collecting a sequence of code points that are + // ASCII digits, from data given position. + // Note from Khafra: you wouldn't guess it, but this is also the same step as #8 + const rangeEnd = collectASequenceOfCodePoints( + (char) => { + const code = char.charCodeAt(0) + + return code >= 0x30 && code <= 0x39 + }, + data, + position + ) + + // 15. Let rangeEndValue be rangeEnd, interpreted as decimal number, if rangeEnd + // is not the empty string; otherwise null. + // Note from Khafra: THE SAME STEP, AGAIN!!! + // Note: why interpret as a decimal if we only collect ascii digits? + const rangeEndValue = rangeEnd.length ? Number(rangeEnd) : null + + // 16. If position is not past the end of data, then return failure. + if (position.position < data.length) { + return 'failure' + } + + // 17. If rangeEndValue and rangeStartValue are null, then return failure. + if (rangeEndValue === null && rangeStartValue === null) { + return 'failure' + } + + // 18. If rangeStartValue and rangeEndValue are numbers, and rangeStartValue is + // greater than rangeEndValue, then return failure. + // Note: ... when can they not be numbers? + if (rangeStartValue > rangeEndValue) { + return 'failure' + } + + // 19. Return (rangeStartValue, rangeEndValue). + return { rangeStartValue, rangeEndValue } +} + +/** + * @see https://fetch.spec.whatwg.org/#build-a-content-range + * @param {number} rangeStart + * @param {number} rangeEnd + * @param {number} fullLength + */ +function buildContentRange (rangeStart, rangeEnd, fullLength) { + // 1. Let contentRange be `bytes `. + let contentRange = 'bytes ' + + // 2. Append rangeStart, serialized and isomorphic encoded, to contentRange. + contentRange += isomorphicEncode(`${rangeStart}`) + + // 3. Append 0x2D (-) to contentRange. + contentRange += '-' + + // 4. Append rangeEnd, serialized and isomorphic encoded to contentRange. + contentRange += isomorphicEncode(`${rangeEnd}`) + + // 5. Append 0x2F (/) to contentRange. + contentRange += '/' + + // 6. Append fullLength, serialized and isomorphic encoded to contentRange. + contentRange += isomorphicEncode(`${fullLength}`) + + // 7. Return contentRange. + return contentRange +} + +// A Stream, which pipes the response to zlib.createInflate() or +// zlib.createInflateRaw() depending on the first byte of the Buffer. +// If the lower byte of the first byte is 0x08, then the stream is +// interpreted as a zlib stream, otherwise it's interpreted as a +// raw deflate stream. +class InflateStream extends Transform { + #zlibOptions + + /** @param {zlib.ZlibOptions} [zlibOptions] */ + constructor (zlibOptions) { + super() + this.#zlibOptions = zlibOptions + } + + _transform (chunk, encoding, callback) { + if (!this._inflateStream) { + if (chunk.length === 0) { + callback() + return + } + this._inflateStream = (chunk[0] & 0x0F) === 0x08 + ? zlib.createInflate(this.#zlibOptions) + : zlib.createInflateRaw(this.#zlibOptions) + + this._inflateStream.on('data', this.push.bind(this)) + this._inflateStream.on('end', () => this.push(null)) + this._inflateStream.on('error', (err) => this.destroy(err)) + } + + this._inflateStream.write(chunk, encoding, callback) + } + + _final (callback) { + if (this._inflateStream) { + this._inflateStream.end() + this._inflateStream = null + } + callback() + } +} + +/** + * @param {zlib.ZlibOptions} [zlibOptions] + * @returns {InflateStream} + */ +function createInflate (zlibOptions) { + return new InflateStream(zlibOptions) +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-header-extract-mime-type + * @param {import('./headers').HeadersList} headers + */ +function extractMimeType (headers) { + // 1. Let charset be null. + let charset = null + + // 2. Let essence be null. + let essence = null + + // 3. Let mimeType be null. + let mimeType = null + + // 4. Let values be the result of getting, decoding, and splitting `Content-Type` from headers. + const values = getDecodeSplit('content-type', headers) + + // 5. If values is null, then return failure. + if (values === null) { + return 'failure' + } + + // 6. For each value of values: + for (const value of values) { + // 6.1. Let temporaryMimeType be the result of parsing value. + const temporaryMimeType = parseMIMEType(value) + + // 6.2. If temporaryMimeType is failure or its essence is "*/*", then continue. + if (temporaryMimeType === 'failure' || temporaryMimeType.essence === '*/*') { + continue + } + + // 6.3. Set mimeType to temporaryMimeType. + mimeType = temporaryMimeType + + // 6.4. If mimeType’s essence is not essence, then: + if (mimeType.essence !== essence) { + // 6.4.1. Set charset to null. + charset = null + + // 6.4.2. If mimeType’s parameters["charset"] exists, then set charset to + // mimeType’s parameters["charset"]. + if (mimeType.parameters.has('charset')) { + charset = mimeType.parameters.get('charset') + } + + // 6.4.3. Set essence to mimeType’s essence. + essence = mimeType.essence + } else if (!mimeType.parameters.has('charset') && charset !== null) { + // 6.5. Otherwise, if mimeType’s parameters["charset"] does not exist, and + // charset is non-null, set mimeType’s parameters["charset"] to charset. + mimeType.parameters.set('charset', charset) + } + } + + // 7. If mimeType is null, then return failure. + if (mimeType == null) { + return 'failure' + } + + // 8. Return mimeType. + return mimeType +} + +/** + * @see https://fetch.spec.whatwg.org/#header-value-get-decode-and-split + * @param {string|null} value + */ +function gettingDecodingSplitting (value) { + // 1. Let input be the result of isomorphic decoding value. + const input = value + + // 2. Let position be a position variable for input, initially pointing at the start of input. + const position = { position: 0 } + + // 3. Let values be a list of strings, initially empty. + const values = [] + + // 4. Let temporaryValue be the empty string. + let temporaryValue = '' + + // 5. While position is not past the end of input: + while (position.position < input.length) { + // 5.1. Append the result of collecting a sequence of code points that are not U+0022 (") + // or U+002C (,) from input, given position, to temporaryValue. + temporaryValue += collectASequenceOfCodePoints( + (char) => char !== '"' && char !== ',', + input, + position + ) + + // 5.2. If position is not past the end of input, then: + if (position.position < input.length) { + // 5.2.1. If the code point at position within input is U+0022 ("), then: + if (input.charCodeAt(position.position) === 0x22) { + // 5.2.1.1. Append the result of collecting an HTTP quoted string from input, given position, to temporaryValue. + temporaryValue += collectAnHTTPQuotedString( + input, + position + ) + + // 5.2.1.2. If position is not past the end of input, then continue. + if (position.position < input.length) { + continue + } + } else { + // 5.2.2. Otherwise: + + // 5.2.2.1. Assert: the code point at position within input is U+002C (,). + assert(input.charCodeAt(position.position) === 0x2C) + + // 5.2.2.2. Advance position by 1. + position.position++ + } + } + + // 5.3. Remove all HTTP tab or space from the start and end of temporaryValue. + temporaryValue = removeChars(temporaryValue, true, true, (char) => char === 0x9 || char === 0x20) + + // 5.4. Append temporaryValue to values. + values.push(temporaryValue) + + // 5.6. Set temporaryValue to the empty string. + temporaryValue = '' + } + + // 6. Return values. + return values +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-header-list-get-decode-split + * @param {string} name lowercase header name + * @param {import('./headers').HeadersList} list + */ +function getDecodeSplit (name, list) { + // 1. Let value be the result of getting name from list. + const value = list.get(name, true) + + // 2. If value is null, then return null. + if (value === null) { + return null + } + + // 3. Return the result of getting, decoding, and splitting value. + return gettingDecodingSplitting(value) +} + +const textDecoder = new TextDecoder() + +/** + * @see https://encoding.spec.whatwg.org/#utf-8-decode + * @param {Buffer} buffer + */ +function utf8DecodeBytes (buffer) { + if (buffer.length === 0) { + return '' + } + + // 1. Let buffer be the result of peeking three bytes from + // ioQueue, converted to a byte sequence. + + // 2. If buffer is 0xEF 0xBB 0xBF, then read three + // bytes from ioQueue. (Do nothing with those bytes.) + if (buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) { + buffer = buffer.subarray(3) + } + + // 3. Process a queue with an instance of UTF-8’s + // decoder, ioQueue, output, and "replacement". + const output = textDecoder.decode(buffer) + + // 4. Return output. + return output +} + +class EnvironmentSettingsObjectBase { + get baseUrl () { + return getGlobalOrigin() + } + + get origin () { + return this.baseUrl?.origin + } + + policyContainer = makePolicyContainer() +} + +class EnvironmentSettingsObject { + settingsObject = new EnvironmentSettingsObjectBase() +} + +const environmentSettingsObject = new EnvironmentSettingsObject() + +module.exports = { + isAborted, + isCancelled, + isValidEncodedURL, + ReadableStreamFrom, + tryUpgradeRequestToAPotentiallyTrustworthyURL, + clampAndCoarsenConnectionTimingInfo, + coarsenedSharedCurrentTime, + determineRequestsReferrer, + makePolicyContainer, + clonePolicyContainer, + appendFetchMetadata, + appendRequestOriginHeader, + TAOCheck, + corsCheck, + crossOriginResourcePolicyCheck, + createOpaqueTimingInfo, + setRequestReferrerPolicyOnRedirect, + isValidHTTPToken, + requestBadPort, + requestCurrentURL, + responseURL, + responseLocationURL, + isURLPotentiallyTrustworthy, + isValidReasonPhrase, + sameOrigin, + normalizeMethod, + serializeJavascriptValueToJSONString, + iteratorMixin, + createIterator, + isValidHeaderName, + isValidHeaderValue, + isErrorLike, + fullyReadBody, + readableStreamClose, + isomorphicEncode, + urlIsLocal, + urlHasHttpsScheme, + urlIsHttpHttpsScheme, + readAllBytes, + simpleRangeHeaderValue, + buildContentRange, + createInflate, + extractMimeType, + getDecodeSplit, + utf8DecodeBytes, + environmentSettingsObject, + isOriginIPPotentiallyTrustworthy +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/subresource-integrity/Readme.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/subresource-integrity/Readme.md new file mode 100644 index 0000000000000000000000000000000000000000..289a2b84d466d085b243c49fae084b78e25dbcdd --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/subresource-integrity/Readme.md @@ -0,0 +1,9 @@ +# Subresource Integrity + +based on Editor’s Draft, 12 June 2025 + +This module provides support for Subresource Integrity (SRI) in the context of web fetch operations. SRI is a security feature that allows clients to verify that fetched resources are delivered without unexpected manipulation. + +## Links + +- [Subresource Integrity](https://w3c.github.io/webappsec-subresource-integrity/) \ No newline at end of file diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/subresource-integrity/subresource-integrity.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/subresource-integrity/subresource-integrity.js new file mode 100644 index 0000000000000000000000000000000000000000..fccdda678921a77481925e5ae4c90fd2cbb38a30 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/subresource-integrity/subresource-integrity.js @@ -0,0 +1,306 @@ +'use strict' + +const assert = require('node:assert') + +/** + * @typedef {object} Metadata + * @property {SRIHashAlgorithm} alg - The algorithm used for the hash. + * @property {string} val - The base64-encoded hash value. + */ + +/** + * @typedef {Metadata[]} MetadataList + */ + +/** + * @typedef {('sha256' | 'sha384' | 'sha512')} SRIHashAlgorithm + */ + +/** + * @type {Map} + * + * The valid SRI hash algorithm token set is the ordered set « "sha256", + * "sha384", "sha512" » (corresponding to SHA-256, SHA-384, and SHA-512 + * respectively). The ordering of this set is meaningful, with stronger + * algorithms appearing later in the set. + * + * @see https://w3c.github.io/webappsec-subresource-integrity/#valid-sri-hash-algorithm-token-set + */ +const validSRIHashAlgorithmTokenSet = new Map([['sha256', 0], ['sha384', 1], ['sha512', 2]]) + +// https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable +/** @type {import('crypto')} */ +let crypto +try { + crypto = require('node:crypto') + const cryptoHashes = crypto.getHashes() + + // If no hashes are available, we cannot support SRI. + if (cryptoHashes.length === 0) { + validSRIHashAlgorithmTokenSet.clear() + } + + for (const algorithm of validSRIHashAlgorithmTokenSet.keys()) { + // If the algorithm is not supported, remove it from the list. + if (cryptoHashes.includes(algorithm) === false) { + validSRIHashAlgorithmTokenSet.delete(algorithm) + } + } + /* c8 ignore next 4 */ +} catch { + // If crypto is not available, we cannot support SRI. + validSRIHashAlgorithmTokenSet.clear() +} + +/** + * @typedef GetSRIHashAlgorithmIndex + * @type {(algorithm: SRIHashAlgorithm) => number} + * @param {SRIHashAlgorithm} algorithm + * @returns {number} The index of the algorithm in the valid SRI hash algorithm + * token set. + */ + +const getSRIHashAlgorithmIndex = /** @type {GetSRIHashAlgorithmIndex} */ (Map.prototype.get.bind( + validSRIHashAlgorithmTokenSet)) + +/** + * @typedef IsValidSRIHashAlgorithm + * @type {(algorithm: string) => algorithm is SRIHashAlgorithm} + * @param {*} algorithm + * @returns {algorithm is SRIHashAlgorithm} + */ + +const isValidSRIHashAlgorithm = /** @type {IsValidSRIHashAlgorithm} */ ( + Map.prototype.has.bind(validSRIHashAlgorithmTokenSet) +) + +/** + * @param {Uint8Array} bytes + * @param {string} metadataList + * @returns {boolean} + * + * @see https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist + */ +const bytesMatch = crypto === undefined || validSRIHashAlgorithmTokenSet.size === 0 + // If node is not built with OpenSSL support, we cannot check + // a request's integrity, so allow it by default (the spec will + // allow requests if an invalid hash is given, as precedence). + ? () => true + : (bytes, metadataList) => { + // 1. Let parsedMetadata be the result of parsing metadataList. + const parsedMetadata = parseMetadata(metadataList) + + // 2. If parsedMetadata is empty set, return true. + if (parsedMetadata.length === 0) { + return true + } + + // 3. Let metadata be the result of getting the strongest + // metadata from parsedMetadata. + const metadata = getStrongestMetadata(parsedMetadata) + + // 4. For each item in metadata: + for (const item of metadata) { + // 1. Let algorithm be the item["alg"]. + const algorithm = item.alg + + // 2. Let expectedValue be the item["val"]. + const expectedValue = item.val + + // See https://github.com/web-platform-tests/wpt/commit/e4c5cc7a5e48093220528dfdd1c4012dc3837a0e + // "be liberal with padding". This is annoying, and it's not even in the spec. + + // 3. Let actualValue be the result of applying algorithm to bytes . + const actualValue = applyAlgorithmToBytes(algorithm, bytes) + + // 4. If actualValue is a case-sensitive match for expectedValue, + // return true. + if (caseSensitiveMatch(actualValue, expectedValue)) { + return true + } + } + + // 5. Return false. + return false + } + +/** + * @param {MetadataList} metadataList + * @returns {MetadataList} The strongest hash algorithm from the metadata list. + */ +function getStrongestMetadata (metadataList) { + // 1. Let result be the empty set and strongest be the empty string. + const result = [] + /** @type {Metadata|null} */ + let strongest = null + + // 2. For each item in set: + for (const item of metadataList) { + // 1. Assert: item["alg"] is a valid SRI hash algorithm token. + assert(isValidSRIHashAlgorithm(item.alg), 'Invalid SRI hash algorithm token') + + // 2. If result is the empty set, then: + if (result.length === 0) { + // 1. Append item to result. + result.push(item) + + // 2. Set strongest to item. + strongest = item + + // 3. Continue. + continue + } + + // 3. Let currentAlgorithm be strongest["alg"], and currentAlgorithmIndex be + // the index of currentAlgorithm in the valid SRI hash algorithm token set. + const currentAlgorithm = /** @type {Metadata} */ (strongest).alg + const currentAlgorithmIndex = getSRIHashAlgorithmIndex(currentAlgorithm) + + // 4. Let newAlgorithm be the item["alg"], and newAlgorithmIndex be the + // index of newAlgorithm in the valid SRI hash algorithm token set. + const newAlgorithm = item.alg + const newAlgorithmIndex = getSRIHashAlgorithmIndex(newAlgorithm) + + // 5. If newAlgorithmIndex is less than currentAlgorithmIndex, then continue. + if (newAlgorithmIndex < currentAlgorithmIndex) { + continue + + // 6. Otherwise, if newAlgorithmIndex is greater than + // currentAlgorithmIndex: + } else if (newAlgorithmIndex > currentAlgorithmIndex) { + // 1. Set strongest to item. + strongest = item + + // 2. Set result to « item ». + result[0] = item + result.length = 1 + + // 7. Otherwise, newAlgorithmIndex and currentAlgorithmIndex are the same + // value. Append item to result. + } else { + result.push(item) + } + } + + // 3. Return result. + return result +} + +/** + * @param {string} metadata + * @returns {MetadataList} + * + * @see https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata + */ +function parseMetadata (metadata) { + // 1. Let result be the empty set. + /** @type {MetadataList} */ + const result = [] + + // 2. For each item returned by splitting metadata on spaces: + for (const item of metadata.split(' ')) { + // 1. Let expression-and-options be the result of splitting item on U+003F (?). + const expressionAndOptions = item.split('?', 1) + + // 2. Let algorithm-expression be expression-and-options[0]. + const algorithmExpression = expressionAndOptions[0] + + // 3. Let base64-value be the empty string. + let base64Value = '' + + // 4. Let algorithm-and-value be the result of splitting algorithm-expression on U+002D (-). + const algorithmAndValue = [algorithmExpression.slice(0, 6), algorithmExpression.slice(7)] + + // 5. Let algorithm be algorithm-and-value[0]. + const algorithm = algorithmAndValue[0] + + // 6. If algorithm is not a valid SRI hash algorithm token, then continue. + if (!isValidSRIHashAlgorithm(algorithm)) { + continue + } + + // 7. If algorithm-and-value[1] exists, set base64-value to + // algorithm-and-value[1]. + if (algorithmAndValue[1]) { + base64Value = algorithmAndValue[1] + } + + // 8. Let metadata be the ordered map + // «["alg" → algorithm, "val" → base64-value]». + const metadata = { + alg: algorithm, + val: base64Value + } + + // 9. Append metadata to result. + result.push(metadata) + } + + // 3. Return result. + return result +} + +/** + * Applies the specified hash algorithm to the given bytes + * + * @typedef {(algorithm: SRIHashAlgorithm, bytes: Uint8Array) => string} ApplyAlgorithmToBytes + * @param {SRIHashAlgorithm} algorithm + * @param {Uint8Array} bytes + * @returns {string} + */ +const applyAlgorithmToBytes = (algorithm, bytes) => { + return crypto.hash(algorithm, bytes, 'base64') +} + +/** + * Compares two base64 strings, allowing for base64url + * in the second string. + * + * @param {string} actualValue base64 encoded string + * @param {string} expectedValue base64 or base64url encoded string + * @returns {boolean} + */ +function caseSensitiveMatch (actualValue, expectedValue) { + // Ignore padding characters from the end of the strings by + // decreasing the length by 1 or 2 if the last characters are `=`. + let actualValueLength = actualValue.length + if (actualValueLength !== 0 && actualValue[actualValueLength - 1] === '=') { + actualValueLength -= 1 + } + if (actualValueLength !== 0 && actualValue[actualValueLength - 1] === '=') { + actualValueLength -= 1 + } + let expectedValueLength = expectedValue.length + if (expectedValueLength !== 0 && expectedValue[expectedValueLength - 1] === '=') { + expectedValueLength -= 1 + } + if (expectedValueLength !== 0 && expectedValue[expectedValueLength - 1] === '=') { + expectedValueLength -= 1 + } + + if (actualValueLength !== expectedValueLength) { + return false + } + + for (let i = 0; i < actualValueLength; ++i) { + if ( + actualValue[i] === expectedValue[i] || + (actualValue[i] === '+' && expectedValue[i] === '-') || + (actualValue[i] === '/' && expectedValue[i] === '_') + ) { + continue + } + return false + } + + return true +} + +module.exports = { + applyAlgorithmToBytes, + bytesMatch, + caseSensitiveMatch, + isValidSRIHashAlgorithm, + getStrongestMetadata, + parseMetadata +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/webidl/index.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/webidl/index.js new file mode 100644 index 0000000000000000000000000000000000000000..dfe8a92cfd276ab5cfd976540207a11c681fbc8a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/webidl/index.js @@ -0,0 +1,788 @@ +'use strict' + +const { types, inspect } = require('node:util') +const { markAsUncloneable } = require('node:worker_threads') + +const UNDEFINED = 1 +const BOOLEAN = 2 +const STRING = 3 +const SYMBOL = 4 +const NUMBER = 5 +const BIGINT = 6 +const NULL = 7 +const OBJECT = 8 // function and object + +const FunctionPrototypeSymbolHasInstance = Function.call.bind(Function.prototype[Symbol.hasInstance]) + +/** @type {import('../../../types/webidl').Webidl} */ +const webidl = { + converters: {}, + util: {}, + errors: {}, + is: {} +} + +/** + * @description Instantiate an error. + * + * @param {Object} opts + * @param {string} opts.header + * @param {string} opts.message + * @returns {TypeError} + */ +webidl.errors.exception = function (message) { + return new TypeError(`${message.header}: ${message.message}`) +} + +/** + * @description Instantiate an error when conversion from one type to another has failed. + * + * @param {Object} opts + * @param {string} opts.prefix + * @param {string} opts.argument + * @param {string[]} opts.types + * @returns {TypeError} + */ +webidl.errors.conversionFailed = function (opts) { + const plural = opts.types.length === 1 ? '' : ' one of' + const message = + `${opts.argument} could not be converted to` + + `${plural}: ${opts.types.join(', ')}.` + + return webidl.errors.exception({ + header: opts.prefix, + message + }) +} + +/** + * @description Instantiate an error when an invalid argument is provided + * + * @param {Object} context + * @param {string} context.prefix + * @param {string} context.value + * @param {string} context.type + * @returns {TypeError} + */ +webidl.errors.invalidArgument = function (context) { + return webidl.errors.exception({ + header: context.prefix, + message: `"${context.value}" is an invalid ${context.type}.` + }) +} + +// https://webidl.spec.whatwg.org/#implements +webidl.brandCheck = function (V, I) { + if (!FunctionPrototypeSymbolHasInstance(I, V)) { + const err = new TypeError('Illegal invocation') + err.code = 'ERR_INVALID_THIS' // node compat. + throw err + } +} + +webidl.brandCheckMultiple = function (List) { + const prototypes = List.map((c) => webidl.util.MakeTypeAssertion(c)) + + return (V) => { + if (prototypes.every(typeCheck => !typeCheck(V))) { + const err = new TypeError('Illegal invocation') + err.code = 'ERR_INVALID_THIS' // node compat. + throw err + } + } +} + +webidl.argumentLengthCheck = function ({ length }, min, ctx) { + if (length < min) { + throw webidl.errors.exception({ + message: `${min} argument${min !== 1 ? 's' : ''} required, ` + + `but${length ? ' only' : ''} ${length} found.`, + header: ctx + }) + } +} + +webidl.illegalConstructor = function () { + throw webidl.errors.exception({ + header: 'TypeError', + message: 'Illegal constructor' + }) +} + +webidl.util.MakeTypeAssertion = function (I) { + return (O) => FunctionPrototypeSymbolHasInstance(I, O) +} + +// https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values +webidl.util.Type = function (V) { + switch (typeof V) { + case 'undefined': return UNDEFINED + case 'boolean': return BOOLEAN + case 'string': return STRING + case 'symbol': return SYMBOL + case 'number': return NUMBER + case 'bigint': return BIGINT + case 'function': + case 'object': { + if (V === null) { + return NULL + } + + return OBJECT + } + } +} + +webidl.util.Types = { + UNDEFINED, + BOOLEAN, + STRING, + SYMBOL, + NUMBER, + BIGINT, + NULL, + OBJECT +} + +webidl.util.TypeValueToString = function (o) { + switch (webidl.util.Type(o)) { + case UNDEFINED: return 'Undefined' + case BOOLEAN: return 'Boolean' + case STRING: return 'String' + case SYMBOL: return 'Symbol' + case NUMBER: return 'Number' + case BIGINT: return 'BigInt' + case NULL: return 'Null' + case OBJECT: return 'Object' + } +} + +webidl.util.markAsUncloneable = markAsUncloneable || (() => {}) + +// https://webidl.spec.whatwg.org/#abstract-opdef-converttoint +webidl.util.ConvertToInt = function (V, bitLength, signedness, opts) { + let upperBound + let lowerBound + + // 1. If bitLength is 64, then: + if (bitLength === 64) { + // 1. Let upperBound be 2^53 − 1. + upperBound = Math.pow(2, 53) - 1 + + // 2. If signedness is "unsigned", then let lowerBound be 0. + if (signedness === 'unsigned') { + lowerBound = 0 + } else { + // 3. Otherwise let lowerBound be −2^53 + 1. + lowerBound = Math.pow(-2, 53) + 1 + } + } else if (signedness === 'unsigned') { + // 2. Otherwise, if signedness is "unsigned", then: + + // 1. Let lowerBound be 0. + lowerBound = 0 + + // 2. Let upperBound be 2^bitLength − 1. + upperBound = Math.pow(2, bitLength) - 1 + } else { + // 3. Otherwise: + + // 1. Let lowerBound be -2^bitLength − 1. + lowerBound = Math.pow(-2, bitLength) - 1 + + // 2. Let upperBound be 2^bitLength − 1 − 1. + upperBound = Math.pow(2, bitLength - 1) - 1 + } + + // 4. Let x be ? ToNumber(V). + let x = Number(V) + + // 5. If x is −0, then set x to +0. + if (x === 0) { + x = 0 + } + + // 6. If the conversion is to an IDL type associated + // with the [EnforceRange] extended attribute, then: + if (opts?.enforceRange === true) { + // 1. If x is NaN, +∞, or −∞, then throw a TypeError. + if ( + Number.isNaN(x) || + x === Number.POSITIVE_INFINITY || + x === Number.NEGATIVE_INFINITY + ) { + throw webidl.errors.exception({ + header: 'Integer conversion', + message: `Could not convert ${webidl.util.Stringify(V)} to an integer.` + }) + } + + // 2. Set x to IntegerPart(x). + x = webidl.util.IntegerPart(x) + + // 3. If x < lowerBound or x > upperBound, then + // throw a TypeError. + if (x < lowerBound || x > upperBound) { + throw webidl.errors.exception({ + header: 'Integer conversion', + message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.` + }) + } + + // 4. Return x. + return x + } + + // 7. If x is not NaN and the conversion is to an IDL + // type associated with the [Clamp] extended + // attribute, then: + if (!Number.isNaN(x) && opts?.clamp === true) { + // 1. Set x to min(max(x, lowerBound), upperBound). + x = Math.min(Math.max(x, lowerBound), upperBound) + + // 2. Round x to the nearest integer, choosing the + // even integer if it lies halfway between two, + // and choosing +0 rather than −0. + if (Math.floor(x) % 2 === 0) { + x = Math.floor(x) + } else { + x = Math.ceil(x) + } + + // 3. Return x. + return x + } + + // 8. If x is NaN, +0, +∞, or −∞, then return +0. + if ( + Number.isNaN(x) || + (x === 0 && Object.is(0, x)) || + x === Number.POSITIVE_INFINITY || + x === Number.NEGATIVE_INFINITY + ) { + return 0 + } + + // 9. Set x to IntegerPart(x). + x = webidl.util.IntegerPart(x) + + // 10. Set x to x modulo 2^bitLength. + x = x % Math.pow(2, bitLength) + + // 11. If signedness is "signed" and x ≥ 2^bitLength − 1, + // then return x − 2^bitLength. + if (signedness === 'signed' && x >= Math.pow(2, bitLength) - 1) { + return x - Math.pow(2, bitLength) + } + + // 12. Otherwise, return x. + return x +} + +// https://webidl.spec.whatwg.org/#abstract-opdef-integerpart +webidl.util.IntegerPart = function (n) { + // 1. Let r be floor(abs(n)). + const r = Math.floor(Math.abs(n)) + + // 2. If n < 0, then return -1 × r. + if (n < 0) { + return -1 * r + } + + // 3. Otherwise, return r. + return r +} + +webidl.util.Stringify = function (V) { + const type = webidl.util.Type(V) + + switch (type) { + case SYMBOL: + return `Symbol(${V.description})` + case OBJECT: + return inspect(V) + case STRING: + return `"${V}"` + case BIGINT: + return `${V}n` + default: + return `${V}` + } +} + +// https://webidl.spec.whatwg.org/#es-sequence +webidl.sequenceConverter = function (converter) { + return (V, prefix, argument, Iterable) => { + // 1. If Type(V) is not Object, throw a TypeError. + if (webidl.util.Type(V) !== OBJECT) { + throw webidl.errors.exception({ + header: prefix, + message: `${argument} (${webidl.util.Stringify(V)}) is not iterable.` + }) + } + + // 2. Let method be ? GetMethod(V, @@iterator). + /** @type {Generator} */ + const method = typeof Iterable === 'function' ? Iterable() : V?.[Symbol.iterator]?.() + const seq = [] + let index = 0 + + // 3. If method is undefined, throw a TypeError. + if ( + method === undefined || + typeof method.next !== 'function' + ) { + throw webidl.errors.exception({ + header: prefix, + message: `${argument} is not iterable.` + }) + } + + // https://webidl.spec.whatwg.org/#create-sequence-from-iterable + while (true) { + const { done, value } = method.next() + + if (done) { + break + } + + seq.push(converter(value, prefix, `${argument}[${index++}]`)) + } + + return seq + } +} + +// https://webidl.spec.whatwg.org/#es-to-record +webidl.recordConverter = function (keyConverter, valueConverter) { + return (O, prefix, argument) => { + // 1. If Type(O) is not Object, throw a TypeError. + if (webidl.util.Type(O) !== OBJECT) { + throw webidl.errors.exception({ + header: prefix, + message: `${argument} ("${webidl.util.TypeValueToString(O)}") is not an Object.` + }) + } + + // 2. Let result be a new empty instance of record. + const result = {} + + if (!types.isProxy(O)) { + // 1. Let desc be ? O.[[GetOwnProperty]](key). + const keys = [...Object.getOwnPropertyNames(O), ...Object.getOwnPropertySymbols(O)] + + for (const key of keys) { + const keyName = webidl.util.Stringify(key) + + // 1. Let typedKey be key converted to an IDL value of type K. + const typedKey = keyConverter(key, prefix, `Key ${keyName} in ${argument}`) + + // 2. Let value be ? Get(O, key). + // 3. Let typedValue be value converted to an IDL value of type V. + const typedValue = valueConverter(O[key], prefix, `${argument}[${keyName}]`) + + // 4. Set result[typedKey] to typedValue. + result[typedKey] = typedValue + } + + // 5. Return result. + return result + } + + // 3. Let keys be ? O.[[OwnPropertyKeys]](). + const keys = Reflect.ownKeys(O) + + // 4. For each key of keys. + for (const key of keys) { + // 1. Let desc be ? O.[[GetOwnProperty]](key). + const desc = Reflect.getOwnPropertyDescriptor(O, key) + + // 2. If desc is not undefined and desc.[[Enumerable]] is true: + if (desc?.enumerable) { + // 1. Let typedKey be key converted to an IDL value of type K. + const typedKey = keyConverter(key, prefix, argument) + + // 2. Let value be ? Get(O, key). + // 3. Let typedValue be value converted to an IDL value of type V. + const typedValue = valueConverter(O[key], prefix, argument) + + // 4. Set result[typedKey] to typedValue. + result[typedKey] = typedValue + } + } + + // 5. Return result. + return result + } +} + +webidl.interfaceConverter = function (TypeCheck, name) { + return (V, prefix, argument) => { + if (!TypeCheck(V)) { + throw webidl.errors.exception({ + header: prefix, + message: `Expected ${argument} ("${webidl.util.Stringify(V)}") to be an instance of ${name}.` + }) + } + + return V + } +} + +webidl.dictionaryConverter = function (converters) { + return (dictionary, prefix, argument) => { + const dict = {} + + if (dictionary != null && webidl.util.Type(dictionary) !== OBJECT) { + throw webidl.errors.exception({ + header: prefix, + message: `Expected ${dictionary} to be one of: Null, Undefined, Object.` + }) + } + + for (const options of converters) { + const { key, defaultValue, required, converter } = options + + if (required === true) { + if (dictionary == null || !Object.hasOwn(dictionary, key)) { + throw webidl.errors.exception({ + header: prefix, + message: `Missing required key "${key}".` + }) + } + } + + let value = dictionary?.[key] + const hasDefault = defaultValue !== undefined + + // Only use defaultValue if value is undefined and + // a defaultValue options was provided. + if (hasDefault && value === undefined) { + value = defaultValue() + } + + // A key can be optional and have no default value. + // When this happens, do not perform a conversion, + // and do not assign the key a value. + if (required || hasDefault || value !== undefined) { + value = converter(value, prefix, `${argument}.${key}`) + + if ( + options.allowedValues && + !options.allowedValues.includes(value) + ) { + throw webidl.errors.exception({ + header: prefix, + message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(', ')}.` + }) + } + + dict[key] = value + } + } + + return dict + } +} + +webidl.nullableConverter = function (converter) { + return (V, prefix, argument) => { + if (V === null) { + return V + } + + return converter(V, prefix, argument) + } +} + +/** + * @param {*} value + * @returns {boolean} + */ +webidl.is.USVString = function (value) { + return ( + typeof value === 'string' && + value.isWellFormed() + ) +} + +webidl.is.ReadableStream = webidl.util.MakeTypeAssertion(ReadableStream) +webidl.is.Blob = webidl.util.MakeTypeAssertion(Blob) +webidl.is.URLSearchParams = webidl.util.MakeTypeAssertion(URLSearchParams) +webidl.is.File = webidl.util.MakeTypeAssertion(File) +webidl.is.URL = webidl.util.MakeTypeAssertion(URL) +webidl.is.AbortSignal = webidl.util.MakeTypeAssertion(AbortSignal) +webidl.is.MessagePort = webidl.util.MakeTypeAssertion(MessagePort) + +// https://webidl.spec.whatwg.org/#es-DOMString +webidl.converters.DOMString = function (V, prefix, argument, opts) { + // 1. If V is null and the conversion is to an IDL type + // associated with the [LegacyNullToEmptyString] + // extended attribute, then return the DOMString value + // that represents the empty string. + if (V === null && opts?.legacyNullToEmptyString) { + return '' + } + + // 2. Let x be ? ToString(V). + if (typeof V === 'symbol') { + throw webidl.errors.exception({ + header: prefix, + message: `${argument} is a symbol, which cannot be converted to a DOMString.` + }) + } + + // 3. Return the IDL DOMString value that represents the + // same sequence of code units as the one the + // ECMAScript String value x represents. + return String(V) +} + +// https://webidl.spec.whatwg.org/#es-ByteString +webidl.converters.ByteString = function (V, prefix, argument) { + // 1. Let x be ? ToString(V). + if (typeof V === 'symbol') { + throw webidl.errors.exception({ + header: prefix, + message: `${argument} is a symbol, which cannot be converted to a ByteString.` + }) + } + + const x = String(V) + + // 2. If the value of any element of x is greater than + // 255, then throw a TypeError. + for (let index = 0; index < x.length; index++) { + if (x.charCodeAt(index) > 255) { + throw new TypeError( + 'Cannot convert argument to a ByteString because the character at ' + + `index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.` + ) + } + } + + // 3. Return an IDL ByteString value whose length is the + // length of x, and where the value of each element is + // the value of the corresponding element of x. + return x +} + +/** + * @param {unknown} value + * @returns {string} + * @see https://webidl.spec.whatwg.org/#es-USVString + */ +webidl.converters.USVString = function (value) { + // TODO: rewrite this so we can control the errors thrown + if (typeof value === 'string') { + return value.toWellFormed() + } + return `${value}`.toWellFormed() +} + +// https://webidl.spec.whatwg.org/#es-boolean +webidl.converters.boolean = function (V) { + // 1. Let x be the result of computing ToBoolean(V). + // https://262.ecma-international.org/10.0/index.html#table-10 + const x = Boolean(V) + + // 2. Return the IDL boolean value that is the one that represents + // the same truth value as the ECMAScript Boolean value x. + return x +} + +// https://webidl.spec.whatwg.org/#es-any +webidl.converters.any = function (V) { + return V +} + +// https://webidl.spec.whatwg.org/#es-long-long +webidl.converters['long long'] = function (V, prefix, argument) { + // 1. Let x be ? ConvertToInt(V, 64, "signed"). + const x = webidl.util.ConvertToInt(V, 64, 'signed', undefined, prefix, argument) + + // 2. Return the IDL long long value that represents + // the same numeric value as x. + return x +} + +// https://webidl.spec.whatwg.org/#es-unsigned-long-long +webidl.converters['unsigned long long'] = function (V, prefix, argument) { + // 1. Let x be ? ConvertToInt(V, 64, "unsigned"). + const x = webidl.util.ConvertToInt(V, 64, 'unsigned', undefined, prefix, argument) + + // 2. Return the IDL unsigned long long value that + // represents the same numeric value as x. + return x +} + +// https://webidl.spec.whatwg.org/#es-unsigned-long +webidl.converters['unsigned long'] = function (V, prefix, argument) { + // 1. Let x be ? ConvertToInt(V, 32, "unsigned"). + const x = webidl.util.ConvertToInt(V, 32, 'unsigned', undefined, prefix, argument) + + // 2. Return the IDL unsigned long value that + // represents the same numeric value as x. + return x +} + +// https://webidl.spec.whatwg.org/#es-unsigned-short +webidl.converters['unsigned short'] = function (V, prefix, argument, opts) { + // 1. Let x be ? ConvertToInt(V, 16, "unsigned"). + const x = webidl.util.ConvertToInt(V, 16, 'unsigned', opts, prefix, argument) + + // 2. Return the IDL unsigned short value that represents + // the same numeric value as x. + return x +} + +// https://webidl.spec.whatwg.org/#idl-ArrayBuffer +webidl.converters.ArrayBuffer = function (V, prefix, argument, opts) { + // 1. If Type(V) is not Object, or V does not have an + // [[ArrayBufferData]] internal slot, then throw a + // TypeError. + // see: https://tc39.es/ecma262/#sec-properties-of-the-arraybuffer-instances + // see: https://tc39.es/ecma262/#sec-properties-of-the-sharedarraybuffer-instances + if ( + webidl.util.Type(V) !== OBJECT || + !types.isAnyArrayBuffer(V) + ) { + throw webidl.errors.conversionFailed({ + prefix, + argument: `${argument} ("${webidl.util.Stringify(V)}")`, + types: ['ArrayBuffer'] + }) + } + + // 2. If the conversion is not to an IDL type associated + // with the [AllowShared] extended attribute, and + // IsSharedArrayBuffer(V) is true, then throw a + // TypeError. + if (opts?.allowShared === false && types.isSharedArrayBuffer(V)) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'SharedArrayBuffer is not allowed.' + }) + } + + // 3. If the conversion is not to an IDL type associated + // with the [AllowResizable] extended attribute, and + // IsResizableArrayBuffer(V) is true, then throw a + // TypeError. + if (V.resizable || V.growable) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'Received a resizable ArrayBuffer.' + }) + } + + // 4. Return the IDL ArrayBuffer value that is a + // reference to the same object as V. + return V +} + +webidl.converters.TypedArray = function (V, T, prefix, name, opts) { + // 1. Let T be the IDL type V is being converted to. + + // 2. If Type(V) is not Object, or V does not have a + // [[TypedArrayName]] internal slot with a value + // equal to T’s name, then throw a TypeError. + if ( + webidl.util.Type(V) !== OBJECT || + !types.isTypedArray(V) || + V.constructor.name !== T.name + ) { + throw webidl.errors.conversionFailed({ + prefix, + argument: `${name} ("${webidl.util.Stringify(V)}")`, + types: [T.name] + }) + } + + // 3. If the conversion is not to an IDL type associated + // with the [AllowShared] extended attribute, and + // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is + // true, then throw a TypeError. + if (opts?.allowShared === false && types.isSharedArrayBuffer(V.buffer)) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'SharedArrayBuffer is not allowed.' + }) + } + + // 4. If the conversion is not to an IDL type associated + // with the [AllowResizable] extended attribute, and + // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is + // true, then throw a TypeError. + if (V.buffer.resizable || V.buffer.growable) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'Received a resizable ArrayBuffer.' + }) + } + + // 5. Return the IDL value of type T that is a reference + // to the same object as V. + return V +} + +webidl.converters.DataView = function (V, prefix, name, opts) { + // 1. If Type(V) is not Object, or V does not have a + // [[DataView]] internal slot, then throw a TypeError. + if (webidl.util.Type(V) !== OBJECT || !types.isDataView(V)) { + throw webidl.errors.exception({ + header: prefix, + message: `${name} is not a DataView.` + }) + } + + // 2. If the conversion is not to an IDL type associated + // with the [AllowShared] extended attribute, and + // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true, + // then throw a TypeError. + if (opts?.allowShared === false && types.isSharedArrayBuffer(V.buffer)) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'SharedArrayBuffer is not allowed.' + }) + } + + // 3. If the conversion is not to an IDL type associated + // with the [AllowResizable] extended attribute, and + // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is + // true, then throw a TypeError. + if (V.buffer.resizable || V.buffer.growable) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'Received a resizable ArrayBuffer.' + }) + } + + // 4. Return the IDL DataView value that is a reference + // to the same object as V. + return V +} + +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.ByteString +) + +webidl.converters['sequence>'] = webidl.sequenceConverter( + webidl.converters['sequence'] +) + +webidl.converters['record'] = webidl.recordConverter( + webidl.converters.ByteString, + webidl.converters.ByteString +) + +webidl.converters.Blob = webidl.interfaceConverter(webidl.is.Blob, 'Blob') + +webidl.converters.AbortSignal = webidl.interfaceConverter( + webidl.is.AbortSignal, + 'AbortSignal' +) + +module.exports = { + webidl +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/websocket/connection.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/websocket/connection.js new file mode 100644 index 0000000000000000000000000000000000000000..acbeafc8be1597fb5101118ce038ec954fcec9ad --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/websocket/connection.js @@ -0,0 +1,317 @@ +'use strict' + +const { uid, states, sentCloseFrameState, emptyBuffer, opcodes } = require('./constants') +const { parseExtensions, isClosed, isClosing, isEstablished, validateCloseCodeAndReason } = require('./util') +const { makeRequest } = require('../fetch/request') +const { fetching } = require('../fetch/index') +const { Headers, getHeadersList } = require('../fetch/headers') +const { getDecodeSplit } = require('../fetch/util') +const { WebsocketFrameSend } = require('./frame') +const assert = require('node:assert') + +/** @type {import('crypto')} */ +let crypto +try { + crypto = require('node:crypto') +/* c8 ignore next 3 */ +} catch { + +} + +/** + * @see https://websockets.spec.whatwg.org/#concept-websocket-establish + * @param {URL} url + * @param {string|string[]} protocols + * @param {import('./websocket').Handler} handler + * @param {Partial} options + */ +function establishWebSocketConnection (url, protocols, client, handler, options) { + // 1. Let requestURL be a copy of url, with its scheme set to "http", if url’s + // scheme is "ws", and to "https" otherwise. + const requestURL = url + + requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:' + + // 2. Let request be a new request, whose URL is requestURL, client is client, + // service-workers mode is "none", referrer is "no-referrer", mode is + // "websocket", credentials mode is "include", cache mode is "no-store" , + // and redirect mode is "error". + const request = makeRequest({ + urlList: [requestURL], + client, + serviceWorkers: 'none', + referrer: 'no-referrer', + mode: 'websocket', + credentials: 'include', + cache: 'no-store', + redirect: 'error' + }) + + // Note: undici extension, allow setting custom headers. + if (options.headers) { + const headersList = getHeadersList(new Headers(options.headers)) + + request.headersList = headersList + } + + // 3. Append (`Upgrade`, `websocket`) to request’s header list. + // 4. Append (`Connection`, `Upgrade`) to request’s header list. + // Note: both of these are handled by undici currently. + // https://github.com/nodejs/undici/blob/68c269c4144c446f3f1220951338daef4a6b5ec4/lib/client.js#L1397 + + // 5. Let keyValue be a nonce consisting of a randomly selected + // 16-byte value that has been forgiving-base64-encoded and + // isomorphic encoded. + const keyValue = crypto.randomBytes(16).toString('base64') + + // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s + // header list. + request.headersList.append('sec-websocket-key', keyValue, true) + + // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s + // header list. + request.headersList.append('sec-websocket-version', '13', true) + + // 8. For each protocol in protocols, combine + // (`Sec-WebSocket-Protocol`, protocol) in request’s header + // list. + for (const protocol of protocols) { + request.headersList.append('sec-websocket-protocol', protocol, true) + } + + // 9. Let permessageDeflate be a user-agent defined + // "permessage-deflate" extension header value. + // https://github.com/mozilla/gecko-dev/blob/ce78234f5e653a5d3916813ff990f053510227bc/netwerk/protocol/websocket/WebSocketChannel.cpp#L2673 + const permessageDeflate = 'permessage-deflate; client_max_window_bits' + + // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to + // request’s header list. + request.headersList.append('sec-websocket-extensions', permessageDeflate, true) + + // 11. Fetch request with useParallelQueue set to true, and + // processResponse given response being these steps: + const controller = fetching({ + request, + useParallelQueue: true, + dispatcher: options.dispatcher, + processResponse (response) { + if (response.type === 'error') { + // If the WebSocket connection could not be established, it is also said + // that _The WebSocket Connection is Closed_, but not _cleanly_. + handler.readyState = states.CLOSED + } + + // 1. If response is a network error or its status is not 101, + // fail the WebSocket connection. + if (response.type === 'error' || response.status !== 101) { + failWebsocketConnection(handler, 1002, 'Received network error or non-101 status code.', response.error) + return + } + + // 2. If protocols is not the empty list and extracting header + // list values given `Sec-WebSocket-Protocol` and response’s + // header list results in null, failure, or the empty byte + // sequence, then fail the WebSocket connection. + if (protocols.length !== 0 && !response.headersList.get('Sec-WebSocket-Protocol')) { + failWebsocketConnection(handler, 1002, 'Server did not respond with sent protocols.') + return + } + + // 3. Follow the requirements stated step 2 to step 6, inclusive, + // of the last set of steps in section 4.1 of The WebSocket + // Protocol to validate response. This either results in fail + // the WebSocket connection or the WebSocket connection is + // established. + + // 2. If the response lacks an |Upgrade| header field or the |Upgrade| + // header field contains a value that is not an ASCII case- + // insensitive match for the value "websocket", the client MUST + // _Fail the WebSocket Connection_. + if (response.headersList.get('Upgrade')?.toLowerCase() !== 'websocket') { + failWebsocketConnection(handler, 1002, 'Server did not set Upgrade header to "websocket".') + return + } + + // 3. If the response lacks a |Connection| header field or the + // |Connection| header field doesn't contain a token that is an + // ASCII case-insensitive match for the value "Upgrade", the client + // MUST _Fail the WebSocket Connection_. + if (response.headersList.get('Connection')?.toLowerCase() !== 'upgrade') { + failWebsocketConnection(handler, 1002, 'Server did not set Connection header to "upgrade".') + return + } + + // 4. If the response lacks a |Sec-WebSocket-Accept| header field or + // the |Sec-WebSocket-Accept| contains a value other than the + // base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket- + // Key| (as a string, not base64-decoded) with the string "258EAFA5- + // E914-47DA-95CA-C5AB0DC85B11" but ignoring any leading and + // trailing whitespace, the client MUST _Fail the WebSocket + // Connection_. + const secWSAccept = response.headersList.get('Sec-WebSocket-Accept') + const digest = crypto.createHash('sha1').update(keyValue + uid).digest('base64') + if (secWSAccept !== digest) { + failWebsocketConnection(handler, 1002, 'Incorrect hash received in Sec-WebSocket-Accept header.') + return + } + + // 5. If the response includes a |Sec-WebSocket-Extensions| header + // field and this header field indicates the use of an extension + // that was not present in the client's handshake (the server has + // indicated an extension not requested by the client), the client + // MUST _Fail the WebSocket Connection_. (The parsing of this + // header field to determine which extensions are requested is + // discussed in Section 9.1.) + const secExtension = response.headersList.get('Sec-WebSocket-Extensions') + let extensions + + if (secExtension !== null) { + extensions = parseExtensions(secExtension) + + if (!extensions.has('permessage-deflate')) { + failWebsocketConnection(handler, 1002, 'Sec-WebSocket-Extensions header does not match.') + return + } + } + + // 6. If the response includes a |Sec-WebSocket-Protocol| header field + // and this header field indicates the use of a subprotocol that was + // not present in the client's handshake (the server has indicated a + // subprotocol not requested by the client), the client MUST _Fail + // the WebSocket Connection_. + const secProtocol = response.headersList.get('Sec-WebSocket-Protocol') + + if (secProtocol !== null) { + const requestProtocols = getDecodeSplit('sec-websocket-protocol', request.headersList) + + // The client can request that the server use a specific subprotocol by + // including the |Sec-WebSocket-Protocol| field in its handshake. If it + // is specified, the server needs to include the same field and one of + // the selected subprotocol values in its response for the connection to + // be established. + if (!requestProtocols.includes(secProtocol)) { + failWebsocketConnection(handler, 1002, 'Protocol was not set in the opening handshake.') + return + } + } + + response.socket.on('data', handler.onSocketData) + response.socket.on('close', handler.onSocketClose) + response.socket.on('error', handler.onSocketError) + + handler.wasEverConnected = true + handler.onConnectionEstablished(response, extensions) + } + }) + + return controller +} + +/** + * @see https://whatpr.org/websockets/48.html#close-the-websocket + * @param {import('./websocket').Handler} object + * @param {number} [code=null] + * @param {string} [reason=''] + */ +function closeWebSocketConnection (object, code, reason, validate = false) { + // 1. If code was not supplied, let code be null. + code ??= null + + // 2. If reason was not supplied, let reason be the empty string. + reason ??= '' + + // 3. Validate close code and reason with code and reason. + if (validate) validateCloseCodeAndReason(code, reason) + + // 4. Run the first matching steps from the following list: + // - If object’s ready state is CLOSING (2) or CLOSED (3) + // - If the WebSocket connection is not yet established [WSP] + // - If the WebSocket closing handshake has not yet been started [WSP] + // - Otherwise + if (isClosed(object.readyState) || isClosing(object.readyState)) { + // Do nothing. + } else if (!isEstablished(object.readyState)) { + // Fail the WebSocket connection and set object’s ready state to CLOSING (2). [WSP] + failWebsocketConnection(object) + object.readyState = states.CLOSING + } else if (!object.closeState.has(sentCloseFrameState.SENT) && !object.closeState.has(sentCloseFrameState.RECEIVED)) { + // Upon either sending or receiving a Close control frame, it is said + // that _The WebSocket Closing Handshake is Started_ and that the + // WebSocket connection is in the CLOSING state. + + const frame = new WebsocketFrameSend() + + // If neither code nor reason is present, the WebSocket Close + // message must not have a body. + + // If code is present, then the status code to use in the + // WebSocket Close message must be the integer given by code. + // If code is null and reason is the empty string, the WebSocket Close frame must not have a body. + // If reason is non-empty but code is null, then set code to 1000 ("Normal Closure"). + if (reason.length !== 0 && code === null) { + code = 1000 + } + + // If code is set, then the status code to use in the WebSocket Close frame must be the integer given by code. + assert(code === null || Number.isInteger(code)) + + if (code === null && reason.length === 0) { + frame.frameData = emptyBuffer + } else if (code !== null && reason === null) { + frame.frameData = Buffer.allocUnsafe(2) + frame.frameData.writeUInt16BE(code, 0) + } else if (code !== null && reason !== null) { + // If reason is also present, then reasonBytes must be + // provided in the Close message after the status code. + frame.frameData = Buffer.allocUnsafe(2 + Buffer.byteLength(reason)) + frame.frameData.writeUInt16BE(code, 0) + // the body MAY contain UTF-8-encoded data with value /reason/ + frame.frameData.write(reason, 2, 'utf-8') + } else { + frame.frameData = emptyBuffer + } + + object.socket.write(frame.createFrame(opcodes.CLOSE)) + + object.closeState.add(sentCloseFrameState.SENT) + + // Upon either sending or receiving a Close control frame, it is said + // that _The WebSocket Closing Handshake is Started_ and that the + // WebSocket connection is in the CLOSING state. + object.readyState = states.CLOSING + } else { + // Set object’s ready state to CLOSING (2). + object.readyState = states.CLOSING + } +} + +/** + * @param {import('./websocket').Handler} handler + * @param {number} code + * @param {string|undefined} reason + * @param {unknown} cause + * @returns {void} + */ +function failWebsocketConnection (handler, code, reason, cause) { + // If _The WebSocket Connection is Established_ prior to the point where + // the endpoint is required to _Fail the WebSocket Connection_, the + // endpoint SHOULD send a Close frame with an appropriate status code + // (Section 7.4) before proceeding to _Close the WebSocket Connection_. + if (isEstablished(handler.readyState)) { + closeWebSocketConnection(handler, code, reason, false) + } + + handler.controller.abort() + + if (handler.socket?.destroyed === false) { + handler.socket.destroy() + } + + handler.onFail(code, reason, cause) +} + +module.exports = { + establishWebSocketConnection, + failWebsocketConnection, + closeWebSocketConnection +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/websocket/constants.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/websocket/constants.js new file mode 100644 index 0000000000000000000000000000000000000000..e4e69901c9629a3aeb8102a4e132b8ade2d97d91 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/websocket/constants.js @@ -0,0 +1,126 @@ +'use strict' + +/** + * This is a Globally Unique Identifier unique used to validate that the + * endpoint accepts websocket connections. + * @see https://www.rfc-editor.org/rfc/rfc6455.html#section-1.3 + * @type {'258EAFA5-E914-47DA-95CA-C5AB0DC85B11'} + */ +const uid = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11' + +/** + * @type {PropertyDescriptor} + */ +const staticPropertyDescriptors = { + enumerable: true, + writable: false, + configurable: false +} + +/** + * The states of the WebSocket connection. + * + * @readonly + * @enum + * @property {0} CONNECTING + * @property {1} OPEN + * @property {2} CLOSING + * @property {3} CLOSED + */ +const states = { + CONNECTING: 0, + OPEN: 1, + CLOSING: 2, + CLOSED: 3 +} + +/** + * @readonly + * @enum + * @property {0} NOT_SENT + * @property {1} PROCESSING + * @property {2} SENT + */ +const sentCloseFrameState = { + SENT: 1, + RECEIVED: 2 +} + +/** + * The WebSocket opcodes. + * + * @readonly + * @enum + * @property {0x0} CONTINUATION + * @property {0x1} TEXT + * @property {0x2} BINARY + * @property {0x8} CLOSE + * @property {0x9} PING + * @property {0xA} PONG + * @see https://datatracker.ietf.org/doc/html/rfc6455#section-5.2 + */ +const opcodes = { + CONTINUATION: 0x0, + TEXT: 0x1, + BINARY: 0x2, + CLOSE: 0x8, + PING: 0x9, + PONG: 0xA +} + +/** + * The maximum value for an unsigned 16-bit integer. + * + * @type {65535} 2 ** 16 - 1 + */ +const maxUnsigned16Bit = 65535 + +/** + * The states of the parser. + * + * @readonly + * @enum + * @property {0} INFO + * @property {2} PAYLOADLENGTH_16 + * @property {3} PAYLOADLENGTH_64 + * @property {4} READ_DATA + */ +const parserStates = { + INFO: 0, + PAYLOADLENGTH_16: 2, + PAYLOADLENGTH_64: 3, + READ_DATA: 4 +} + +/** + * An empty buffer. + * + * @type {Buffer} + */ +const emptyBuffer = Buffer.allocUnsafe(0) + +/** + * @readonly + * @property {1} text + * @property {2} typedArray + * @property {3} arrayBuffer + * @property {4} blob + */ +const sendHints = { + text: 1, + typedArray: 2, + arrayBuffer: 3, + blob: 4 +} + +module.exports = { + uid, + sentCloseFrameState, + staticPropertyDescriptors, + states, + opcodes, + maxUnsigned16Bit, + parserStates, + emptyBuffer, + sendHints +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/websocket/events.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/websocket/events.js new file mode 100644 index 0000000000000000000000000000000000000000..3f2cf61ada9e848406f03769cc77527672176db8 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/websocket/events.js @@ -0,0 +1,331 @@ +'use strict' + +const { webidl } = require('../webidl') +const { kEnumerableProperty } = require('../../core/util') +const { kConstruct } = require('../../core/symbols') + +/** + * @see https://html.spec.whatwg.org/multipage/comms.html#messageevent + */ +class MessageEvent extends Event { + #eventInit + + constructor (type, eventInitDict = {}) { + if (type === kConstruct) { + super(arguments[1], arguments[2]) + webidl.util.markAsUncloneable(this) + return + } + + const prefix = 'MessageEvent constructor' + webidl.argumentLengthCheck(arguments, 1, prefix) + + type = webidl.converters.DOMString(type, prefix, 'type') + eventInitDict = webidl.converters.MessageEventInit(eventInitDict, prefix, 'eventInitDict') + + super(type, eventInitDict) + + this.#eventInit = eventInitDict + webidl.util.markAsUncloneable(this) + } + + get data () { + webidl.brandCheck(this, MessageEvent) + + return this.#eventInit.data + } + + get origin () { + webidl.brandCheck(this, MessageEvent) + + return this.#eventInit.origin + } + + get lastEventId () { + webidl.brandCheck(this, MessageEvent) + + return this.#eventInit.lastEventId + } + + get source () { + webidl.brandCheck(this, MessageEvent) + + return this.#eventInit.source + } + + get ports () { + webidl.brandCheck(this, MessageEvent) + + if (!Object.isFrozen(this.#eventInit.ports)) { + Object.freeze(this.#eventInit.ports) + } + + return this.#eventInit.ports + } + + initMessageEvent ( + type, + bubbles = false, + cancelable = false, + data = null, + origin = '', + lastEventId = '', + source = null, + ports = [] + ) { + webidl.brandCheck(this, MessageEvent) + + webidl.argumentLengthCheck(arguments, 1, 'MessageEvent.initMessageEvent') + + return new MessageEvent(type, { + bubbles, cancelable, data, origin, lastEventId, source, ports + }) + } + + static createFastMessageEvent (type, init) { + const messageEvent = new MessageEvent(kConstruct, type, init) + messageEvent.#eventInit = init + messageEvent.#eventInit.data ??= null + messageEvent.#eventInit.origin ??= '' + messageEvent.#eventInit.lastEventId ??= '' + messageEvent.#eventInit.source ??= null + messageEvent.#eventInit.ports ??= [] + return messageEvent + } +} + +const { createFastMessageEvent } = MessageEvent +delete MessageEvent.createFastMessageEvent + +/** + * @see https://websockets.spec.whatwg.org/#the-closeevent-interface + */ +class CloseEvent extends Event { + #eventInit + + constructor (type, eventInitDict = {}) { + const prefix = 'CloseEvent constructor' + webidl.argumentLengthCheck(arguments, 1, prefix) + + type = webidl.converters.DOMString(type, prefix, 'type') + eventInitDict = webidl.converters.CloseEventInit(eventInitDict) + + super(type, eventInitDict) + + this.#eventInit = eventInitDict + webidl.util.markAsUncloneable(this) + } + + get wasClean () { + webidl.brandCheck(this, CloseEvent) + + return this.#eventInit.wasClean + } + + get code () { + webidl.brandCheck(this, CloseEvent) + + return this.#eventInit.code + } + + get reason () { + webidl.brandCheck(this, CloseEvent) + + return this.#eventInit.reason + } +} + +// https://html.spec.whatwg.org/multipage/webappapis.html#the-errorevent-interface +class ErrorEvent extends Event { + #eventInit + + constructor (type, eventInitDict) { + const prefix = 'ErrorEvent constructor' + webidl.argumentLengthCheck(arguments, 1, prefix) + + super(type, eventInitDict) + webidl.util.markAsUncloneable(this) + + type = webidl.converters.DOMString(type, prefix, 'type') + eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {}) + + this.#eventInit = eventInitDict + } + + get message () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.message + } + + get filename () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.filename + } + + get lineno () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.lineno + } + + get colno () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.colno + } + + get error () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.error + } +} + +Object.defineProperties(MessageEvent.prototype, { + [Symbol.toStringTag]: { + value: 'MessageEvent', + configurable: true + }, + data: kEnumerableProperty, + origin: kEnumerableProperty, + lastEventId: kEnumerableProperty, + source: kEnumerableProperty, + ports: kEnumerableProperty, + initMessageEvent: kEnumerableProperty +}) + +Object.defineProperties(CloseEvent.prototype, { + [Symbol.toStringTag]: { + value: 'CloseEvent', + configurable: true + }, + reason: kEnumerableProperty, + code: kEnumerableProperty, + wasClean: kEnumerableProperty +}) + +Object.defineProperties(ErrorEvent.prototype, { + [Symbol.toStringTag]: { + value: 'ErrorEvent', + configurable: true + }, + message: kEnumerableProperty, + filename: kEnumerableProperty, + lineno: kEnumerableProperty, + colno: kEnumerableProperty, + error: kEnumerableProperty +}) + +webidl.converters.MessagePort = webidl.interfaceConverter( + webidl.is.MessagePort, + 'MessagePort' +) + +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.MessagePort +) + +const eventInit = [ + { + key: 'bubbles', + converter: webidl.converters.boolean, + defaultValue: () => false + }, + { + key: 'cancelable', + converter: webidl.converters.boolean, + defaultValue: () => false + }, + { + key: 'composed', + converter: webidl.converters.boolean, + defaultValue: () => false + } +] + +webidl.converters.MessageEventInit = webidl.dictionaryConverter([ + ...eventInit, + { + key: 'data', + converter: webidl.converters.any, + defaultValue: () => null + }, + { + key: 'origin', + converter: webidl.converters.USVString, + defaultValue: () => '' + }, + { + key: 'lastEventId', + converter: webidl.converters.DOMString, + defaultValue: () => '' + }, + { + key: 'source', + // Node doesn't implement WindowProxy or ServiceWorker, so the only + // valid value for source is a MessagePort. + converter: webidl.nullableConverter(webidl.converters.MessagePort), + defaultValue: () => null + }, + { + key: 'ports', + converter: webidl.converters['sequence'], + defaultValue: () => new Array(0) + } +]) + +webidl.converters.CloseEventInit = webidl.dictionaryConverter([ + ...eventInit, + { + key: 'wasClean', + converter: webidl.converters.boolean, + defaultValue: () => false + }, + { + key: 'code', + converter: webidl.converters['unsigned short'], + defaultValue: () => 0 + }, + { + key: 'reason', + converter: webidl.converters.USVString, + defaultValue: () => '' + } +]) + +webidl.converters.ErrorEventInit = webidl.dictionaryConverter([ + ...eventInit, + { + key: 'message', + converter: webidl.converters.DOMString, + defaultValue: () => '' + }, + { + key: 'filename', + converter: webidl.converters.USVString, + defaultValue: () => '' + }, + { + key: 'lineno', + converter: webidl.converters['unsigned long'], + defaultValue: () => 0 + }, + { + key: 'colno', + converter: webidl.converters['unsigned long'], + defaultValue: () => 0 + }, + { + key: 'error', + converter: webidl.converters.any + } +]) + +module.exports = { + MessageEvent, + CloseEvent, + ErrorEvent, + createFastMessageEvent +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/websocket/frame.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/websocket/frame.js new file mode 100644 index 0000000000000000000000000000000000000000..68f31ebab9fa790165ace25ca9a5a77ebf85dc1e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/websocket/frame.js @@ -0,0 +1,139 @@ +'use strict' + +const { maxUnsigned16Bit, opcodes } = require('./constants') + +const BUFFER_SIZE = 8 * 1024 + +/** @type {import('crypto')} */ +let crypto +let buffer = null +let bufIdx = BUFFER_SIZE + +try { + crypto = require('node:crypto') +/* c8 ignore next 3 */ +} catch { + crypto = { + // not full compatibility, but minimum. + randomFillSync: function randomFillSync (buffer, _offset, _size) { + for (let i = 0; i < buffer.length; ++i) { + buffer[i] = Math.random() * 255 | 0 + } + return buffer + } + } +} + +function generateMask () { + if (bufIdx === BUFFER_SIZE) { + bufIdx = 0 + crypto.randomFillSync((buffer ??= Buffer.allocUnsafeSlow(BUFFER_SIZE)), 0, BUFFER_SIZE) + } + return [buffer[bufIdx++], buffer[bufIdx++], buffer[bufIdx++], buffer[bufIdx++]] +} + +class WebsocketFrameSend { + /** + * @param {Buffer|undefined} data + */ + constructor (data) { + this.frameData = data + } + + createFrame (opcode) { + const frameData = this.frameData + const maskKey = generateMask() + const bodyLength = frameData?.byteLength ?? 0 + + /** @type {number} */ + let payloadLength = bodyLength // 0-125 + let offset = 6 + + if (bodyLength > maxUnsigned16Bit) { + offset += 8 // payload length is next 8 bytes + payloadLength = 127 + } else if (bodyLength > 125) { + offset += 2 // payload length is next 2 bytes + payloadLength = 126 + } + + const buffer = Buffer.allocUnsafe(bodyLength + offset) + + // Clear first 2 bytes, everything else is overwritten + buffer[0] = buffer[1] = 0 + buffer[0] |= 0x80 // FIN + buffer[0] = (buffer[0] & 0xF0) + opcode // opcode + + /*! ws. MIT License. Einar Otto Stangvik */ + buffer[offset - 4] = maskKey[0] + buffer[offset - 3] = maskKey[1] + buffer[offset - 2] = maskKey[2] + buffer[offset - 1] = maskKey[3] + + buffer[1] = payloadLength + + if (payloadLength === 126) { + buffer.writeUInt16BE(bodyLength, 2) + } else if (payloadLength === 127) { + // Clear extended payload length + buffer[2] = buffer[3] = 0 + buffer.writeUIntBE(bodyLength, 4, 6) + } + + buffer[1] |= 0x80 // MASK + + // mask body + for (let i = 0; i < bodyLength; ++i) { + buffer[offset + i] = frameData[i] ^ maskKey[i & 3] + } + + return buffer + } + + /** + * @param {Uint8Array} buffer + */ + static createFastTextFrame (buffer) { + const maskKey = generateMask() + + const bodyLength = buffer.length + + // mask body + for (let i = 0; i < bodyLength; ++i) { + buffer[i] ^= maskKey[i & 3] + } + + let payloadLength = bodyLength + let offset = 6 + + if (bodyLength > maxUnsigned16Bit) { + offset += 8 // payload length is next 8 bytes + payloadLength = 127 + } else if (bodyLength > 125) { + offset += 2 // payload length is next 2 bytes + payloadLength = 126 + } + const head = Buffer.allocUnsafeSlow(offset) + + head[0] = 0x80 /* FIN */ | opcodes.TEXT /* opcode TEXT */ + head[1] = payloadLength | 0x80 /* MASK */ + head[offset - 4] = maskKey[0] + head[offset - 3] = maskKey[1] + head[offset - 2] = maskKey[2] + head[offset - 1] = maskKey[3] + + if (payloadLength === 126) { + head.writeUInt16BE(bodyLength, 2) + } else if (payloadLength === 127) { + head[2] = head[3] = 0 + head.writeUIntBE(bodyLength, 4, 6) + } + + return [head, buffer] + } +} + +module.exports = { + WebsocketFrameSend, + generateMask // for benchmark +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/websocket/permessage-deflate.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/websocket/permessage-deflate.js new file mode 100644 index 0000000000000000000000000000000000000000..76cb366d5e556fdcefd00c36255fdb1b4a7d3a89 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/websocket/permessage-deflate.js @@ -0,0 +1,70 @@ +'use strict' + +const { createInflateRaw, Z_DEFAULT_WINDOWBITS } = require('node:zlib') +const { isValidClientWindowBits } = require('./util') + +const tail = Buffer.from([0x00, 0x00, 0xff, 0xff]) +const kBuffer = Symbol('kBuffer') +const kLength = Symbol('kLength') + +class PerMessageDeflate { + /** @type {import('node:zlib').InflateRaw} */ + #inflate + + #options = {} + + constructor (extensions) { + this.#options.serverNoContextTakeover = extensions.has('server_no_context_takeover') + this.#options.serverMaxWindowBits = extensions.get('server_max_window_bits') + } + + decompress (chunk, fin, callback) { + // An endpoint uses the following algorithm to decompress a message. + // 1. Append 4 octets of 0x00 0x00 0xff 0xff to the tail end of the + // payload of the message. + // 2. Decompress the resulting data using DEFLATE. + + if (!this.#inflate) { + let windowBits = Z_DEFAULT_WINDOWBITS + + if (this.#options.serverMaxWindowBits) { // empty values default to Z_DEFAULT_WINDOWBITS + if (!isValidClientWindowBits(this.#options.serverMaxWindowBits)) { + callback(new Error('Invalid server_max_window_bits')) + return + } + + windowBits = Number.parseInt(this.#options.serverMaxWindowBits) + } + + this.#inflate = createInflateRaw({ windowBits }) + this.#inflate[kBuffer] = [] + this.#inflate[kLength] = 0 + + this.#inflate.on('data', (data) => { + this.#inflate[kBuffer].push(data) + this.#inflate[kLength] += data.length + }) + + this.#inflate.on('error', (err) => { + this.#inflate = null + callback(err) + }) + } + + this.#inflate.write(chunk) + if (fin) { + this.#inflate.write(tail) + } + + this.#inflate.flush(() => { + const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]) + + this.#inflate[kBuffer].length = 0 + this.#inflate[kLength] = 0 + + callback(null, full) + }) + } +} + +module.exports = { PerMessageDeflate } diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/websocket/receiver.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/websocket/receiver.js new file mode 100644 index 0000000000000000000000000000000000000000..ba0a5aa0773e4acd1e268b3c0796c2d2ff4b91d7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/websocket/receiver.js @@ -0,0 +1,444 @@ +'use strict' + +const { Writable } = require('node:stream') +const assert = require('node:assert') +const { parserStates, opcodes, states, emptyBuffer, sentCloseFrameState } = require('./constants') +const { + isValidStatusCode, + isValidOpcode, + websocketMessageReceived, + utf8Decode, + isControlFrame, + isTextBinaryFrame, + isContinuationFrame +} = require('./util') +const { failWebsocketConnection } = require('./connection') +const { WebsocketFrameSend } = require('./frame') +const { PerMessageDeflate } = require('./permessage-deflate') + +// This code was influenced by ws released under the MIT license. +// Copyright (c) 2011 Einar Otto Stangvik +// Copyright (c) 2013 Arnout Kazemier and contributors +// Copyright (c) 2016 Luigi Pinca and contributors + +class ByteParser extends Writable { + #buffers = [] + #fragmentsBytes = 0 + #byteOffset = 0 + #loop = false + + #state = parserStates.INFO + + #info = {} + #fragments = [] + + /** @type {Map} */ + #extensions + + /** @type {import('./websocket').Handler} */ + #handler + + constructor (handler, extensions) { + super() + + this.#handler = handler + this.#extensions = extensions == null ? new Map() : extensions + + if (this.#extensions.has('permessage-deflate')) { + this.#extensions.set('permessage-deflate', new PerMessageDeflate(extensions)) + } + } + + /** + * @param {Buffer} chunk + * @param {() => void} callback + */ + _write (chunk, _, callback) { + this.#buffers.push(chunk) + this.#byteOffset += chunk.length + this.#loop = true + + this.run(callback) + } + + /** + * Runs whenever a new chunk is received. + * Callback is called whenever there are no more chunks buffering, + * or not enough bytes are buffered to parse. + */ + run (callback) { + while (this.#loop) { + if (this.#state === parserStates.INFO) { + // If there aren't enough bytes to parse the payload length, etc. + if (this.#byteOffset < 2) { + return callback() + } + + const buffer = this.consume(2) + const fin = (buffer[0] & 0x80) !== 0 + const opcode = buffer[0] & 0x0F + const masked = (buffer[1] & 0x80) === 0x80 + + const fragmented = !fin && opcode !== opcodes.CONTINUATION + const payloadLength = buffer[1] & 0x7F + + const rsv1 = buffer[0] & 0x40 + const rsv2 = buffer[0] & 0x20 + const rsv3 = buffer[0] & 0x10 + + if (!isValidOpcode(opcode)) { + failWebsocketConnection(this.#handler, 1002, 'Invalid opcode received') + return callback() + } + + if (masked) { + failWebsocketConnection(this.#handler, 1002, 'Frame cannot be masked') + return callback() + } + + // MUST be 0 unless an extension is negotiated that defines meanings + // for non-zero values. If a nonzero value is received and none of + // the negotiated extensions defines the meaning of such a nonzero + // value, the receiving endpoint MUST _Fail the WebSocket + // Connection_. + // This document allocates the RSV1 bit of the WebSocket header for + // PMCEs and calls the bit the "Per-Message Compressed" bit. On a + // WebSocket connection where a PMCE is in use, this bit indicates + // whether a message is compressed or not. + if (rsv1 !== 0 && !this.#extensions.has('permessage-deflate')) { + failWebsocketConnection(this.#handler, 1002, 'Expected RSV1 to be clear.') + return + } + + if (rsv2 !== 0 || rsv3 !== 0) { + failWebsocketConnection(this.#handler, 1002, 'RSV1, RSV2, RSV3 must be clear') + return + } + + if (fragmented && !isTextBinaryFrame(opcode)) { + // Only text and binary frames can be fragmented + failWebsocketConnection(this.#handler, 1002, 'Invalid frame type was fragmented.') + return + } + + // If we are already parsing a text/binary frame and do not receive either + // a continuation frame or close frame, fail the connection. + if (isTextBinaryFrame(opcode) && this.#fragments.length > 0) { + failWebsocketConnection(this.#handler, 1002, 'Expected continuation frame') + return + } + + if (this.#info.fragmented && fragmented) { + // A fragmented frame can't be fragmented itself + failWebsocketConnection(this.#handler, 1002, 'Fragmented frame exceeded 125 bytes.') + return + } + + // "All control frames MUST have a payload length of 125 bytes or less + // and MUST NOT be fragmented." + if ((payloadLength > 125 || fragmented) && isControlFrame(opcode)) { + failWebsocketConnection(this.#handler, 1002, 'Control frame either too large or fragmented') + return + } + + if (isContinuationFrame(opcode) && this.#fragments.length === 0 && !this.#info.compressed) { + failWebsocketConnection(this.#handler, 1002, 'Unexpected continuation frame') + return + } + + if (payloadLength <= 125) { + this.#info.payloadLength = payloadLength + this.#state = parserStates.READ_DATA + } else if (payloadLength === 126) { + this.#state = parserStates.PAYLOADLENGTH_16 + } else if (payloadLength === 127) { + this.#state = parserStates.PAYLOADLENGTH_64 + } + + if (isTextBinaryFrame(opcode)) { + this.#info.binaryType = opcode + this.#info.compressed = rsv1 !== 0 + } + + this.#info.opcode = opcode + this.#info.masked = masked + this.#info.fin = fin + this.#info.fragmented = fragmented + } else if (this.#state === parserStates.PAYLOADLENGTH_16) { + if (this.#byteOffset < 2) { + return callback() + } + + const buffer = this.consume(2) + + this.#info.payloadLength = buffer.readUInt16BE(0) + this.#state = parserStates.READ_DATA + } else if (this.#state === parserStates.PAYLOADLENGTH_64) { + if (this.#byteOffset < 8) { + return callback() + } + + const buffer = this.consume(8) + const upper = buffer.readUInt32BE(0) + + // 2^31 is the maximum bytes an arraybuffer can contain + // on 32-bit systems. Although, on 64-bit systems, this is + // 2^53-1 bytes. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length + // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/common/globals.h;drc=1946212ac0100668f14eb9e2843bdd846e510a1e;bpv=1;bpt=1;l=1275 + // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-array-buffer.h;l=34;drc=1946212ac0100668f14eb9e2843bdd846e510a1e + if (upper > 2 ** 31 - 1) { + failWebsocketConnection(this.#handler, 1009, 'Received payload length > 2^31 bytes.') + return + } + + const lower = buffer.readUInt32BE(4) + + this.#info.payloadLength = (upper << 8) + lower + this.#state = parserStates.READ_DATA + } else if (this.#state === parserStates.READ_DATA) { + if (this.#byteOffset < this.#info.payloadLength) { + return callback() + } + + const body = this.consume(this.#info.payloadLength) + + if (isControlFrame(this.#info.opcode)) { + this.#loop = this.parseControlFrame(body) + this.#state = parserStates.INFO + } else { + if (!this.#info.compressed) { + this.writeFragments(body) + + // If the frame is not fragmented, a message has been received. + // If the frame is fragmented, it will terminate with a fin bit set + // and an opcode of 0 (continuation), therefore we handle that when + // parsing continuation frames, not here. + if (!this.#info.fragmented && this.#info.fin) { + websocketMessageReceived(this.#handler, this.#info.binaryType, this.consumeFragments()) + } + + this.#state = parserStates.INFO + } else { + this.#extensions.get('permessage-deflate').decompress(body, this.#info.fin, (error, data) => { + if (error) { + failWebsocketConnection(this.#handler, 1007, error.message) + return + } + + this.writeFragments(data) + + if (!this.#info.fin) { + this.#state = parserStates.INFO + this.#loop = true + this.run(callback) + return + } + + websocketMessageReceived(this.#handler, this.#info.binaryType, this.consumeFragments()) + + this.#loop = true + this.#state = parserStates.INFO + this.run(callback) + }) + + this.#loop = false + break + } + } + } + } + } + + /** + * Take n bytes from the buffered Buffers + * @param {number} n + * @returns {Buffer} + */ + consume (n) { + if (n > this.#byteOffset) { + throw new Error('Called consume() before buffers satiated.') + } else if (n === 0) { + return emptyBuffer + } + + this.#byteOffset -= n + + const first = this.#buffers[0] + + if (first.length > n) { + // replace with remaining buffer + this.#buffers[0] = first.subarray(n, first.length) + return first.subarray(0, n) + } else if (first.length === n) { + // prefect match + return this.#buffers.shift() + } else { + let offset = 0 + // If Buffer.allocUnsafe is used, extra copies will be made because the offset is non-zero. + const buffer = Buffer.allocUnsafeSlow(n) + while (offset !== n) { + const next = this.#buffers[0] + const length = next.length + + if (length + offset === n) { + buffer.set(this.#buffers.shift(), offset) + break + } else if (length + offset > n) { + buffer.set(next.subarray(0, n - offset), offset) + this.#buffers[0] = next.subarray(n - offset) + break + } else { + buffer.set(this.#buffers.shift(), offset) + offset += length + } + } + + return buffer + } + } + + writeFragments (fragment) { + this.#fragmentsBytes += fragment.length + this.#fragments.push(fragment) + } + + consumeFragments () { + const fragments = this.#fragments + + if (fragments.length === 1) { + // single fragment + this.#fragmentsBytes = 0 + return fragments.shift() + } + + let offset = 0 + // If Buffer.allocUnsafe is used, extra copies will be made because the offset is non-zero. + const output = Buffer.allocUnsafeSlow(this.#fragmentsBytes) + + for (let i = 0; i < fragments.length; ++i) { + const buffer = fragments[i] + output.set(buffer, offset) + offset += buffer.length + } + + this.#fragments = [] + this.#fragmentsBytes = 0 + + return output + } + + parseCloseBody (data) { + assert(data.length !== 1) + + // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5 + /** @type {number|undefined} */ + let code + + if (data.length >= 2) { + // _The WebSocket Connection Close Code_ is + // defined as the status code (Section 7.4) contained in the first Close + // control frame received by the application + code = data.readUInt16BE(0) + } + + if (code !== undefined && !isValidStatusCode(code)) { + return { code: 1002, reason: 'Invalid status code', error: true } + } + + // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6 + /** @type {Buffer} */ + let reason = data.subarray(2) + + // Remove BOM + if (reason[0] === 0xEF && reason[1] === 0xBB && reason[2] === 0xBF) { + reason = reason.subarray(3) + } + + try { + reason = utf8Decode(reason) + } catch { + return { code: 1007, reason: 'Invalid UTF-8', error: true } + } + + return { code, reason, error: false } + } + + /** + * Parses control frames. + * @param {Buffer} body + */ + parseControlFrame (body) { + const { opcode, payloadLength } = this.#info + + if (opcode === opcodes.CLOSE) { + if (payloadLength === 1) { + failWebsocketConnection(this.#handler, 1002, 'Received close frame with a 1-byte body.') + return false + } + + this.#info.closeInfo = this.parseCloseBody(body) + + if (this.#info.closeInfo.error) { + const { code, reason } = this.#info.closeInfo + + failWebsocketConnection(this.#handler, code, reason) + return false + } + + // Upon receiving such a frame, the other peer sends a + // Close frame in response, if it hasn't already sent one. + if (!this.#handler.closeState.has(sentCloseFrameState.SENT) && !this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) { + // If an endpoint receives a Close frame and did not previously send a + // Close frame, the endpoint MUST send a Close frame in response. (When + // sending a Close frame in response, the endpoint typically echos the + // status code it received.) + let body = emptyBuffer + if (this.#info.closeInfo.code) { + body = Buffer.allocUnsafe(2) + body.writeUInt16BE(this.#info.closeInfo.code, 0) + } + const closeFrame = new WebsocketFrameSend(body) + + this.#handler.socket.write(closeFrame.createFrame(opcodes.CLOSE)) + this.#handler.closeState.add(sentCloseFrameState.SENT) + } + + // Upon either sending or receiving a Close control frame, it is said + // that _The WebSocket Closing Handshake is Started_ and that the + // WebSocket connection is in the CLOSING state. + this.#handler.readyState = states.CLOSING + this.#handler.closeState.add(sentCloseFrameState.RECEIVED) + + return false + } else if (opcode === opcodes.PING) { + // Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in + // response, unless it already received a Close frame. + // A Pong frame sent in response to a Ping frame must have identical + // "Application data" + + if (!this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) { + const frame = new WebsocketFrameSend(body) + + this.#handler.socket.write(frame.createFrame(opcodes.PONG)) + + this.#handler.onPing(body) + } + } else if (opcode === opcodes.PONG) { + // A Pong frame MAY be sent unsolicited. This serves as a + // unidirectional heartbeat. A response to an unsolicited Pong frame is + // not expected. + this.#handler.onPong(body) + } + + return true + } + + get closingInfo () { + return this.#info.closeInfo + } +} + +module.exports = { + ByteParser +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/websocket/sender.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/websocket/sender.js new file mode 100644 index 0000000000000000000000000000000000000000..c647bf629d7c1f923dfce2d696faedc140d9d225 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/websocket/sender.js @@ -0,0 +1,109 @@ +'use strict' + +const { WebsocketFrameSend } = require('./frame') +const { opcodes, sendHints } = require('./constants') +const FixedQueue = require('../../dispatcher/fixed-queue') + +/** + * @typedef {object} SendQueueNode + * @property {Promise | null} promise + * @property {((...args: any[]) => any)} callback + * @property {Buffer | null} frame + */ + +class SendQueue { + /** + * @type {FixedQueue} + */ + #queue = new FixedQueue() + + /** + * @type {boolean} + */ + #running = false + + /** @type {import('node:net').Socket} */ + #socket + + constructor (socket) { + this.#socket = socket + } + + add (item, cb, hint) { + if (hint !== sendHints.blob) { + if (!this.#running) { + // TODO(@tsctx): support fast-path for string on running + if (hint === sendHints.text) { + // special fast-path for string + const { 0: head, 1: body } = WebsocketFrameSend.createFastTextFrame(item) + this.#socket.cork() + this.#socket.write(head) + this.#socket.write(body, cb) + this.#socket.uncork() + } else { + // direct writing + this.#socket.write(createFrame(item, hint), cb) + } + } else { + /** @type {SendQueueNode} */ + const node = { + promise: null, + callback: cb, + frame: createFrame(item, hint) + } + this.#queue.push(node) + } + return + } + + /** @type {SendQueueNode} */ + const node = { + promise: item.arrayBuffer().then((ab) => { + node.promise = null + node.frame = createFrame(ab, hint) + }), + callback: cb, + frame: null + } + + this.#queue.push(node) + + if (!this.#running) { + this.#run() + } + } + + async #run () { + this.#running = true + const queue = this.#queue + while (!queue.isEmpty()) { + const node = queue.shift() + // wait pending promise + if (node.promise !== null) { + await node.promise + } + // write + this.#socket.write(node.frame, node.callback) + // cleanup + node.callback = node.frame = null + } + this.#running = false + } +} + +function createFrame (data, hint) { + return new WebsocketFrameSend(toBuffer(data, hint)).createFrame(hint === sendHints.text ? opcodes.TEXT : opcodes.BINARY) +} + +function toBuffer (data, hint) { + switch (hint) { + case sendHints.text: + case sendHints.typedArray: + return new Uint8Array(data.buffer, data.byteOffset, data.byteLength) + case sendHints.arrayBuffer: + case sendHints.blob: + return new Uint8Array(data) + } +} + +module.exports = { SendQueue } diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/websocket/stream/websocketerror.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/websocket/stream/websocketerror.js new file mode 100644 index 0000000000000000000000000000000000000000..e57b0697d60e0b50864a323a2e49c9d78d1ea8e7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/websocket/stream/websocketerror.js @@ -0,0 +1,83 @@ +'use strict' + +const { webidl } = require('../../webidl') +const { validateCloseCodeAndReason } = require('../util') +const { kConstruct } = require('../../../core/symbols') +const { kEnumerableProperty } = require('../../../core/util') + +class WebSocketError extends DOMException { + #closeCode + #reason + + constructor (message = '', init = undefined) { + message = webidl.converters.DOMString(message, 'WebSocketError', 'message') + + // 1. Set this 's name to " WebSocketError ". + // 2. Set this 's message to message . + super(message, 'WebSocketError') + + if (init === kConstruct) { + return + } else if (init !== null) { + init = webidl.converters.WebSocketCloseInfo(init) + } + + // 3. Let code be init [" closeCode "] if it exists , or null otherwise. + let code = init.closeCode ?? null + + // 4. Let reason be init [" reason "] if it exists , or the empty string otherwise. + const reason = init.reason ?? '' + + // 5. Validate close code and reason with code and reason . + validateCloseCodeAndReason(code, reason) + + // 6. If reason is non-empty, but code is not set, then set code to 1000 ("Normal Closure"). + if (reason.length !== 0 && code === null) { + code = 1000 + } + + // 7. Set this 's closeCode to code . + this.#closeCode = code + + // 8. Set this 's reason to reason . + this.#reason = reason + } + + get closeCode () { + return this.#closeCode + } + + get reason () { + return this.#reason + } + + /** + * @param {string} message + * @param {number|null} code + * @param {string} reason + */ + static createUnvalidatedWebSocketError (message, code, reason) { + const error = new WebSocketError(message, kConstruct) + error.#closeCode = code + error.#reason = reason + return error + } +} + +const { createUnvalidatedWebSocketError } = WebSocketError +delete WebSocketError.createUnvalidatedWebSocketError + +Object.defineProperties(WebSocketError.prototype, { + closeCode: kEnumerableProperty, + reason: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'WebSocketError', + writable: false, + enumerable: false, + configurable: true + } +}) + +webidl.is.WebSocketError = webidl.util.MakeTypeAssertion(WebSocketError) + +module.exports = { WebSocketError, createUnvalidatedWebSocketError } diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/websocket/stream/websocketstream.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/websocket/stream/websocketstream.js new file mode 100644 index 0000000000000000000000000000000000000000..e7a8bce614a11d5135a2a7db4811973352bb30f6 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/websocket/stream/websocketstream.js @@ -0,0 +1,488 @@ +'use strict' + +const { createDeferredPromise } = require('../../../util/promise') +const { environmentSettingsObject } = require('../../fetch/util') +const { states, opcodes, sentCloseFrameState } = require('../constants') +const { webidl } = require('../../webidl') +const { getURLRecord, isValidSubprotocol, isEstablished, utf8Decode } = require('../util') +const { establishWebSocketConnection, failWebsocketConnection, closeWebSocketConnection } = require('../connection') +const { isArrayBuffer } = require('node:util/types') +const { channels } = require('../../../core/diagnostics') +const { WebsocketFrameSend } = require('../frame') +const { ByteParser } = require('../receiver') +const { WebSocketError, createUnvalidatedWebSocketError } = require('./websocketerror') +const { utf8DecodeBytes } = require('../../fetch/util') +const { kEnumerableProperty } = require('../../../core/util') + +let emittedExperimentalWarning = false + +class WebSocketStream { + // Each WebSocketStream object has an associated url , which is a URL record . + /** @type {URL} */ + #url + + // Each WebSocketStream object has an associated opened promise , which is a promise. + /** @type {import('../../../util/promise').DeferredPromise} */ + #openedPromise + + // Each WebSocketStream object has an associated closed promise , which is a promise. + /** @type {import('../../../util/promise').DeferredPromise} */ + #closedPromise + + // Each WebSocketStream object has an associated readable stream , which is a ReadableStream . + /** @type {ReadableStream} */ + #readableStream + /** @type {ReadableStreamDefaultController} */ + #readableStreamController + + // Each WebSocketStream object has an associated writable stream , which is a WritableStream . + /** @type {WritableStream} */ + #writableStream + + // Each WebSocketStream object has an associated boolean handshake aborted , which is initially false. + #handshakeAborted = false + + /** @type {import('../websocket').Handler} */ + #handler = { + // https://whatpr.org/websockets/48/7b748d3...d5570f3.html#feedback-to-websocket-stream-from-the-protocol + onConnectionEstablished: (response, extensions) => this.#onConnectionEstablished(response, extensions), + onFail: (_code, _reason) => {}, + onMessage: (opcode, data) => this.#onMessage(opcode, data), + onParserError: (err) => failWebsocketConnection(this.#handler, null, err.message), + onParserDrain: () => this.#handler.socket.resume(), + onSocketData: (chunk) => { + if (!this.#parser.write(chunk)) { + this.#handler.socket.pause() + } + }, + onSocketError: (err) => { + this.#handler.readyState = states.CLOSING + + if (channels.socketError.hasSubscribers) { + channels.socketError.publish(err) + } + + this.#handler.socket.destroy() + }, + onSocketClose: () => this.#onSocketClose(), + onPing: () => {}, + onPong: () => {}, + + readyState: states.CONNECTING, + socket: null, + closeState: new Set(), + controller: null, + wasEverConnected: false + } + + /** @type {import('../receiver').ByteParser} */ + #parser + + constructor (url, options = undefined) { + if (!emittedExperimentalWarning) { + process.emitWarning('WebSocketStream is experimental! Expect it to change at any time.', { + code: 'UNDICI-WSS' + }) + emittedExperimentalWarning = true + } + + webidl.argumentLengthCheck(arguments, 1, 'WebSocket') + + url = webidl.converters.USVString(url) + if (options !== null) { + options = webidl.converters.WebSocketStreamOptions(options) + } + + // 1. Let baseURL be this 's relevant settings object 's API base URL . + const baseURL = environmentSettingsObject.settingsObject.baseUrl + + // 2. Let urlRecord be the result of getting a URL record given url and baseURL . + const urlRecord = getURLRecord(url, baseURL) + + // 3. Let protocols be options [" protocols "] if it exists , otherwise an empty sequence. + const protocols = options.protocols + + // 4. If any of the values in protocols occur more than once or otherwise fail to match the requirements for elements that comprise the value of ` Sec-WebSocket-Protocol ` fields as defined by The WebSocket Protocol , then throw a " SyntaxError " DOMException . [WSP] + if (protocols.length !== new Set(protocols.map(p => p.toLowerCase())).size) { + throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') + } + + if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) { + throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') + } + + // 5. Set this 's url to urlRecord . + this.#url = urlRecord.toString() + + // 6. Set this 's opened promise and closed promise to new promises. + this.#openedPromise = createDeferredPromise() + this.#closedPromise = createDeferredPromise() + + // 7. Apply backpressure to the WebSocket. + // TODO + + // 8. If options [" signal "] exists , + if (options.signal != null) { + // 8.1. Let signal be options [" signal "]. + const signal = options.signal + + // 8.2. If signal is aborted , then reject this 's opened promise and closed promise with signal ’s abort reason + // and return. + if (signal.aborted) { + this.#openedPromise.reject(signal.reason) + this.#closedPromise.reject(signal.reason) + return + } + + // 8.3. Add the following abort steps to signal : + signal.addEventListener('abort', () => { + // 8.3.1. If the WebSocket connection is not yet established : [WSP] + if (!isEstablished(this.#handler.readyState)) { + // 8.3.1.1. Fail the WebSocket connection . + failWebsocketConnection(this.#handler) + + // Set this 's ready state to CLOSING . + this.#handler.readyState = states.CLOSING + + // Reject this 's opened promise and closed promise with signal ’s abort reason . + this.#openedPromise.reject(signal.reason) + this.#closedPromise.reject(signal.reason) + + // Set this 's handshake aborted to true. + this.#handshakeAborted = true + } + }, { once: true }) + } + + // 9. Let client be this 's relevant settings object . + const client = environmentSettingsObject.settingsObject + + // 10. Run this step in parallel : + // 10.1. Establish a WebSocket connection given urlRecord , protocols , and client . [FETCH] + this.#handler.controller = establishWebSocketConnection( + urlRecord, + protocols, + client, + this.#handler, + options + ) + } + + // The url getter steps are to return this 's url , serialized . + get url () { + return this.#url.toString() + } + + // The opened getter steps are to return this 's opened promise . + get opened () { + return this.#openedPromise.promise + } + + // The closed getter steps are to return this 's closed promise . + get closed () { + return this.#closedPromise.promise + } + + // The close( closeInfo ) method steps are: + close (closeInfo = undefined) { + if (closeInfo !== null) { + closeInfo = webidl.converters.WebSocketCloseInfo(closeInfo) + } + + // 1. Let code be closeInfo [" closeCode "] if present, or null otherwise. + const code = closeInfo.closeCode ?? null + + // 2. Let reason be closeInfo [" reason "]. + const reason = closeInfo.reason + + // 3. Close the WebSocket with this , code , and reason . + closeWebSocketConnection(this.#handler, code, reason, true) + } + + #write (chunk) { + // 1. Let promise be a new promise created in stream ’s relevant realm . + const promise = createDeferredPromise() + + // 2. Let data be null. + let data = null + + // 3. Let opcode be null. + let opcode = null + + // 4. If chunk is a BufferSource , + if (ArrayBuffer.isView(chunk) || isArrayBuffer(chunk)) { + // 4.1. Set data to a copy of the bytes given chunk . + data = new Uint8Array(ArrayBuffer.isView(chunk) ? new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength) : chunk) + + // 4.2. Set opcode to a binary frame opcode. + opcode = opcodes.BINARY + } else { + // 5. Otherwise, + + // 5.1. Let string be the result of converting chunk to an IDL USVString . + // If this throws an exception, return a promise rejected with the exception. + let string + + try { + string = webidl.converters.DOMString(chunk) + } catch (e) { + promise.reject(e) + return + } + + // 5.2. Set data to the result of UTF-8 encoding string . + data = new TextEncoder().encode(string) + + // 5.3. Set opcode to a text frame opcode. + opcode = opcodes.TEXT + } + + // 6. In parallel, + // 6.1. Wait until there is sufficient buffer space in stream to send the message. + + // 6.2. If the closing handshake has not yet started , Send a WebSocket Message to stream comprised of data using opcode . + if (!this.#handler.closeState.has(sentCloseFrameState.SENT) && !this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) { + const frame = new WebsocketFrameSend(data) + + this.#handler.socket.write(frame.createFrame(opcode), () => { + promise.resolve(undefined) + }) + } + + // 6.3. Queue a global task on the WebSocket task source given stream ’s relevant global object to resolve promise with undefined. + return promise + } + + /** @type {import('../websocket').Handler['onConnectionEstablished']} */ + #onConnectionEstablished (response, parsedExtensions) { + this.#handler.socket = response.socket + + const parser = new ByteParser(this.#handler, parsedExtensions) + parser.on('drain', () => this.#handler.onParserDrain()) + parser.on('error', (err) => this.#handler.onParserError(err)) + + this.#parser = parser + + // 1. Change stream ’s ready state to OPEN (1). + this.#handler.readyState = states.OPEN + + // 2. Set stream ’s was ever connected to true. + // This is done in the opening handshake. + + // 3. Let extensions be the extensions in use . + const extensions = parsedExtensions ?? '' + + // 4. Let protocol be the subprotocol in use . + const protocol = response.headersList.get('sec-websocket-protocol') ?? '' + + // 5. Let pullAlgorithm be an action that pulls bytes from stream . + // 6. Let cancelAlgorithm be an action that cancels stream with reason , given reason . + // 7. Let readable be a new ReadableStream . + // 8. Set up readable with pullAlgorithm and cancelAlgorithm . + const readable = new ReadableStream({ + start: (controller) => { + this.#readableStreamController = controller + }, + pull (controller) { + let chunk + while (controller.desiredSize > 0 && (chunk = response.socket.read()) !== null) { + controller.enqueue(chunk) + } + }, + cancel: (reason) => this.#cancel(reason) + }) + + // 9. Let writeAlgorithm be an action that writes chunk to stream , given chunk . + // 10. Let closeAlgorithm be an action that closes stream . + // 11. Let abortAlgorithm be an action that aborts stream with reason , given reason . + // 12. Let writable be a new WritableStream . + // 13. Set up writable with writeAlgorithm , closeAlgorithm , and abortAlgorithm . + const writable = new WritableStream({ + write: (chunk) => this.#write(chunk), + close: () => closeWebSocketConnection(this.#handler, null, null), + abort: (reason) => this.#closeUsingReason(reason) + }) + + // Set stream ’s readable stream to readable . + this.#readableStream = readable + + // Set stream ’s writable stream to writable . + this.#writableStream = writable + + // Resolve stream ’s opened promise with WebSocketOpenInfo «[ " extensions " → extensions , " protocol " → protocol , " readable " → readable , " writable " → writable ]». + this.#openedPromise.resolve({ + extensions, + protocol, + readable, + writable + }) + } + + /** @type {import('../websocket').Handler['onMessage']} */ + #onMessage (type, data) { + // 1. If stream’s ready state is not OPEN (1), then return. + if (this.#handler.readyState !== states.OPEN) { + return + } + + // 2. Let chunk be determined by switching on type: + // - type indicates that the data is Text + // a new DOMString containing data + // - type indicates that the data is Binary + // a new Uint8Array object, created in the relevant Realm of the + // WebSocketStream object, whose contents are data + let chunk + + if (type === opcodes.TEXT) { + try { + chunk = utf8Decode(data) + } catch { + failWebsocketConnection(this.#handler, 'Received invalid UTF-8 in text frame.') + return + } + } else if (type === opcodes.BINARY) { + chunk = new Uint8Array(data.buffer, data.byteOffset, data.byteLength) + } + + // 3. Enqueue chunk into stream’s readable stream. + this.#readableStreamController.enqueue(chunk) + + // 4. Apply backpressure to the WebSocket. + } + + /** @type {import('../websocket').Handler['onSocketClose']} */ + #onSocketClose () { + const wasClean = + this.#handler.closeState.has(sentCloseFrameState.SENT) && + this.#handler.closeState.has(sentCloseFrameState.RECEIVED) + + // 1. Change the ready state to CLOSED (3). + this.#handler.readyState = states.CLOSED + + // 2. If stream ’s handshake aborted is true, then return. + if (this.#handshakeAborted) { + return + } + + // 3. If stream ’s was ever connected is false, then reject stream ’s opened promise with a new WebSocketError. + if (!this.#handler.wasEverConnected) { + this.#openedPromise.reject(new WebSocketError('Socket never opened')) + } + + const result = this.#parser.closingInfo + + // 4. Let code be the WebSocket connection close code . + // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5 + // If this Close control frame contains no status code, _The WebSocket + // Connection Close Code_ is considered to be 1005. If _The WebSocket + // Connection is Closed_ and no Close control frame was received by the + // endpoint (such as could occur if the underlying transport connection + // is lost), _The WebSocket Connection Close Code_ is considered to be + // 1006. + let code = result?.code ?? 1005 + + if (!this.#handler.closeState.has(sentCloseFrameState.SENT) && !this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) { + code = 1006 + } + + // 5. Let reason be the result of applying UTF-8 decode without BOM to the WebSocket connection close reason . + const reason = result?.reason == null ? '' : utf8DecodeBytes(Buffer.from(result.reason)) + + // 6. If the connection was closed cleanly , + if (wasClean) { + // 6.1. Close stream ’s readable stream . + this.#readableStreamController.close() + + // 6.2. Error stream ’s writable stream with an " InvalidStateError " DOMException indicating that a closed WebSocketStream cannot be written to. + if (!this.#writableStream.locked) { + this.#writableStream.abort(new DOMException('A closed WebSocketStream cannot be written to', 'InvalidStateError')) + } + + // 6.3. Resolve stream ’s closed promise with WebSocketCloseInfo «[ " closeCode " → code , " reason " → reason ]». + this.#closedPromise.resolve({ + closeCode: code, + reason + }) + } else { + // 7. Otherwise, + + // 7.1. Let error be a new WebSocketError whose closeCode is code and reason is reason . + const error = createUnvalidatedWebSocketError('unclean close', code, reason) + + // 7.2. Error stream ’s readable stream with error . + this.#readableStreamController.error(error) + + // 7.3. Error stream ’s writable stream with error . + this.#writableStream.abort(error) + + // 7.4. Reject stream ’s closed promise with error . + this.#closedPromise.reject(error) + } + } + + #closeUsingReason (reason) { + // 1. Let code be null. + let code = null + + // 2. Let reasonString be the empty string. + let reasonString = '' + + // 3. If reason implements WebSocketError , + if (webidl.is.WebSocketError(reason)) { + // 3.1. Set code to reason ’s closeCode . + code = reason.closeCode + + // 3.2. Set reasonString to reason ’s reason . + reasonString = reason.reason + } + + // 4. Close the WebSocket with stream , code , and reasonString . If this throws an exception, + // discard code and reasonString and close the WebSocket with stream . + closeWebSocketConnection(this.#handler, code, reasonString) + } + + // To cancel a WebSocketStream stream given reason , close using reason giving stream and reason . + #cancel (reason) { + this.#closeUsingReason(reason) + } +} + +Object.defineProperties(WebSocketStream.prototype, { + url: kEnumerableProperty, + opened: kEnumerableProperty, + closed: kEnumerableProperty, + close: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'WebSocketStream', + writable: false, + enumerable: false, + configurable: true + } +}) + +webidl.converters.WebSocketStreamOptions = webidl.dictionaryConverter([ + { + key: 'protocols', + converter: webidl.sequenceConverter(webidl.converters.USVString), + defaultValue: () => [] + }, + { + key: 'signal', + converter: webidl.nullableConverter(webidl.converters.AbortSignal), + defaultValue: () => null + } +]) + +webidl.converters.WebSocketCloseInfo = webidl.dictionaryConverter([ + { + key: 'closeCode', + converter: (V) => webidl.converters['unsigned short'](V, { enforceRange: true }) + }, + { + key: 'reason', + converter: webidl.converters.USVString, + defaultValue: () => '' + } +]) + +module.exports = { WebSocketStream } diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/websocket/util.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/websocket/util.js new file mode 100644 index 0000000000000000000000000000000000000000..ae8f076c0fbbd4e9ddec8a161f1754f1315a233e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/websocket/util.js @@ -0,0 +1,338 @@ +'use strict' + +const { states, opcodes } = require('./constants') +const { isUtf8 } = require('node:buffer') +const { collectASequenceOfCodePointsFast, removeHTTPWhitespace } = require('../fetch/data-url') + +/** + * @param {number} readyState + * @returns {boolean} + */ +function isConnecting (readyState) { + // If the WebSocket connection is not yet established, and the connection + // is not yet closed, then the WebSocket connection is in the CONNECTING state. + return readyState === states.CONNECTING +} + +/** + * @param {number} readyState + * @returns {boolean} + */ +function isEstablished (readyState) { + // If the server's response is validated as provided for above, it is + // said that _The WebSocket Connection is Established_ and that the + // WebSocket Connection is in the OPEN state. + return readyState === states.OPEN +} + +/** + * @param {number} readyState + * @returns {boolean} + */ +function isClosing (readyState) { + // Upon either sending or receiving a Close control frame, it is said + // that _The WebSocket Closing Handshake is Started_ and that the + // WebSocket connection is in the CLOSING state. + return readyState === states.CLOSING +} + +/** + * @param {number} readyState + * @returns {boolean} + */ +function isClosed (readyState) { + return readyState === states.CLOSED +} + +/** + * @see https://dom.spec.whatwg.org/#concept-event-fire + * @param {string} e + * @param {EventTarget} target + * @param {(...args: ConstructorParameters) => Event} eventFactory + * @param {EventInit | undefined} eventInitDict + * @returns {void} + */ +function fireEvent (e, target, eventFactory = (type, init) => new Event(type, init), eventInitDict = {}) { + // 1. If eventConstructor is not given, then let eventConstructor be Event. + + // 2. Let event be the result of creating an event given eventConstructor, + // in the relevant realm of target. + // 3. Initialize event’s type attribute to e. + const event = eventFactory(e, eventInitDict) + + // 4. Initialize any other IDL attributes of event as described in the + // invocation of this algorithm. + + // 5. Return the result of dispatching event at target, with legacy target + // override flag set if set. + target.dispatchEvent(event) +} + +/** + * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol + * @param {import('./websocket').Handler} handler + * @param {number} type Opcode + * @param {Buffer} data application data + * @returns {void} + */ +function websocketMessageReceived (handler, type, data) { + handler.onMessage(type, data) +} + +/** + * @param {Buffer} buffer + * @returns {ArrayBuffer} + */ +function toArrayBuffer (buffer) { + if (buffer.byteLength === buffer.buffer.byteLength) { + return buffer.buffer + } + return new Uint8Array(buffer).buffer +} + +/** + * @see https://datatracker.ietf.org/doc/html/rfc6455 + * @see https://datatracker.ietf.org/doc/html/rfc2616 + * @see https://bugs.chromium.org/p/chromium/issues/detail?id=398407 + * @param {string} protocol + * @returns {boolean} + */ +function isValidSubprotocol (protocol) { + // If present, this value indicates one + // or more comma-separated subprotocol the client wishes to speak, + // ordered by preference. The elements that comprise this value + // MUST be non-empty strings with characters in the range U+0021 to + // U+007E not including separator characters as defined in + // [RFC2616] and MUST all be unique strings. + if (protocol.length === 0) { + return false + } + + for (let i = 0; i < protocol.length; ++i) { + const code = protocol.charCodeAt(i) + + if ( + code < 0x21 || // CTL, contains SP (0x20) and HT (0x09) + code > 0x7E || + code === 0x22 || // " + code === 0x28 || // ( + code === 0x29 || // ) + code === 0x2C || // , + code === 0x2F || // / + code === 0x3A || // : + code === 0x3B || // ; + code === 0x3C || // < + code === 0x3D || // = + code === 0x3E || // > + code === 0x3F || // ? + code === 0x40 || // @ + code === 0x5B || // [ + code === 0x5C || // \ + code === 0x5D || // ] + code === 0x7B || // { + code === 0x7D // } + ) { + return false + } + } + + return true +} + +/** + * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7-4 + * @param {number} code + * @returns {boolean} + */ +function isValidStatusCode (code) { + if (code >= 1000 && code < 1015) { + return ( + code !== 1004 && // reserved + code !== 1005 && // "MUST NOT be set as a status code" + code !== 1006 // "MUST NOT be set as a status code" + ) + } + + return code >= 3000 && code <= 4999 +} + +/** + * @see https://datatracker.ietf.org/doc/html/rfc6455#section-5.5 + * @param {number} opcode + * @returns {boolean} + */ +function isControlFrame (opcode) { + return ( + opcode === opcodes.CLOSE || + opcode === opcodes.PING || + opcode === opcodes.PONG + ) +} + +/** + * @param {number} opcode + * @returns {boolean} + */ +function isContinuationFrame (opcode) { + return opcode === opcodes.CONTINUATION +} + +/** + * @param {number} opcode + * @returns {boolean} + */ +function isTextBinaryFrame (opcode) { + return opcode === opcodes.TEXT || opcode === opcodes.BINARY +} + +/** + * + * @param {number} opcode + * @returns {boolean} + */ +function isValidOpcode (opcode) { + return isTextBinaryFrame(opcode) || isContinuationFrame(opcode) || isControlFrame(opcode) +} + +/** + * Parses a Sec-WebSocket-Extensions header value. + * @param {string} extensions + * @returns {Map} + */ +// TODO(@Uzlopak, @KhafraDev): make compliant https://datatracker.ietf.org/doc/html/rfc6455#section-9.1 +function parseExtensions (extensions) { + const position = { position: 0 } + const extensionList = new Map() + + while (position.position < extensions.length) { + const pair = collectASequenceOfCodePointsFast(';', extensions, position) + const [name, value = ''] = pair.split('=', 2) + + extensionList.set( + removeHTTPWhitespace(name, true, false), + removeHTTPWhitespace(value, false, true) + ) + + position.position++ + } + + return extensionList +} + +/** + * @see https://www.rfc-editor.org/rfc/rfc7692#section-7.1.2.2 + * @description "client-max-window-bits = 1*DIGIT" + * @param {string} value + * @returns {boolean} + */ +function isValidClientWindowBits (value) { + for (let i = 0; i < value.length; i++) { + const byte = value.charCodeAt(i) + + if (byte < 0x30 || byte > 0x39) { + return false + } + } + + return true +} + +/** + * @see https://whatpr.org/websockets/48/7b748d3...d5570f3.html#get-a-url-record + * @param {string} url + * @param {string} [baseURL] + */ +function getURLRecord (url, baseURL) { + // 1. Let urlRecord be the result of applying the URL parser to url with baseURL . + // 2. If urlRecord is failure, then throw a " SyntaxError " DOMException . + let urlRecord + + try { + urlRecord = new URL(url, baseURL) + } catch (e) { + throw new DOMException(e, 'SyntaxError') + } + + // 3. If urlRecord ’s scheme is " http ", then set urlRecord ’s scheme to " ws ". + // 4. Otherwise, if urlRecord ’s scheme is " https ", set urlRecord ’s scheme to " wss ". + if (urlRecord.protocol === 'http:') { + urlRecord.protocol = 'ws:' + } else if (urlRecord.protocol === 'https:') { + urlRecord.protocol = 'wss:' + } + + // 5. If urlRecord ’s scheme is not " ws " or " wss ", then throw a " SyntaxError " DOMException . + if (urlRecord.protocol !== 'ws:' && urlRecord.protocol !== 'wss:') { + throw new DOMException('expected a ws: or wss: url', 'SyntaxError') + } + + // If urlRecord ’s fragment is non-null, then throw a " SyntaxError " DOMException . + if (urlRecord.hash.length || urlRecord.href.endsWith('#')) { + throw new DOMException('hash', 'SyntaxError') + } + + // Return urlRecord . + return urlRecord +} + +// https://whatpr.org/websockets/48.html#validate-close-code-and-reason +function validateCloseCodeAndReason (code, reason) { + // 1. If code is not null, but is neither an integer equal to + // 1000 nor an integer in the range 3000 to 4999, inclusive, + // throw an "InvalidAccessError" DOMException. + if (code !== null) { + if (code !== 1000 && (code < 3000 || code > 4999)) { + throw new DOMException('invalid code', 'InvalidAccessError') + } + } + + // 2. If reason is not null, then: + if (reason !== null) { + // 2.1. Let reasonBytes be the result of UTF-8 encoding reason. + // 2.2. If reasonBytes is longer than 123 bytes, then throw a + // "SyntaxError" DOMException. + const reasonBytesLength = Buffer.byteLength(reason) + + if (reasonBytesLength > 123) { + throw new DOMException(`Reason must be less than 123 bytes; received ${reasonBytesLength}`, 'SyntaxError') + } + } +} + +/** + * Converts a Buffer to utf-8, even on platforms without icu. + * @type {(buffer: Buffer) => string} + */ +const utf8Decode = (() => { + if (typeof process.versions.icu === 'string') { + const fatalDecoder = new TextDecoder('utf-8', { fatal: true }) + return fatalDecoder.decode.bind(fatalDecoder) + } + return function (buffer) { + if (isUtf8(buffer)) { + return buffer.toString('utf-8') + } + throw new TypeError('Invalid utf-8 received.') + } +})() + +module.exports = { + isConnecting, + isEstablished, + isClosing, + isClosed, + fireEvent, + isValidSubprotocol, + isValidStatusCode, + websocketMessageReceived, + utf8Decode, + isControlFrame, + isContinuationFrame, + isTextBinaryFrame, + isValidOpcode, + parseExtensions, + isValidClientWindowBits, + toArrayBuffer, + getURLRecord, + validateCloseCodeAndReason +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/websocket/websocket.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/websocket/websocket.js new file mode 100644 index 0000000000000000000000000000000000000000..1f10cb0a73a7ed4fe8e856ed9041e101e1ae5307 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/lib/web/websocket/websocket.js @@ -0,0 +1,749 @@ +'use strict' + +const { isArrayBuffer } = require('node:util/types') +const { webidl } = require('../webidl') +const { URLSerializer } = require('../fetch/data-url') +const { environmentSettingsObject } = require('../fetch/util') +const { staticPropertyDescriptors, states, sentCloseFrameState, sendHints, opcodes } = require('./constants') +const { + isConnecting, + isEstablished, + isClosing, + isClosed, + isValidSubprotocol, + fireEvent, + utf8Decode, + toArrayBuffer, + getURLRecord +} = require('./util') +const { establishWebSocketConnection, closeWebSocketConnection, failWebsocketConnection } = require('./connection') +const { ByteParser } = require('./receiver') +const { kEnumerableProperty } = require('../../core/util') +const { getGlobalDispatcher } = require('../../global') +const { ErrorEvent, CloseEvent, createFastMessageEvent } = require('./events') +const { SendQueue } = require('./sender') +const { WebsocketFrameSend } = require('./frame') +const { channels } = require('../../core/diagnostics') + +/** + * @typedef {object} Handler + * @property {(response: any, extensions?: string[]) => void} onConnectionEstablished + * @property {(code: number, reason: any) => void} onFail + * @property {(opcode: number, data: Buffer) => void} onMessage + * @property {(error: Error) => void} onParserError + * @property {() => void} onParserDrain + * @property {(chunk: Buffer) => void} onSocketData + * @property {(err: Error) => void} onSocketError + * @property {() => void} onSocketClose + * @property {(body: Buffer) => void} onPing + * @property {(body: Buffer) => void} onPong + * + * @property {number} readyState + * @property {import('stream').Duplex} socket + * @property {Set} closeState + * @property {import('../fetch/index').Fetch} controller + * @property {boolean} [wasEverConnected=false] + */ + +// https://websockets.spec.whatwg.org/#interface-definition +class WebSocket extends EventTarget { + #events = { + open: null, + error: null, + close: null, + message: null + } + + #bufferedAmount = 0 + #protocol = '' + #extensions = '' + + /** @type {SendQueue} */ + #sendQueue + + /** @type {Handler} */ + #handler = { + onConnectionEstablished: (response, extensions) => this.#onConnectionEstablished(response, extensions), + onFail: (code, reason, cause) => this.#onFail(code, reason, cause), + onMessage: (opcode, data) => this.#onMessage(opcode, data), + onParserError: (err) => failWebsocketConnection(this.#handler, null, err.message), + onParserDrain: () => this.#onParserDrain(), + onSocketData: (chunk) => { + if (!this.#parser.write(chunk)) { + this.#handler.socket.pause() + } + }, + onSocketError: (err) => { + this.#handler.readyState = states.CLOSING + + if (channels.socketError.hasSubscribers) { + channels.socketError.publish(err) + } + + this.#handler.socket.destroy() + }, + onSocketClose: () => this.#onSocketClose(), + onPing: (body) => { + if (channels.ping.hasSubscribers) { + channels.ping.publish({ + payload: body, + websocket: this + }) + } + }, + onPong: (body) => { + if (channels.pong.hasSubscribers) { + channels.pong.publish({ + payload: body, + websocket: this + }) + } + }, + + readyState: states.CONNECTING, + socket: null, + closeState: new Set(), + controller: null, + wasEverConnected: false + } + + #url + #binaryType + /** @type {import('./receiver').ByteParser} */ + #parser + + /** + * @param {string} url + * @param {string|string[]} protocols + */ + constructor (url, protocols = []) { + super() + + webidl.util.markAsUncloneable(this) + + const prefix = 'WebSocket constructor' + webidl.argumentLengthCheck(arguments, 1, prefix) + + const options = webidl.converters['DOMString or sequence or WebSocketInit'](protocols, prefix, 'options') + + url = webidl.converters.USVString(url) + protocols = options.protocols + + // 1. Let baseURL be this's relevant settings object's API base URL. + const baseURL = environmentSettingsObject.settingsObject.baseUrl + + // 2. Let urlRecord be the result of getting a URL record given url and baseURL. + const urlRecord = getURLRecord(url, baseURL) + + // 3. If protocols is a string, set protocols to a sequence consisting + // of just that string. + if (typeof protocols === 'string') { + protocols = [protocols] + } + + // 4. If any of the values in protocols occur more than once or otherwise + // fail to match the requirements for elements that comprise the value + // of `Sec-WebSocket-Protocol` fields as defined by The WebSocket + // protocol, then throw a "SyntaxError" DOMException. + if (protocols.length !== new Set(protocols.map(p => p.toLowerCase())).size) { + throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') + } + + if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) { + throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') + } + + // 5. Set this's url to urlRecord. + this.#url = new URL(urlRecord.href) + + // 6. Let client be this's relevant settings object. + const client = environmentSettingsObject.settingsObject + + // 7. Run this step in parallel: + // 7.1. Establish a WebSocket connection given urlRecord, protocols, + // and client. + this.#handler.controller = establishWebSocketConnection( + urlRecord, + protocols, + client, + this.#handler, + options + ) + + // Each WebSocket object has an associated ready state, which is a + // number representing the state of the connection. Initially it must + // be CONNECTING (0). + this.#handler.readyState = WebSocket.CONNECTING + + // The extensions attribute must initially return the empty string. + + // The protocol attribute must initially return the empty string. + + // Each WebSocket object has an associated binary type, which is a + // BinaryType. Initially it must be "blob". + this.#binaryType = 'blob' + } + + /** + * @see https://websockets.spec.whatwg.org/#dom-websocket-close + * @param {number|undefined} code + * @param {string|undefined} reason + */ + close (code = undefined, reason = undefined) { + webidl.brandCheck(this, WebSocket) + + const prefix = 'WebSocket.close' + + if (code !== undefined) { + code = webidl.converters['unsigned short'](code, prefix, 'code', { clamp: true }) + } + + if (reason !== undefined) { + reason = webidl.converters.USVString(reason) + } + + // 1. If code is the special value "missing", then set code to null. + code ??= null + + // 2. If reason is the special value "missing", then set reason to the empty string. + reason ??= '' + + // 3. Close the WebSocket with this, code, and reason. + closeWebSocketConnection(this.#handler, code, reason, true) + } + + /** + * @see https://websockets.spec.whatwg.org/#dom-websocket-send + * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data + */ + send (data) { + webidl.brandCheck(this, WebSocket) + + const prefix = 'WebSocket.send' + webidl.argumentLengthCheck(arguments, 1, prefix) + + data = webidl.converters.WebSocketSendData(data, prefix, 'data') + + // 1. If this's ready state is CONNECTING, then throw an + // "InvalidStateError" DOMException. + if (isConnecting(this.#handler.readyState)) { + throw new DOMException('Sent before connected.', 'InvalidStateError') + } + + // 2. Run the appropriate set of steps from the following list: + // https://datatracker.ietf.org/doc/html/rfc6455#section-6.1 + // https://datatracker.ietf.org/doc/html/rfc6455#section-5.2 + + if (!isEstablished(this.#handler.readyState) || isClosing(this.#handler.readyState)) { + return + } + + // If data is a string + if (typeof data === 'string') { + // If the WebSocket connection is established and the WebSocket + // closing handshake has not yet started, then the user agent + // must send a WebSocket Message comprised of the data argument + // using a text frame opcode; if the data cannot be sent, e.g. + // because it would need to be buffered but the buffer is full, + // the user agent must flag the WebSocket as full and then close + // the WebSocket connection. Any invocation of this method with a + // string argument that does not throw an exception must increase + // the bufferedAmount attribute by the number of bytes needed to + // express the argument as UTF-8. + + const buffer = Buffer.from(data) + + this.#bufferedAmount += buffer.byteLength + this.#sendQueue.add(buffer, () => { + this.#bufferedAmount -= buffer.byteLength + }, sendHints.text) + } else if (isArrayBuffer(data)) { + // If the WebSocket connection is established, and the WebSocket + // closing handshake has not yet started, then the user agent must + // send a WebSocket Message comprised of data using a binary frame + // opcode; if the data cannot be sent, e.g. because it would need + // to be buffered but the buffer is full, the user agent must flag + // the WebSocket as full and then close the WebSocket connection. + // The data to be sent is the data stored in the buffer described + // by the ArrayBuffer object. Any invocation of this method with an + // ArrayBuffer argument that does not throw an exception must + // increase the bufferedAmount attribute by the length of the + // ArrayBuffer in bytes. + + this.#bufferedAmount += data.byteLength + this.#sendQueue.add(data, () => { + this.#bufferedAmount -= data.byteLength + }, sendHints.arrayBuffer) + } else if (ArrayBuffer.isView(data)) { + // If the WebSocket connection is established, and the WebSocket + // closing handshake has not yet started, then the user agent must + // send a WebSocket Message comprised of data using a binary frame + // opcode; if the data cannot be sent, e.g. because it would need to + // be buffered but the buffer is full, the user agent must flag the + // WebSocket as full and then close the WebSocket connection. The + // data to be sent is the data stored in the section of the buffer + // described by the ArrayBuffer object that data references. Any + // invocation of this method with this kind of argument that does + // not throw an exception must increase the bufferedAmount attribute + // by the length of data’s buffer in bytes. + + this.#bufferedAmount += data.byteLength + this.#sendQueue.add(data, () => { + this.#bufferedAmount -= data.byteLength + }, sendHints.typedArray) + } else if (webidl.is.Blob(data)) { + // If the WebSocket connection is established, and the WebSocket + // closing handshake has not yet started, then the user agent must + // send a WebSocket Message comprised of data using a binary frame + // opcode; if the data cannot be sent, e.g. because it would need to + // be buffered but the buffer is full, the user agent must flag the + // WebSocket as full and then close the WebSocket connection. The data + // to be sent is the raw data represented by the Blob object. Any + // invocation of this method with a Blob argument that does not throw + // an exception must increase the bufferedAmount attribute by the size + // of the Blob object’s raw data, in bytes. + + this.#bufferedAmount += data.size + this.#sendQueue.add(data, () => { + this.#bufferedAmount -= data.size + }, sendHints.blob) + } + } + + get readyState () { + webidl.brandCheck(this, WebSocket) + + // The readyState getter steps are to return this's ready state. + return this.#handler.readyState + } + + get bufferedAmount () { + webidl.brandCheck(this, WebSocket) + + return this.#bufferedAmount + } + + get url () { + webidl.brandCheck(this, WebSocket) + + // The url getter steps are to return this's url, serialized. + return URLSerializer(this.#url) + } + + get extensions () { + webidl.brandCheck(this, WebSocket) + + return this.#extensions + } + + get protocol () { + webidl.brandCheck(this, WebSocket) + + return this.#protocol + } + + get onopen () { + webidl.brandCheck(this, WebSocket) + + return this.#events.open + } + + set onopen (fn) { + webidl.brandCheck(this, WebSocket) + + if (this.#events.open) { + this.removeEventListener('open', this.#events.open) + } + + if (typeof fn === 'function') { + this.#events.open = fn + this.addEventListener('open', fn) + } else { + this.#events.open = null + } + } + + get onerror () { + webidl.brandCheck(this, WebSocket) + + return this.#events.error + } + + set onerror (fn) { + webidl.brandCheck(this, WebSocket) + + if (this.#events.error) { + this.removeEventListener('error', this.#events.error) + } + + if (typeof fn === 'function') { + this.#events.error = fn + this.addEventListener('error', fn) + } else { + this.#events.error = null + } + } + + get onclose () { + webidl.brandCheck(this, WebSocket) + + return this.#events.close + } + + set onclose (fn) { + webidl.brandCheck(this, WebSocket) + + if (this.#events.close) { + this.removeEventListener('close', this.#events.close) + } + + if (typeof fn === 'function') { + this.#events.close = fn + this.addEventListener('close', fn) + } else { + this.#events.close = null + } + } + + get onmessage () { + webidl.brandCheck(this, WebSocket) + + return this.#events.message + } + + set onmessage (fn) { + webidl.brandCheck(this, WebSocket) + + if (this.#events.message) { + this.removeEventListener('message', this.#events.message) + } + + if (typeof fn === 'function') { + this.#events.message = fn + this.addEventListener('message', fn) + } else { + this.#events.message = null + } + } + + get binaryType () { + webidl.brandCheck(this, WebSocket) + + return this.#binaryType + } + + set binaryType (type) { + webidl.brandCheck(this, WebSocket) + + if (type !== 'blob' && type !== 'arraybuffer') { + this.#binaryType = 'blob' + } else { + this.#binaryType = type + } + } + + /** + * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol + */ + #onConnectionEstablished (response, parsedExtensions) { + // processResponse is called when the "response’s header list has been received and initialized." + // once this happens, the connection is open + this.#handler.socket = response.socket + + const parser = new ByteParser(this.#handler, parsedExtensions) + parser.on('drain', () => this.#handler.onParserDrain()) + parser.on('error', (err) => this.#handler.onParserError(err)) + + this.#parser = parser + this.#sendQueue = new SendQueue(response.socket) + + // 1. Change the ready state to OPEN (1). + this.#handler.readyState = states.OPEN + + // 2. Change the extensions attribute’s value to the extensions in use, if + // it is not the null value. + // https://datatracker.ietf.org/doc/html/rfc6455#section-9.1 + const extensions = response.headersList.get('sec-websocket-extensions') + + if (extensions !== null) { + this.#extensions = extensions + } + + // 3. Change the protocol attribute’s value to the subprotocol in use, if + // it is not the null value. + // https://datatracker.ietf.org/doc/html/rfc6455#section-1.9 + const protocol = response.headersList.get('sec-websocket-protocol') + + if (protocol !== null) { + this.#protocol = protocol + } + + // 4. Fire an event named open at the WebSocket object. + fireEvent('open', this) + + if (channels.open.hasSubscribers) { + // Convert headers to a plain object for the event + const headers = response.headersList.entries + channels.open.publish({ + address: response.socket.address(), + protocol: this.#protocol, + extensions: this.#extensions, + websocket: this, + handshakeResponse: { + status: response.status, + statusText: response.statusText, + headers + } + }) + } + } + + #onFail (code, reason, cause) { + if (reason) { + // TODO: process.nextTick + fireEvent('error', this, (type, init) => new ErrorEvent(type, init), { + error: new Error(reason, cause ? { cause } : undefined), + message: reason + }) + } + + if (!this.#handler.wasEverConnected) { + this.#handler.readyState = states.CLOSED + + // If the WebSocket connection could not be established, it is also said + // that _The WebSocket Connection is Closed_, but not _cleanly_. + fireEvent('close', this, (type, init) => new CloseEvent(type, init), { + wasClean: false, code, reason + }) + } + } + + #onMessage (type, data) { + // 1. If ready state is not OPEN (1), then return. + if (this.#handler.readyState !== states.OPEN) { + return + } + + // 2. Let dataForEvent be determined by switching on type and binary type: + let dataForEvent + + if (type === opcodes.TEXT) { + // -> type indicates that the data is Text + // a new DOMString containing data + try { + dataForEvent = utf8Decode(data) + } catch { + failWebsocketConnection(this.#handler, 1007, 'Received invalid UTF-8 in text frame.') + return + } + } else if (type === opcodes.BINARY) { + if (this.#binaryType === 'blob') { + // -> type indicates that the data is Binary and binary type is "blob" + // a new Blob object, created in the relevant Realm of the WebSocket + // object, that represents data as its raw data + dataForEvent = new Blob([data]) + } else { + // -> type indicates that the data is Binary and binary type is "arraybuffer" + // a new ArrayBuffer object, created in the relevant Realm of the + // WebSocket object, whose contents are data + dataForEvent = toArrayBuffer(data) + } + } + + // 3. Fire an event named message at the WebSocket object, using MessageEvent, + // with the origin attribute initialized to the serialization of the WebSocket + // object’s url's origin, and the data attribute initialized to dataForEvent. + fireEvent('message', this, createFastMessageEvent, { + origin: this.#url.origin, + data: dataForEvent + }) + } + + #onParserDrain () { + this.#handler.socket.resume() + } + + /** + * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol + * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4 + */ + #onSocketClose () { + // If the TCP connection was closed after the + // WebSocket closing handshake was completed, the WebSocket connection + // is said to have been closed _cleanly_. + const wasClean = + this.#handler.closeState.has(sentCloseFrameState.SENT) && + this.#handler.closeState.has(sentCloseFrameState.RECEIVED) + + let code = 1005 + let reason = '' + + const result = this.#parser.closingInfo + + if (result && !result.error) { + code = result.code ?? 1005 + reason = result.reason + } else if (!this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) { + // If _The WebSocket + // Connection is Closed_ and no Close control frame was received by the + // endpoint (such as could occur if the underlying transport connection + // is lost), _The WebSocket Connection Close Code_ is considered to be + // 1006. + code = 1006 + } + + // 1. Change the ready state to CLOSED (3). + this.#handler.readyState = states.CLOSED + + // 2. If the user agent was required to fail the WebSocket + // connection, or if the WebSocket connection was closed + // after being flagged as full, fire an event named error + // at the WebSocket object. + // TODO + + // 3. Fire an event named close at the WebSocket object, + // using CloseEvent, with the wasClean attribute + // initialized to true if the connection closed cleanly + // and false otherwise, the code attribute initialized to + // the WebSocket connection close code, and the reason + // attribute initialized to the result of applying UTF-8 + // decode without BOM to the WebSocket connection close + // reason. + // TODO: process.nextTick + fireEvent('close', this, (type, init) => new CloseEvent(type, init), { + wasClean, code, reason + }) + + if (channels.close.hasSubscribers) { + channels.close.publish({ + websocket: this, + code, + reason + }) + } + } + + /** + * @param {WebSocket} ws + * @param {Buffer|undefined} buffer + */ + static ping (ws, buffer) { + if (Buffer.isBuffer(buffer)) { + if (buffer.length > 125) { + throw new TypeError('A PING frame cannot have a body larger than 125 bytes.') + } + } else if (buffer !== undefined) { + throw new TypeError('Expected buffer payload') + } + + // An endpoint MAY send a Ping frame any time after the connection is + // established and before the connection is closed. + const readyState = ws.#handler.readyState + + if (isEstablished(readyState) && !isClosing(readyState) && !isClosed(readyState)) { + const frame = new WebsocketFrameSend(buffer) + ws.#handler.socket.write(frame.createFrame(opcodes.PING)) + } + } +} + +const { ping } = WebSocket +Reflect.deleteProperty(WebSocket, 'ping') + +// https://websockets.spec.whatwg.org/#dom-websocket-connecting +WebSocket.CONNECTING = WebSocket.prototype.CONNECTING = states.CONNECTING +// https://websockets.spec.whatwg.org/#dom-websocket-open +WebSocket.OPEN = WebSocket.prototype.OPEN = states.OPEN +// https://websockets.spec.whatwg.org/#dom-websocket-closing +WebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING +// https://websockets.spec.whatwg.org/#dom-websocket-closed +WebSocket.CLOSED = WebSocket.prototype.CLOSED = states.CLOSED + +Object.defineProperties(WebSocket.prototype, { + CONNECTING: staticPropertyDescriptors, + OPEN: staticPropertyDescriptors, + CLOSING: staticPropertyDescriptors, + CLOSED: staticPropertyDescriptors, + url: kEnumerableProperty, + readyState: kEnumerableProperty, + bufferedAmount: kEnumerableProperty, + onopen: kEnumerableProperty, + onerror: kEnumerableProperty, + onclose: kEnumerableProperty, + close: kEnumerableProperty, + onmessage: kEnumerableProperty, + binaryType: kEnumerableProperty, + send: kEnumerableProperty, + extensions: kEnumerableProperty, + protocol: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'WebSocket', + writable: false, + enumerable: false, + configurable: true + } +}) + +Object.defineProperties(WebSocket, { + CONNECTING: staticPropertyDescriptors, + OPEN: staticPropertyDescriptors, + CLOSING: staticPropertyDescriptors, + CLOSED: staticPropertyDescriptors +}) + +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.DOMString +) + +webidl.converters['DOMString or sequence'] = function (V, prefix, argument) { + if (webidl.util.Type(V) === webidl.util.Types.OBJECT && Symbol.iterator in V) { + return webidl.converters['sequence'](V) + } + + return webidl.converters.DOMString(V, prefix, argument) +} + +// This implements the proposal made in https://github.com/whatwg/websockets/issues/42 +webidl.converters.WebSocketInit = webidl.dictionaryConverter([ + { + key: 'protocols', + converter: webidl.converters['DOMString or sequence'], + defaultValue: () => new Array(0) + }, + { + key: 'dispatcher', + converter: webidl.converters.any, + defaultValue: () => getGlobalDispatcher() + }, + { + key: 'headers', + converter: webidl.nullableConverter(webidl.converters.HeadersInit) + } +]) + +webidl.converters['DOMString or sequence or WebSocketInit'] = function (V) { + if (webidl.util.Type(V) === webidl.util.Types.OBJECT && !(Symbol.iterator in V)) { + return webidl.converters.WebSocketInit(V) + } + + return { protocols: webidl.converters['DOMString or sequence'](V) } +} + +webidl.converters.WebSocketSendData = function (V) { + if (webidl.util.Type(V) === webidl.util.Types.OBJECT) { + if (webidl.is.Blob(V)) { + return V + } + + if (ArrayBuffer.isView(V) || isArrayBuffer(V)) { + return V + } + } + + return webidl.converters.USVString(V) +} + +module.exports = { + WebSocket, + ping +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/scripts/strip-comments.js b/novas/novacore-zephyr/claude-code-router/node_modules/undici/scripts/strip-comments.js new file mode 100644 index 0000000000000000000000000000000000000000..d687a268090311c938b3e9455ab818e200f1535d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/scripts/strip-comments.js @@ -0,0 +1,10 @@ +'use strict' + +const { readFileSync, writeFileSync } = require('node:fs') +const { transcode } = require('node:buffer') + +const buffer = transcode + ? transcode(readFileSync('./undici-fetch.js'), 'utf8', 'latin1') + : readFileSync('./undici-fetch.js') + +writeFileSync('./undici-fetch.js', buffer.toString('latin1')) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/README.md b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/README.md new file mode 100644 index 0000000000000000000000000000000000000000..20a721c445a21b60d9d3a20d142da608bffd7d9b --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/README.md @@ -0,0 +1,6 @@ +# undici-types + +This package is a dual-publish of the [undici](https://www.npmjs.com/package/undici) library types. The `undici` package **still contains types**. This package is for users who _only_ need undici types (such as for `@types/node`). It is published alongside every release of `undici`, so you can always use the same version. + +- [GitHub nodejs/undici](https://github.com/nodejs/undici) +- [Undici Documentation](https://undici.nodejs.org/#/) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/agent.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/agent.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8c881481a46bf6ca0b4d1bc290010fef75fc055b --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/agent.d.ts @@ -0,0 +1,31 @@ +import { URL } from 'url' +import Pool from './pool' +import Dispatcher from './dispatcher' +import TClientStats from './client-stats' +import TPoolStats from './pool-stats' + +export default Agent + +declare class Agent extends Dispatcher { + constructor (opts?: Agent.Options) + /** `true` after `dispatcher.close()` has been called. */ + closed: boolean + /** `true` after `dispatcher.destroyed()` has been called or `dispatcher.close()` has been called and the dispatcher shutdown has completed. */ + destroyed: boolean + /** Dispatches a request. */ + dispatch (options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandler): boolean + /** Aggregate stats for a Agent by origin. */ + readonly stats: Record +} + +declare namespace Agent { + export interface Options extends Pool.Options { + /** Default: `(origin, opts) => new Pool(origin, opts)`. */ + factory?(origin: string | URL, opts: Object): Dispatcher; + + interceptors?: { Agent?: readonly Dispatcher.DispatchInterceptor[] } & Pool.Options['interceptors'] + } + + export interface DispatchOptions extends Dispatcher.DispatchOptions { + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/api.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/api.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e58d08f61ccd846ae9bcc90a822ceb4193e2d993 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/api.d.ts @@ -0,0 +1,43 @@ +import { URL, UrlObject } from 'url' +import { Duplex } from 'stream' +import Dispatcher from './dispatcher' + +/** Performs an HTTP request. */ +declare function request ( + url: string | URL | UrlObject, + options?: { dispatcher?: Dispatcher } & Omit, 'origin' | 'path' | 'method'> & Partial>, +): Promise> + +/** A faster version of `request`. */ +declare function stream ( + url: string | URL | UrlObject, + options: { dispatcher?: Dispatcher } & Omit, 'origin' | 'path'>, + factory: Dispatcher.StreamFactory +): Promise> + +/** For easy use with `stream.pipeline`. */ +declare function pipeline ( + url: string | URL | UrlObject, + options: { dispatcher?: Dispatcher } & Omit, 'origin' | 'path'>, + handler: Dispatcher.PipelineHandler +): Duplex + +/** Starts two-way communications with the requested resource. */ +declare function connect ( + url: string | URL | UrlObject, + options?: { dispatcher?: Dispatcher } & Omit, 'origin' | 'path'> +): Promise> + +/** Upgrade to a different protocol. */ +declare function upgrade ( + url: string | URL | UrlObject, + options?: { dispatcher?: Dispatcher } & Omit +): Promise + +export { + request, + stream, + pipeline, + connect, + upgrade +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/balanced-pool.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/balanced-pool.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..733239c0bf035742463cb15369d9d970d749a2e1 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/balanced-pool.d.ts @@ -0,0 +1,29 @@ +import Pool from './pool' +import Dispatcher from './dispatcher' +import { URL } from 'url' + +export default BalancedPool + +type BalancedPoolConnectOptions = Omit + +declare class BalancedPool extends Dispatcher { + constructor (url: string | string[] | URL | URL[], options?: Pool.Options) + + addUpstream (upstream: string | URL): BalancedPool + removeUpstream (upstream: string | URL): BalancedPool + upstreams: Array + + /** `true` after `pool.close()` has been called. */ + closed: boolean + /** `true` after `pool.destroyed()` has been called or `pool.close()` has been called and the pool shutdown has completed. */ + destroyed: boolean + + // Override dispatcher APIs. + override connect ( + options: BalancedPoolConnectOptions + ): Promise + override connect ( + options: BalancedPoolConnectOptions, + callback: (err: Error | null, data: Dispatcher.ConnectData) => void + ): void +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/cache-interceptor.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/cache-interceptor.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e53be60a611ab24f417f5bb69a957ba3d69e6999 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/cache-interceptor.d.ts @@ -0,0 +1,172 @@ +import { Readable, Writable } from 'node:stream' + +export default CacheHandler + +declare namespace CacheHandler { + export type CacheMethods = 'GET' | 'HEAD' | 'OPTIONS' | 'TRACE' + + export interface CacheHandlerOptions { + store: CacheStore + + cacheByDefault?: number + + type?: CacheOptions['type'] + } + + export interface CacheOptions { + store?: CacheStore + + /** + * The methods to cache + * Note we can only cache safe methods. Unsafe methods (i.e. PUT, POST) + * invalidate the cache for a origin. + * @see https://www.rfc-editor.org/rfc/rfc9111.html#name-invalidating-stored-respons + * @see https://www.rfc-editor.org/rfc/rfc9110#section-9.2.1 + */ + methods?: CacheMethods[] + + /** + * RFC9111 allows for caching responses that we aren't explicitly told to + * cache or to not cache. + * @see https://www.rfc-editor.org/rfc/rfc9111.html#section-3-5 + * @default undefined + */ + cacheByDefault?: number + + /** + * TODO docs + * @default 'shared' + */ + type?: 'shared' | 'private' + } + + export interface CacheControlDirectives { + 'max-stale'?: number; + 'min-fresh'?: number; + 'max-age'?: number; + 's-maxage'?: number; + 'stale-while-revalidate'?: number; + 'stale-if-error'?: number; + public?: true; + private?: true | string[]; + 'no-store'?: true; + 'no-cache'?: true | string[]; + 'must-revalidate'?: true; + 'proxy-revalidate'?: true; + immutable?: true; + 'no-transform'?: true; + 'must-understand'?: true; + 'only-if-cached'?: true; + } + + export interface CacheKey { + origin: string + method: string + path: string + headers?: Record + } + + export interface CacheValue { + statusCode: number + statusMessage: string + headers: Record + vary?: Record + etag?: string + cacheControlDirectives?: CacheControlDirectives + cachedAt: number + staleAt: number + deleteAt: number + } + + export interface DeleteByUri { + origin: string + method: string + path: string + } + + type GetResult = { + statusCode: number + statusMessage: string + headers: Record + vary?: Record + etag?: string + body?: Readable | Iterable | AsyncIterable | Buffer | Iterable | AsyncIterable | string + cacheControlDirectives: CacheControlDirectives, + cachedAt: number + staleAt: number + deleteAt: number + } + + /** + * Underlying storage provider for cached responses + */ + export interface CacheStore { + get(key: CacheKey): GetResult | Promise | undefined + + createWriteStream(key: CacheKey, val: CacheValue): Writable | undefined + + delete(key: CacheKey): void | Promise + } + + export interface MemoryCacheStoreOpts { + /** + * @default Infinity + */ + maxCount?: number + + /** + * @default Infinity + */ + maxSize?: number + + /** + * @default Infinity + */ + maxEntrySize?: number + + errorCallback?: (err: Error) => void + } + + export class MemoryCacheStore implements CacheStore { + constructor (opts?: MemoryCacheStoreOpts) + + get (key: CacheKey): GetResult | Promise | undefined + + createWriteStream (key: CacheKey, value: CacheValue): Writable | undefined + + delete (key: CacheKey): void | Promise + } + + export interface SqliteCacheStoreOpts { + /** + * Location of the database + * @default ':memory:' + */ + location?: string + + /** + * @default Infinity + */ + maxCount?: number + + /** + * @default Infinity + */ + maxEntrySize?: number + } + + export class SqliteCacheStore implements CacheStore { + constructor (opts?: SqliteCacheStoreOpts) + + /** + * Closes the connection to the database + */ + close (): void + + get (key: CacheKey): GetResult | Promise | undefined + + createWriteStream (key: CacheKey, value: CacheValue): Writable | undefined + + delete (key: CacheKey): void | Promise + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/cache.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/cache.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4c33335766667761460cc464303e80efe0c6eb10 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/cache.d.ts @@ -0,0 +1,36 @@ +import type { RequestInfo, Response, Request } from './fetch' + +export interface CacheStorage { + match (request: RequestInfo, options?: MultiCacheQueryOptions): Promise, + has (cacheName: string): Promise, + open (cacheName: string): Promise, + delete (cacheName: string): Promise, + keys (): Promise +} + +declare const CacheStorage: { + prototype: CacheStorage + new(): CacheStorage +} + +export interface Cache { + match (request: RequestInfo, options?: CacheQueryOptions): Promise, + matchAll (request?: RequestInfo, options?: CacheQueryOptions): Promise, + add (request: RequestInfo): Promise, + addAll (requests: RequestInfo[]): Promise, + put (request: RequestInfo, response: Response): Promise, + delete (request: RequestInfo, options?: CacheQueryOptions): Promise, + keys (request?: RequestInfo, options?: CacheQueryOptions): Promise +} + +export interface CacheQueryOptions { + ignoreSearch?: boolean, + ignoreMethod?: boolean, + ignoreVary?: boolean +} + +export interface MultiCacheQueryOptions extends CacheQueryOptions { + cacheName?: string +} + +export declare const caches: CacheStorage diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/client-stats.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/client-stats.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ad9bd8482dffba3d6888210b16244c50d179246a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/client-stats.d.ts @@ -0,0 +1,15 @@ +import Client from './client' + +export default ClientStats + +declare class ClientStats { + constructor (pool: Client) + /** If socket has open connection. */ + connected: boolean + /** Number of open socket connections in this client that do not have an active request. */ + pending: number + /** Number of currently active requests of this client. */ + running: number + /** Number of active, pending, or queued requests of this client. */ + size: number +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/client.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/client.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bd1a32c380aa1ef2d3d7c24381a55bb76f772947 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/client.d.ts @@ -0,0 +1,108 @@ +import { URL } from 'url' +import Dispatcher from './dispatcher' +import buildConnector from './connector' +import TClientStats from './client-stats' + +type ClientConnectOptions = Omit + +/** + * A basic HTTP/1.1 client, mapped on top a single TCP/TLS connection. Pipelining is disabled by default. + */ +export class Client extends Dispatcher { + constructor (url: string | URL, options?: Client.Options) + /** Property to get and set the pipelining factor. */ + pipelining: number + /** `true` after `client.close()` has been called. */ + closed: boolean + /** `true` after `client.destroyed()` has been called or `client.close()` has been called and the client shutdown has completed. */ + destroyed: boolean + /** Aggregate stats for a Client. */ + readonly stats: TClientStats + + // Override dispatcher APIs. + override connect ( + options: ClientConnectOptions + ): Promise + override connect ( + options: ClientConnectOptions, + callback: (err: Error | null, data: Dispatcher.ConnectData) => void + ): void +} + +export declare namespace Client { + export interface OptionsInterceptors { + Client: readonly Dispatcher.DispatchInterceptor[]; + } + export interface Options { + /** TODO */ + interceptors?: OptionsInterceptors; + /** The maximum length of request headers in bytes. Default: Node.js' `--max-http-header-size` or `16384` (16KiB). */ + maxHeaderSize?: number; + /** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers (Node 14 and above only). Default: `300e3` milliseconds (300s). */ + headersTimeout?: number; + /** @deprecated unsupported socketTimeout, use headersTimeout & bodyTimeout instead */ + socketTimeout?: never; + /** @deprecated unsupported requestTimeout, use headersTimeout & bodyTimeout instead */ + requestTimeout?: never; + /** TODO */ + connectTimeout?: number; + /** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Default: `300e3` milliseconds (300s). */ + bodyTimeout?: number; + /** @deprecated unsupported idleTimeout, use keepAliveTimeout instead */ + idleTimeout?: never; + /** @deprecated unsupported keepAlive, use pipelining=0 instead */ + keepAlive?: never; + /** the timeout, in milliseconds, after which a socket without active requests will time out. Monitors time between activity on a connected socket. This value may be overridden by *keep-alive* hints from the server. Default: `4e3` milliseconds (4s). */ + keepAliveTimeout?: number; + /** @deprecated unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead */ + maxKeepAliveTimeout?: never; + /** the maximum allowed `idleTimeout`, in milliseconds, when overridden by *keep-alive* hints from the server. Default: `600e3` milliseconds (10min). */ + keepAliveMaxTimeout?: number; + /** A number of milliseconds subtracted from server *keep-alive* hints when overriding `idleTimeout` to account for timing inaccuracies caused by e.g. transport latency. Default: `1e3` milliseconds (1s). */ + keepAliveTimeoutThreshold?: number; + /** TODO */ + socketPath?: string; + /** The amount of concurrent requests to be sent over the single TCP/TLS connection according to [RFC7230](https://tools.ietf.org/html/rfc7230#section-6.3.2). Default: `1`. */ + pipelining?: number; + /** @deprecated use the connect option instead */ + tls?: never; + /** If `true`, an error is thrown when the request content-length header doesn't match the length of the request body. Default: `true`. */ + strictContentLength?: boolean; + /** TODO */ + maxCachedSessions?: number; + /** TODO */ + connect?: Partial | buildConnector.connector; + /** TODO */ + maxRequestsPerClient?: number; + /** TODO */ + localAddress?: string; + /** Max response body size in bytes, -1 is disabled */ + maxResponseSize?: number; + /** Enables a family autodetection algorithm that loosely implements section 5 of RFC 8305. */ + autoSelectFamily?: boolean; + /** The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option. */ + autoSelectFamilyAttemptTimeout?: number; + /** + * @description Enables support for H2 if the server has assigned bigger priority to it through ALPN negotiation. + * @default false + */ + allowH2?: boolean; + /** + * @description Dictates the maximum number of concurrent streams for a single H2 session. It can be overridden by a SETTINGS remote frame. + * @default 100 + */ + maxConcurrentStreams?: number; + } + export interface SocketInfo { + localAddress?: string + localPort?: number + remoteAddress?: string + remotePort?: number + remoteFamily?: string + timeout?: number + bytesWritten?: number + bytesRead?: number + } +} + +export default Client diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/connector.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/connector.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bd924339eb3986d17544bd1905c8856e25396e27 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/connector.d.ts @@ -0,0 +1,34 @@ +import { TLSSocket, ConnectionOptions } from 'tls' +import { IpcNetConnectOpts, Socket, TcpNetConnectOpts } from 'net' + +export default buildConnector +declare function buildConnector (options?: buildConnector.BuildOptions): buildConnector.connector + +declare namespace buildConnector { + export type BuildOptions = (ConnectionOptions | TcpNetConnectOpts | IpcNetConnectOpts) & { + allowH2?: boolean; + maxCachedSessions?: number | null; + socketPath?: string | null; + timeout?: number | null; + port?: number; + keepAlive?: boolean | null; + keepAliveInitialDelay?: number | null; + } + + export interface Options { + hostname: string + host?: string + protocol: string + port: string + servername?: string + localAddress?: string | null + httpSocket?: Socket + } + + export type Callback = (...args: CallbackArgs) => void + type CallbackArgs = [null, Socket | TLSSocket] | [Error, null] + + export interface connector { + (options: buildConnector.Options, callback: buildConnector.Callback): void + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/content-type.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/content-type.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f2a87f1b7518f72d94894b21fbfe96b7d0264ab3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/content-type.d.ts @@ -0,0 +1,21 @@ +/// + +interface MIMEType { + type: string + subtype: string + parameters: Map + essence: string +} + +/** + * Parse a string to a {@link MIMEType} object. Returns `failure` if the string + * couldn't be parsed. + * @see https://mimesniff.spec.whatwg.org/#parse-a-mime-type + */ +export function parseMIMEType (input: string): 'failure' | MIMEType + +/** + * Convert a MIMEType object to a string. + * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type + */ +export function serializeAMimeType (mimeType: MIMEType): string diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/cookies.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/cookies.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f746d35853fe5a5a0894e69a1e9d42c57ef2a657 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/cookies.d.ts @@ -0,0 +1,30 @@ +/// + +import type { Headers } from './fetch' + +export interface Cookie { + name: string + value: string + expires?: Date | number + maxAge?: number + domain?: string + path?: string + secure?: boolean + httpOnly?: boolean + sameSite?: 'Strict' | 'Lax' | 'None' + unparsed?: string[] +} + +export function deleteCookie ( + headers: Headers, + name: string, + attributes?: { name?: string, domain?: string } +): void + +export function getCookies (headers: Headers): Record + +export function getSetCookies (headers: Headers): Cookie[] + +export function setCookie (headers: Headers, cookie: Cookie): void + +export function parseCookie (cookie: string): Cookie | null diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/diagnostics-channel.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/diagnostics-channel.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4925c871d70e882f8209b28da2f1b2deb46ad002 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/diagnostics-channel.d.ts @@ -0,0 +1,74 @@ +import { Socket } from 'net' +import { URL } from 'url' +import buildConnector from './connector' +import Dispatcher from './dispatcher' + +declare namespace DiagnosticsChannel { + interface Request { + origin?: string | URL; + completed: boolean; + method?: Dispatcher.HttpMethod; + path: string; + headers: any; + } + interface Response { + statusCode: number; + statusText: string; + headers: Array; + } + interface ConnectParams { + host: URL['host']; + hostname: URL['hostname']; + protocol: URL['protocol']; + port: URL['port']; + servername: string | null; + } + type Connector = buildConnector.connector + export interface RequestCreateMessage { + request: Request; + } + export interface RequestBodySentMessage { + request: Request; + } + + export interface RequestBodyChunkSentMessage { + request: Request; + chunk: Uint8Array | string; + } + export interface RequestBodyChunkReceivedMessage { + request: Request; + chunk: Buffer; + } + export interface RequestHeadersMessage { + request: Request; + response: Response; + } + export interface RequestTrailersMessage { + request: Request; + trailers: Array; + } + export interface RequestErrorMessage { + request: Request; + error: Error; + } + export interface ClientSendHeadersMessage { + request: Request; + headers: string; + socket: Socket; + } + export interface ClientBeforeConnectMessage { + connectParams: ConnectParams; + connector: Connector; + } + export interface ClientConnectedMessage { + socket: Socket; + connectParams: ConnectParams; + connector: Connector; + } + export interface ClientConnectErrorMessage { + error: Error; + socket: Socket; + connectParams: ConnectParams; + connector: Connector; + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/dispatcher.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/dispatcher.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fffe870c272a787f01e9fcbf78e87a3fdbd906ce --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/dispatcher.d.ts @@ -0,0 +1,276 @@ +import { URL } from 'url' +import { Duplex, Readable, Writable } from 'stream' +import { EventEmitter } from 'events' +import { Blob } from 'buffer' +import { IncomingHttpHeaders } from './header' +import BodyReadable from './readable' +import { FormData } from './formdata' +import Errors from './errors' +import { Autocomplete } from './utility' + +type AbortSignal = unknown + +export default Dispatcher + +export type UndiciHeaders = Record | IncomingHttpHeaders | string[] | Iterable<[string, string | string[] | undefined]> | null + +/** Dispatcher is the core API used to dispatch requests. */ +declare class Dispatcher extends EventEmitter { + /** Dispatches a request. This API is expected to evolve through semver-major versions and is less stable than the preceding higher level APIs. It is primarily intended for library developers who implement higher level APIs on top of this. */ + dispatch (options: Dispatcher.DispatchOptions, handler: Dispatcher.DispatchHandler): boolean + /** Starts two-way communications with the requested resource. */ + connect(options: Dispatcher.ConnectOptions): Promise> + connect(options: Dispatcher.ConnectOptions, callback: (err: Error | null, data: Dispatcher.ConnectData) => void): void + /** Compose a chain of dispatchers */ + compose (dispatchers: Dispatcher.DispatcherComposeInterceptor[]): Dispatcher.ComposedDispatcher + compose (...dispatchers: Dispatcher.DispatcherComposeInterceptor[]): Dispatcher.ComposedDispatcher + /** Performs an HTTP request. */ + request(options: Dispatcher.RequestOptions): Promise> + request(options: Dispatcher.RequestOptions, callback: (err: Error | null, data: Dispatcher.ResponseData) => void): void + /** For easy use with `stream.pipeline`. */ + pipeline(options: Dispatcher.PipelineOptions, handler: Dispatcher.PipelineHandler): Duplex + /** A faster version of `Dispatcher.request`. */ + stream(options: Dispatcher.RequestOptions, factory: Dispatcher.StreamFactory): Promise> + stream(options: Dispatcher.RequestOptions, factory: Dispatcher.StreamFactory, callback: (err: Error | null, data: Dispatcher.StreamData) => void): void + /** Upgrade to a different protocol. */ + upgrade (options: Dispatcher.UpgradeOptions): Promise + upgrade (options: Dispatcher.UpgradeOptions, callback: (err: Error | null, data: Dispatcher.UpgradeData) => void): void + /** Closes the client and gracefully waits for enqueued requests to complete before invoking the callback (or returning a promise if no callback is provided). */ + close (): Promise + close (callback: () => void): void + /** Destroy the client abruptly with the given err. All the pending and running requests will be asynchronously aborted and error. Waits until socket is closed before invoking the callback (or returning a promise if no callback is provided). Since this operation is asynchronously dispatched there might still be some progress on dispatched requests. */ + destroy (): Promise + destroy (err: Error | null): Promise + destroy (callback: () => void): void + destroy (err: Error | null, callback: () => void): void + + on (eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this + on (eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + on (eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + on (eventName: 'drain', callback: (origin: URL) => void): this + + once (eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this + once (eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + once (eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + once (eventName: 'drain', callback: (origin: URL) => void): this + + off (eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this + off (eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + off (eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + off (eventName: 'drain', callback: (origin: URL) => void): this + + addListener (eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this + addListener (eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + addListener (eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + addListener (eventName: 'drain', callback: (origin: URL) => void): this + + removeListener (eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this + removeListener (eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + removeListener (eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + removeListener (eventName: 'drain', callback: (origin: URL) => void): this + + prependListener (eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this + prependListener (eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + prependListener (eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + prependListener (eventName: 'drain', callback: (origin: URL) => void): this + + prependOnceListener (eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this + prependOnceListener (eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + prependOnceListener (eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this + prependOnceListener (eventName: 'drain', callback: (origin: URL) => void): this + + listeners (eventName: 'connect'): ((origin: URL, targets: readonly Dispatcher[]) => void)[] + listeners (eventName: 'disconnect'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[] + listeners (eventName: 'connectionError'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[] + listeners (eventName: 'drain'): ((origin: URL) => void)[] + + rawListeners (eventName: 'connect'): ((origin: URL, targets: readonly Dispatcher[]) => void)[] + rawListeners (eventName: 'disconnect'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[] + rawListeners (eventName: 'connectionError'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[] + rawListeners (eventName: 'drain'): ((origin: URL) => void)[] + + emit (eventName: 'connect', origin: URL, targets: readonly Dispatcher[]): boolean + emit (eventName: 'disconnect', origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError): boolean + emit (eventName: 'connectionError', origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError): boolean + emit (eventName: 'drain', origin: URL): boolean +} + +declare namespace Dispatcher { + export interface ComposedDispatcher extends Dispatcher {} + export type Dispatch = Dispatcher['dispatch'] + export type DispatcherComposeInterceptor = (dispatch: Dispatch) => Dispatch + export interface DispatchOptions { + origin?: string | URL; + path: string; + method: HttpMethod; + /** Default: `null` */ + body?: string | Buffer | Uint8Array | Readable | null | FormData; + /** Default: `null` */ + headers?: UndiciHeaders; + /** Query string params to be embedded in the request URL. Default: `null` */ + query?: Record; + /** Whether the requests can be safely retried or not. If `false` the request won't be sent until all preceding requests in the pipeline have completed. Default: `true` if `method` is `HEAD` or `GET`. */ + idempotent?: boolean; + /** Whether the response is expected to take a long time and would end up blocking the pipeline. When this is set to `true` further pipelining will be avoided on the same connection until headers have been received. Defaults to `method !== 'HEAD'`. */ + blocking?: boolean; + /** Upgrade the request. Should be used to specify the kind of upgrade i.e. `'Websocket'`. Default: `method === 'CONNECT' || null`. */ + upgrade?: boolean | string | null; + /** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers. Defaults to 300 seconds. */ + headersTimeout?: number | null; + /** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use 0 to disable it entirely. Defaults to 300 seconds. */ + bodyTimeout?: number | null; + /** Whether the request should stablish a keep-alive or not. Default `false` */ + reset?: boolean; + /** Whether Undici should throw an error upon receiving a 4xx or 5xx response from the server. Defaults to false */ + throwOnError?: boolean; + /** For H2, it appends the expect: 100-continue header, and halts the request body until a 100-continue is received from the remote server */ + expectContinue?: boolean; + } + export interface ConnectOptions { + origin: string | URL; + path: string; + /** Default: `null` */ + headers?: UndiciHeaders; + /** Default: `null` */ + signal?: AbortSignal | EventEmitter | null; + /** This argument parameter is passed through to `ConnectData` */ + opaque?: TOpaque; + /** Default: false */ + redirectionLimitReached?: boolean; + /** Default: `null` */ + responseHeaders?: 'raw' | null; + } + export interface RequestOptions extends DispatchOptions { + /** Default: `null` */ + opaque?: TOpaque; + /** Default: `null` */ + signal?: AbortSignal | EventEmitter | null; + /** Default: false */ + redirectionLimitReached?: boolean; + /** Default: `null` */ + onInfo?: (info: { statusCode: number, headers: Record }) => void; + /** Default: `null` */ + responseHeaders?: 'raw' | null; + /** Default: `64 KiB` */ + highWaterMark?: number; + } + export interface PipelineOptions extends RequestOptions { + /** `true` if the `handler` will return an object stream. Default: `false` */ + objectMode?: boolean; + } + export interface UpgradeOptions { + path: string; + /** Default: `'GET'` */ + method?: string; + /** Default: `null` */ + headers?: UndiciHeaders; + /** A string of comma separated protocols, in descending preference order. Default: `'Websocket'` */ + protocol?: string; + /** Default: `null` */ + signal?: AbortSignal | EventEmitter | null; + /** Default: false */ + redirectionLimitReached?: boolean; + /** Default: `null` */ + responseHeaders?: 'raw' | null; + } + export interface ConnectData { + statusCode: number; + headers: IncomingHttpHeaders; + socket: Duplex; + opaque: TOpaque; + } + export interface ResponseData { + statusCode: number; + headers: IncomingHttpHeaders; + body: BodyReadable & BodyMixin; + trailers: Record; + opaque: TOpaque; + context: object; + } + export interface PipelineHandlerData { + statusCode: number; + headers: IncomingHttpHeaders; + opaque: TOpaque; + body: BodyReadable; + context: object; + } + export interface StreamData { + opaque: TOpaque; + trailers: Record; + } + export interface UpgradeData { + headers: IncomingHttpHeaders; + socket: Duplex; + opaque: TOpaque; + } + export interface StreamFactoryData { + statusCode: number; + headers: IncomingHttpHeaders; + opaque: TOpaque; + context: object; + } + export type StreamFactory = (data: StreamFactoryData) => Writable + + export interface DispatchController { + get aborted () : boolean + get paused () : boolean + get reason () : Error | null + abort (reason: Error): void + pause(): void + resume(): void + } + + export interface DispatchHandler { + onRequestStart?(controller: DispatchController, context: any): void; + onRequestUpgrade?(controller: DispatchController, statusCode: number, headers: IncomingHttpHeaders, socket: Duplex): void; + onResponseStart?(controller: DispatchController, statusCode: number, headers: IncomingHttpHeaders, statusMessage?: string): void; + onResponseData?(controller: DispatchController, chunk: Buffer): void; + onResponseEnd?(controller: DispatchController, trailers: IncomingHttpHeaders): void; + onResponseError?(controller: DispatchController, error: Error): void; + + /** Invoked before request is dispatched on socket. May be invoked multiple times when a request is retried when the request at the head of the pipeline fails. */ + /** @deprecated */ + onConnect?(abort: (err?: Error) => void): void; + /** Invoked when an error has occurred. */ + /** @deprecated */ + onError?(err: Error): void; + /** Invoked when request is upgraded either due to a `Upgrade` header or `CONNECT` method. */ + /** @deprecated */ + onUpgrade?(statusCode: number, headers: Buffer[] | string[] | null, socket: Duplex): void; + /** Invoked when response is received, before headers have been read. **/ + /** @deprecated */ + onResponseStarted?(): void; + /** Invoked when statusCode and headers have been received. May be invoked multiple times due to 1xx informational headers. */ + /** @deprecated */ + onHeaders?(statusCode: number, headers: Buffer[], resume: () => void, statusText: string): boolean; + /** Invoked when response payload data is received. */ + /** @deprecated */ + onData?(chunk: Buffer): boolean; + /** Invoked when response payload and trailers have been received and the request has completed. */ + /** @deprecated */ + onComplete?(trailers: string[] | null): void; + /** Invoked when a body chunk is sent to the server. May be invoked multiple times for chunked requests */ + /** @deprecated */ + onBodySent?(chunkSize: number, totalBytesSent: number): void; + } + export type PipelineHandler = (data: PipelineHandlerData) => Readable + export type HttpMethod = Autocomplete<'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'OPTIONS' | 'TRACE' | 'PATCH'> + + /** + * @link https://fetch.spec.whatwg.org/#body-mixin + */ + interface BodyMixin { + readonly body?: never; + readonly bodyUsed: boolean; + arrayBuffer(): Promise; + blob(): Promise; + bytes(): Promise; + formData(): Promise; + json(): Promise; + text(): Promise; + } + + export interface DispatchInterceptor { + (dispatch: Dispatch): Dispatch + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/env-http-proxy-agent.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/env-http-proxy-agent.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1733d7f6e32ab15b16fc81fc2018e5f5e2c2b84e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/env-http-proxy-agent.d.ts @@ -0,0 +1,22 @@ +import Agent from './agent' +import ProxyAgent from './proxy-agent' +import Dispatcher from './dispatcher' + +export default EnvHttpProxyAgent + +declare class EnvHttpProxyAgent extends Dispatcher { + constructor (opts?: EnvHttpProxyAgent.Options) + + dispatch (options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandler): boolean +} + +declare namespace EnvHttpProxyAgent { + export interface Options extends Omit { + /** Overrides the value of the HTTP_PROXY environment variable */ + httpProxy?: string; + /** Overrides the value of the HTTPS_PROXY environment variable */ + httpsProxy?: string; + /** Overrides the value of the NO_PROXY environment variable */ + noProxy?: string; + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/errors.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/errors.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..387420db040bd602cf755521cb476072f92af92d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/errors.d.ts @@ -0,0 +1,171 @@ +import { IncomingHttpHeaders } from './header' +import Client from './client' + +export default Errors + +declare namespace Errors { + export class UndiciError extends Error { + name: string + code: string + } + + /** Connect timeout error. */ + export class ConnectTimeoutError extends UndiciError { + name: 'ConnectTimeoutError' + code: 'UND_ERR_CONNECT_TIMEOUT' + } + + /** A header exceeds the `headersTimeout` option. */ + export class HeadersTimeoutError extends UndiciError { + name: 'HeadersTimeoutError' + code: 'UND_ERR_HEADERS_TIMEOUT' + } + + /** Headers overflow error. */ + export class HeadersOverflowError extends UndiciError { + name: 'HeadersOverflowError' + code: 'UND_ERR_HEADERS_OVERFLOW' + } + + /** A body exceeds the `bodyTimeout` option. */ + export class BodyTimeoutError extends UndiciError { + name: 'BodyTimeoutError' + code: 'UND_ERR_BODY_TIMEOUT' + } + + export class ResponseError extends UndiciError { + constructor ( + message: string, + code: number, + options: { + headers?: IncomingHttpHeaders | string[] | null, + body?: null | Record | string + } + ) + name: 'ResponseError' + code: 'UND_ERR_RESPONSE' + statusCode: number + body: null | Record | string + headers: IncomingHttpHeaders | string[] | null + } + + export class ResponseStatusCodeError extends UndiciError { + constructor ( + message?: string, + statusCode?: number, + headers?: IncomingHttpHeaders | string[] | null, + body?: null | Record | string + ) + name: 'ResponseStatusCodeError' + code: 'UND_ERR_RESPONSE_STATUS_CODE' + body: null | Record | string + status: number + statusCode: number + headers: IncomingHttpHeaders | string[] | null + } + + /** Passed an invalid argument. */ + export class InvalidArgumentError extends UndiciError { + name: 'InvalidArgumentError' + code: 'UND_ERR_INVALID_ARG' + } + + /** Returned an invalid value. */ + export class InvalidReturnValueError extends UndiciError { + name: 'InvalidReturnValueError' + code: 'UND_ERR_INVALID_RETURN_VALUE' + } + + /** The request has been aborted by the user. */ + export class RequestAbortedError extends UndiciError { + name: 'AbortError' + code: 'UND_ERR_ABORTED' + } + + /** Expected error with reason. */ + export class InformationalError extends UndiciError { + name: 'InformationalError' + code: 'UND_ERR_INFO' + } + + /** Request body length does not match content-length header. */ + export class RequestContentLengthMismatchError extends UndiciError { + name: 'RequestContentLengthMismatchError' + code: 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH' + } + + /** Response body length does not match content-length header. */ + export class ResponseContentLengthMismatchError extends UndiciError { + name: 'ResponseContentLengthMismatchError' + code: 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH' + } + + /** Trying to use a destroyed client. */ + export class ClientDestroyedError extends UndiciError { + name: 'ClientDestroyedError' + code: 'UND_ERR_DESTROYED' + } + + /** Trying to use a closed client. */ + export class ClientClosedError extends UndiciError { + name: 'ClientClosedError' + code: 'UND_ERR_CLOSED' + } + + /** There is an error with the socket. */ + export class SocketError extends UndiciError { + name: 'SocketError' + code: 'UND_ERR_SOCKET' + socket: Client.SocketInfo | null + } + + /** Encountered unsupported functionality. */ + export class NotSupportedError extends UndiciError { + name: 'NotSupportedError' + code: 'UND_ERR_NOT_SUPPORTED' + } + + /** No upstream has been added to the BalancedPool. */ + export class BalancedPoolMissingUpstreamError extends UndiciError { + name: 'MissingUpstreamError' + code: 'UND_ERR_BPL_MISSING_UPSTREAM' + } + + export class HTTPParserError extends UndiciError { + name: 'HTTPParserError' + code: string + } + + /** The response exceed the length allowed. */ + export class ResponseExceededMaxSizeError extends UndiciError { + name: 'ResponseExceededMaxSizeError' + code: 'UND_ERR_RES_EXCEEDED_MAX_SIZE' + } + + export class RequestRetryError extends UndiciError { + constructor ( + message: string, + statusCode: number, + headers?: IncomingHttpHeaders | string[] | null, + body?: null | Record | string + ) + name: 'RequestRetryError' + code: 'UND_ERR_REQ_RETRY' + statusCode: number + data: { + count: number; + } + + headers: Record + } + + export class SecureProxyConnectionError extends UndiciError { + constructor ( + cause?: Error, + message?: string, + options?: Record + ) + name: 'SecureProxyConnectionError' + code: 'UND_ERR_PRX_TLS' + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/eventsource.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/eventsource.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..081ca09aee97ff540fecfb22737d94c39d52c35c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/eventsource.d.ts @@ -0,0 +1,66 @@ +import { MessageEvent, ErrorEvent } from './websocket' +import Dispatcher from './dispatcher' + +import { + EventListenerOptions, + AddEventListenerOptions, + EventListenerOrEventListenerObject +} from './patch' + +interface EventSourceEventMap { + error: ErrorEvent + message: MessageEvent + open: Event +} + +interface EventSource extends EventTarget { + close(): void + readonly CLOSED: 2 + readonly CONNECTING: 0 + readonly OPEN: 1 + onerror: ((this: EventSource, ev: ErrorEvent) => any) | null + onmessage: ((this: EventSource, ev: MessageEvent) => any) | null + onopen: ((this: EventSource, ev: Event) => any) | null + readonly readyState: 0 | 1 | 2 + readonly url: string + readonly withCredentials: boolean + + addEventListener( + type: K, + listener: (this: EventSource, ev: EventSourceEventMap[K]) => any, + options?: boolean | AddEventListenerOptions + ): void + addEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions + ): void + removeEventListener( + type: K, + listener: (this: EventSource, ev: EventSourceEventMap[K]) => any, + options?: boolean | EventListenerOptions + ): void + removeEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | EventListenerOptions + ): void +} + +export declare const EventSource: { + prototype: EventSource + new (url: string | URL, init?: EventSourceInit): EventSource + readonly CLOSED: 2 + readonly CONNECTING: 0 + readonly OPEN: 1 +} + +interface EventSourceInit { + withCredentials?: boolean + // @deprecated use `node.dispatcher` instead + dispatcher?: Dispatcher + node?: { + dispatcher?: Dispatcher + reconnectionTime?: number + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/fetch.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/fetch.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2cf502900d13e9b12ab975274f28bffa690eb77c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/fetch.d.ts @@ -0,0 +1,211 @@ +// based on https://github.com/Ethan-Arrowood/undici-fetch/blob/249269714db874351589d2d364a0645d5160ae71/index.d.ts (MIT license) +// and https://github.com/node-fetch/node-fetch/blob/914ce6be5ec67a8bab63d68510aabf07cb818b6d/index.d.ts (MIT license) +/// + +import { Blob } from 'buffer' +import { URL, URLSearchParams } from 'url' +import { ReadableStream } from 'stream/web' +import { FormData } from './formdata' +import { HeaderRecord } from './header' +import Dispatcher from './dispatcher' + +export type RequestInfo = string | URL | Request + +export declare function fetch ( + input: RequestInfo, + init?: RequestInit +): Promise + +export type BodyInit = + | ArrayBuffer + | AsyncIterable + | Blob + | FormData + | Iterable + | NodeJS.ArrayBufferView + | URLSearchParams + | null + | string + +export class BodyMixin { + readonly body: ReadableStream | null + readonly bodyUsed: boolean + + readonly arrayBuffer: () => Promise + readonly blob: () => Promise + readonly bytes: () => Promise + /** + * @deprecated This method is not recommended for parsing multipart/form-data bodies in server environments. + * It is recommended to use a library such as [@fastify/busboy](https://www.npmjs.com/package/@fastify/busboy) as follows: + * + * @example + * ```js + * import { Busboy } from '@fastify/busboy' + * import { Readable } from 'node:stream' + * + * const response = await fetch('...') + * const busboy = new Busboy({ headers: { 'content-type': response.headers.get('content-type') } }) + * + * // handle events emitted from `busboy` + * + * Readable.fromWeb(response.body).pipe(busboy) + * ``` + */ + readonly formData: () => Promise + readonly json: () => Promise + readonly text: () => Promise +} + +export interface SpecIterator { + next(...args: [] | [TNext]): IteratorResult; +} + +export interface SpecIterableIterator extends SpecIterator { + [Symbol.iterator](): SpecIterableIterator; +} + +export interface SpecIterable { + [Symbol.iterator](): SpecIterator; +} + +export type HeadersInit = [string, string][] | HeaderRecord | Headers + +export declare class Headers implements SpecIterable<[string, string]> { + constructor (init?: HeadersInit) + readonly append: (name: string, value: string) => void + readonly delete: (name: string) => void + readonly get: (name: string) => string | null + readonly has: (name: string) => boolean + readonly set: (name: string, value: string) => void + readonly getSetCookie: () => string[] + readonly forEach: ( + callbackfn: (value: string, key: string, iterable: Headers) => void, + thisArg?: unknown + ) => void + + readonly keys: () => SpecIterableIterator + readonly values: () => SpecIterableIterator + readonly entries: () => SpecIterableIterator<[string, string]> + readonly [Symbol.iterator]: () => SpecIterableIterator<[string, string]> +} + +export type RequestCache = + | 'default' + | 'force-cache' + | 'no-cache' + | 'no-store' + | 'only-if-cached' + | 'reload' + +export type RequestCredentials = 'omit' | 'include' | 'same-origin' + +type RequestDestination = + | '' + | 'audio' + | 'audioworklet' + | 'document' + | 'embed' + | 'font' + | 'image' + | 'manifest' + | 'object' + | 'paintworklet' + | 'report' + | 'script' + | 'sharedworker' + | 'style' + | 'track' + | 'video' + | 'worker' + | 'xslt' + +export interface RequestInit { + body?: BodyInit | null + cache?: RequestCache + credentials?: RequestCredentials + dispatcher?: Dispatcher + duplex?: RequestDuplex + headers?: HeadersInit + integrity?: string + keepalive?: boolean + method?: string + mode?: RequestMode + redirect?: RequestRedirect + referrer?: string + referrerPolicy?: ReferrerPolicy + signal?: AbortSignal | null + window?: null +} + +export type ReferrerPolicy = + | '' + | 'no-referrer' + | 'no-referrer-when-downgrade' + | 'origin' + | 'origin-when-cross-origin' + | 'same-origin' + | 'strict-origin' + | 'strict-origin-when-cross-origin' + | 'unsafe-url' + +export type RequestMode = 'cors' | 'navigate' | 'no-cors' | 'same-origin' + +export type RequestRedirect = 'error' | 'follow' | 'manual' + +export type RequestDuplex = 'half' + +export declare class Request extends BodyMixin { + constructor (input: RequestInfo, init?: RequestInit) + + readonly cache: RequestCache + readonly credentials: RequestCredentials + readonly destination: RequestDestination + readonly headers: Headers + readonly integrity: string + readonly method: string + readonly mode: RequestMode + readonly redirect: RequestRedirect + readonly referrer: string + readonly referrerPolicy: ReferrerPolicy + readonly url: string + + readonly keepalive: boolean + readonly signal: AbortSignal + readonly duplex: RequestDuplex + + readonly clone: () => Request +} + +export interface ResponseInit { + readonly status?: number + readonly statusText?: string + readonly headers?: HeadersInit +} + +export type ResponseType = + | 'basic' + | 'cors' + | 'default' + | 'error' + | 'opaque' + | 'opaqueredirect' + +export type ResponseRedirectStatus = 301 | 302 | 303 | 307 | 308 + +export declare class Response extends BodyMixin { + constructor (body?: BodyInit, init?: ResponseInit) + + readonly headers: Headers + readonly ok: boolean + readonly status: number + readonly statusText: string + readonly type: ResponseType + readonly url: string + readonly redirected: boolean + + readonly clone: () => Response + + static error (): Response + static json (data: any, init?: ResponseInit): Response + static redirect (url: string | URL, status: ResponseRedirectStatus): Response +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/formdata.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/formdata.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..030f5485950d343405827f8b1aacacec2472b55d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/formdata.d.ts @@ -0,0 +1,108 @@ +// Based on https://github.com/octet-stream/form-data/blob/2d0f0dc371517444ce1f22cdde13f51995d0953a/lib/FormData.ts (MIT) +/// + +import { File } from 'buffer' +import { SpecIterableIterator } from './fetch' + +/** + * A `string` or `File` that represents a single value from a set of `FormData` key-value pairs. + */ +declare type FormDataEntryValue = string | File + +/** + * Provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using fetch(). + */ +export declare class FormData { + /** + * Appends a new value onto an existing key inside a FormData object, + * or adds the key if it does not already exist. + * + * The difference between `set()` and `append()` is that if the specified key already exists, `set()` will overwrite all existing values with the new one, whereas `append()` will append the new value onto the end of the existing set of values. + * + * @param name The name of the field whose data is contained in `value`. + * @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) + or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string. + * @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename. + */ + append (name: string, value: unknown, fileName?: string): void + + /** + * Set a new value for an existing key inside FormData, + * or add the new field if it does not already exist. + * + * @param name The name of the field whose data is contained in `value`. + * @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) + or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string. + * @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename. + * + */ + set (name: string, value: unknown, fileName?: string): void + + /** + * Returns the first value associated with a given key from within a `FormData` object. + * If you expect multiple values and want all of them, use the `getAll()` method instead. + * + * @param {string} name A name of the value you want to retrieve. + * + * @returns A `FormDataEntryValue` containing the value. If the key doesn't exist, the method returns null. + */ + get (name: string): FormDataEntryValue | null + + /** + * Returns all the values associated with a given key from within a `FormData` object. + * + * @param {string} name A name of the value you want to retrieve. + * + * @returns An array of `FormDataEntryValue` whose key matches the value passed in the `name` parameter. If the key doesn't exist, the method returns an empty list. + */ + getAll (name: string): FormDataEntryValue[] + + /** + * Returns a boolean stating whether a `FormData` object contains a certain key. + * + * @param name A string representing the name of the key you want to test for. + * + * @return A boolean value. + */ + has (name: string): boolean + + /** + * Deletes a key and its value(s) from a `FormData` object. + * + * @param name The name of the key you want to delete. + */ + delete (name: string): void + + /** + * Executes given callback function for each field of the FormData instance + */ + forEach: ( + callbackfn: (value: FormDataEntryValue, key: string, iterable: FormData) => void, + thisArg?: unknown + ) => void + + /** + * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all keys contained in this `FormData` object. + * Each key is a `string`. + */ + keys: () => SpecIterableIterator + + /** + * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all values contained in this object `FormData` object. + * Each value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue). + */ + values: () => SpecIterableIterator + + /** + * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through the `FormData` key/value pairs. + * The key of each pair is a string; the value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue). + */ + entries: () => SpecIterableIterator<[string, FormDataEntryValue]> + + /** + * An alias for FormData#entries() + */ + [Symbol.iterator]: () => SpecIterableIterator<[string, FormDataEntryValue]> + + readonly [Symbol.toStringTag]: string +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/global-dispatcher.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/global-dispatcher.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2760e136de4469460e7e35cf0908ac2ad20fc316 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/global-dispatcher.d.ts @@ -0,0 +1,9 @@ +import Dispatcher from './dispatcher' + +declare function setGlobalDispatcher (dispatcher: DispatcherImplementation): void +declare function getGlobalDispatcher (): Dispatcher + +export { + getGlobalDispatcher, + setGlobalDispatcher +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/global-origin.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/global-origin.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..265769b7b4e6bc82f6fcfb0143736cbe8fab92a4 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/global-origin.d.ts @@ -0,0 +1,7 @@ +declare function setGlobalOrigin (origin: string | URL | undefined): void +declare function getGlobalOrigin (): URL | undefined + +export { + setGlobalOrigin, + getGlobalOrigin +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/h2c-client.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/h2c-client.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e7a6808df36324049b1290e0a629a28f49848008 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/h2c-client.d.ts @@ -0,0 +1,73 @@ +import { URL } from 'url' +import Dispatcher from './dispatcher' +import buildConnector from './connector' + +type H2ClientOptions = Omit + +/** + * A basic H2C client, mapped on top a single TCP connection. Pipelining is disabled by default. + */ +export class H2CClient extends Dispatcher { + constructor (url: string | URL, options?: H2CClient.Options) + /** Property to get and set the pipelining factor. */ + pipelining: number + /** `true` after `client.close()` has been called. */ + closed: boolean + /** `true` after `client.destroyed()` has been called or `client.close()` has been called and the client shutdown has completed. */ + destroyed: boolean + + // Override dispatcher APIs. + override connect ( + options: H2ClientOptions + ): Promise + override connect ( + options: H2ClientOptions, + callback: (err: Error | null, data: Dispatcher.ConnectData) => void + ): void +} + +export declare namespace H2CClient { + export interface Options { + /** The maximum length of request headers in bytes. Default: Node.js' `--max-http-header-size` or `16384` (16KiB). */ + maxHeaderSize?: number; + /** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers (Node 14 and above only). Default: `300e3` milliseconds (300s). */ + headersTimeout?: number; + /** TODO */ + connectTimeout?: number; + /** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Default: `300e3` milliseconds (300s). */ + bodyTimeout?: number; + /** the timeout, in milliseconds, after which a socket without active requests will time out. Monitors time between activity on a connected socket. This value may be overridden by *keep-alive* hints from the server. Default: `4e3` milliseconds (4s). */ + keepAliveTimeout?: number; + /** the maximum allowed `idleTimeout`, in milliseconds, when overridden by *keep-alive* hints from the server. Default: `600e3` milliseconds (10min). */ + keepAliveMaxTimeout?: number; + /** A number of milliseconds subtracted from server *keep-alive* hints when overriding `idleTimeout` to account for timing inaccuracies caused by e.g. transport latency. Default: `1e3` milliseconds (1s). */ + keepAliveTimeoutThreshold?: number; + /** TODO */ + socketPath?: string; + /** The amount of concurrent requests to be sent over the single TCP/TLS connection according to [RFC7230](https://tools.ietf.org/html/rfc7230#section-6.3.2). Default: `1`. */ + pipelining?: number; + /** If `true`, an error is thrown when the request content-length header doesn't match the length of the request body. Default: `true`. */ + strictContentLength?: boolean; + /** TODO */ + maxCachedSessions?: number; + /** TODO */ + connect?: Omit, 'allowH2'> | buildConnector.connector; + /** TODO */ + maxRequestsPerClient?: number; + /** TODO */ + localAddress?: string; + /** Max response body size in bytes, -1 is disabled */ + maxResponseSize?: number; + /** Enables a family autodetection algorithm that loosely implements section 5 of RFC 8305. */ + autoSelectFamily?: boolean; + /** The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option. */ + autoSelectFamilyAttemptTimeout?: number; + /** + * @description Dictates the maximum number of concurrent streams for a single H2 session. It can be overridden by a SETTINGS remote frame. + * @default 100 + */ + maxConcurrentStreams?: number + } +} + +export default H2CClient diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/handlers.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/handlers.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8007dbf8e39a132426b2f04db68d2a0667569190 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/handlers.d.ts @@ -0,0 +1,15 @@ +import Dispatcher from './dispatcher' + +export declare class RedirectHandler implements Dispatcher.DispatchHandler { + constructor ( + dispatch: Dispatcher.Dispatch, + maxRedirections: number, + opts: Dispatcher.DispatchOptions, + handler: Dispatcher.DispatchHandler, + redirectionLimitReached: boolean + ) +} + +export declare class DecoratorHandler implements Dispatcher.DispatchHandler { + constructor (handler: Dispatcher.DispatchHandler) +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/header.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/header.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..efd7b1dd0bbae5a603aa1d0452b13cd1a8bc721c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/header.d.ts @@ -0,0 +1,160 @@ +import { Autocomplete } from './utility' + +/** + * The header type declaration of `undici`. + */ +export type IncomingHttpHeaders = Record + +type HeaderNames = Autocomplete< + | 'Accept' + | 'Accept-CH' + | 'Accept-Charset' + | 'Accept-Encoding' + | 'Accept-Language' + | 'Accept-Patch' + | 'Accept-Post' + | 'Accept-Ranges' + | 'Access-Control-Allow-Credentials' + | 'Access-Control-Allow-Headers' + | 'Access-Control-Allow-Methods' + | 'Access-Control-Allow-Origin' + | 'Access-Control-Expose-Headers' + | 'Access-Control-Max-Age' + | 'Access-Control-Request-Headers' + | 'Access-Control-Request-Method' + | 'Age' + | 'Allow' + | 'Alt-Svc' + | 'Alt-Used' + | 'Authorization' + | 'Cache-Control' + | 'Clear-Site-Data' + | 'Connection' + | 'Content-Disposition' + | 'Content-Encoding' + | 'Content-Language' + | 'Content-Length' + | 'Content-Location' + | 'Content-Range' + | 'Content-Security-Policy' + | 'Content-Security-Policy-Report-Only' + | 'Content-Type' + | 'Cookie' + | 'Cross-Origin-Embedder-Policy' + | 'Cross-Origin-Opener-Policy' + | 'Cross-Origin-Resource-Policy' + | 'Date' + | 'Device-Memory' + | 'ETag' + | 'Expect' + | 'Expect-CT' + | 'Expires' + | 'Forwarded' + | 'From' + | 'Host' + | 'If-Match' + | 'If-Modified-Since' + | 'If-None-Match' + | 'If-Range' + | 'If-Unmodified-Since' + | 'Keep-Alive' + | 'Last-Modified' + | 'Link' + | 'Location' + | 'Max-Forwards' + | 'Origin' + | 'Permissions-Policy' + | 'Priority' + | 'Proxy-Authenticate' + | 'Proxy-Authorization' + | 'Range' + | 'Referer' + | 'Referrer-Policy' + | 'Retry-After' + | 'Sec-Fetch-Dest' + | 'Sec-Fetch-Mode' + | 'Sec-Fetch-Site' + | 'Sec-Fetch-User' + | 'Sec-Purpose' + | 'Sec-WebSocket-Accept' + | 'Server' + | 'Server-Timing' + | 'Service-Worker-Navigation-Preload' + | 'Set-Cookie' + | 'SourceMap' + | 'Strict-Transport-Security' + | 'TE' + | 'Timing-Allow-Origin' + | 'Trailer' + | 'Transfer-Encoding' + | 'Upgrade' + | 'Upgrade-Insecure-Requests' + | 'User-Agent' + | 'Vary' + | 'Via' + | 'WWW-Authenticate' + | 'X-Content-Type-Options' + | 'X-Frame-Options' +> + +type IANARegisteredMimeType = Autocomplete< + | 'audio/aac' + | 'video/x-msvideo' + | 'image/avif' + | 'video/av1' + | 'application/octet-stream' + | 'image/bmp' + | 'text/css' + | 'text/csv' + | 'application/vnd.ms-fontobject' + | 'application/epub+zip' + | 'image/gif' + | 'application/gzip' + | 'text/html' + | 'image/x-icon' + | 'text/calendar' + | 'image/jpeg' + | 'text/javascript' + | 'application/json' + | 'application/ld+json' + | 'audio/x-midi' + | 'audio/mpeg' + | 'video/mp4' + | 'video/mpeg' + | 'audio/ogg' + | 'video/ogg' + | 'application/ogg' + | 'audio/opus' + | 'font/otf' + | 'application/pdf' + | 'image/png' + | 'application/rtf' + | 'image/svg+xml' + | 'image/tiff' + | 'video/mp2t' + | 'font/ttf' + | 'text/plain' + | 'application/wasm' + | 'video/webm' + | 'audio/webm' + | 'image/webp' + | 'font/woff' + | 'font/woff2' + | 'application/xhtml+xml' + | 'application/xml' + | 'application/zip' + | 'video/3gpp' + | 'video/3gpp2' + | 'model/gltf+json' + | 'model/gltf-binary' +> + +type KnownHeaderValues = { + 'content-type': IANARegisteredMimeType +} + +export type HeaderRecord = { + [K in HeaderNames | Lowercase]?: Lowercase extends keyof KnownHeaderValues + ? KnownHeaderValues[Lowercase] + : string +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/index.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..be0bc289c5f48c2a45f0583146d6f6e8173cfd1d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/index.d.ts @@ -0,0 +1,80 @@ +import Dispatcher from './dispatcher' +import { setGlobalDispatcher, getGlobalDispatcher } from './global-dispatcher' +import { setGlobalOrigin, getGlobalOrigin } from './global-origin' +import Pool from './pool' +import { RedirectHandler, DecoratorHandler } from './handlers' + +import BalancedPool from './balanced-pool' +import Client from './client' +import H2CClient from './h2c-client' +import buildConnector from './connector' +import errors from './errors' +import Agent from './agent' +import MockClient from './mock-client' +import MockPool from './mock-pool' +import MockAgent from './mock-agent' +import { SnapshotAgent } from './snapshot-agent' +import { MockCallHistory, MockCallHistoryLog } from './mock-call-history' +import mockErrors from './mock-errors' +import ProxyAgent from './proxy-agent' +import EnvHttpProxyAgent from './env-http-proxy-agent' +import RetryHandler from './retry-handler' +import RetryAgent from './retry-agent' +import { request, pipeline, stream, connect, upgrade } from './api' +import interceptors from './interceptors' + +export * from './util' +export * from './cookies' +export * from './eventsource' +export * from './fetch' +export * from './formdata' +export * from './diagnostics-channel' +export * from './websocket' +export * from './content-type' +export * from './cache' +export { Interceptable } from './mock-interceptor' + +declare function globalThisInstall (): void + +export { Dispatcher, BalancedPool, Pool, Client, buildConnector, errors, Agent, request, stream, pipeline, connect, upgrade, setGlobalDispatcher, getGlobalDispatcher, setGlobalOrigin, getGlobalOrigin, interceptors, MockClient, MockPool, MockAgent, SnapshotAgent, MockCallHistory, MockCallHistoryLog, mockErrors, ProxyAgent, EnvHttpProxyAgent, RedirectHandler, DecoratorHandler, RetryHandler, RetryAgent, H2CClient, globalThisInstall as install } +export default Undici + +declare namespace Undici { + const Dispatcher: typeof import('./dispatcher').default + const Pool: typeof import('./pool').default + const RedirectHandler: typeof import ('./handlers').RedirectHandler + const DecoratorHandler: typeof import ('./handlers').DecoratorHandler + const RetryHandler: typeof import ('./retry-handler').default + const BalancedPool: typeof import('./balanced-pool').default + const Client: typeof import('./client').default + const H2CClient: typeof import('./h2c-client').default + const buildConnector: typeof import('./connector').default + const errors: typeof import('./errors').default + const Agent: typeof import('./agent').default + const setGlobalDispatcher: typeof import('./global-dispatcher').setGlobalDispatcher + const getGlobalDispatcher: typeof import('./global-dispatcher').getGlobalDispatcher + const request: typeof import('./api').request + const stream: typeof import('./api').stream + const pipeline: typeof import('./api').pipeline + const connect: typeof import('./api').connect + const upgrade: typeof import('./api').upgrade + const MockClient: typeof import('./mock-client').default + const MockPool: typeof import('./mock-pool').default + const MockAgent: typeof import('./mock-agent').default + const SnapshotAgent: typeof import('./snapshot-agent').SnapshotAgent + const MockCallHistory: typeof import('./mock-call-history').MockCallHistory + const MockCallHistoryLog: typeof import('./mock-call-history').MockCallHistoryLog + const mockErrors: typeof import('./mock-errors').default + const fetch: typeof import('./fetch').fetch + const Headers: typeof import('./fetch').Headers + const Response: typeof import('./fetch').Response + const Request: typeof import('./fetch').Request + const FormData: typeof import('./formdata').FormData + const caches: typeof import('./cache').caches + const interceptors: typeof import('./interceptors').default + const cacheStores: { + MemoryCacheStore: typeof import('./cache-interceptor').default.MemoryCacheStore, + SqliteCacheStore: typeof import('./cache-interceptor').default.SqliteCacheStore + } + const install: typeof globalThisInstall +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/interceptors.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/interceptors.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..74389db2758574cb135d3425d5d040851bab848d --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/interceptors.d.ts @@ -0,0 +1,39 @@ +import CacheHandler from './cache-interceptor' +import Dispatcher from './dispatcher' +import RetryHandler from './retry-handler' +import { LookupOptions } from 'node:dns' + +export default Interceptors + +declare namespace Interceptors { + export type DumpInterceptorOpts = { maxSize?: number } + export type RetryInterceptorOpts = RetryHandler.RetryOptions + export type RedirectInterceptorOpts = { maxRedirections?: number } + export type DecompressInterceptorOpts = { + skipErrorResponses?: boolean + skipStatusCodes?: number[] + } + + export type ResponseErrorInterceptorOpts = { throwOnError: boolean } + export type CacheInterceptorOpts = CacheHandler.CacheOptions + + // DNS interceptor + export type DNSInterceptorRecord = { address: string, ttl: number, family: 4 | 6 } + export type DNSInterceptorOriginRecords = { 4: { ips: DNSInterceptorRecord[] } | null, 6: { ips: DNSInterceptorRecord[] } | null } + export type DNSInterceptorOpts = { + maxTTL?: number + maxItems?: number + lookup?: (hostname: string, options: LookupOptions, callback: (err: NodeJS.ErrnoException | null, addresses: DNSInterceptorRecord[]) => void) => void + pick?: (origin: URL, records: DNSInterceptorOriginRecords, affinity: 4 | 6) => DNSInterceptorRecord + dualStack?: boolean + affinity?: 4 | 6 + } + + export function dump (opts?: DumpInterceptorOpts): Dispatcher.DispatcherComposeInterceptor + export function retry (opts?: RetryInterceptorOpts): Dispatcher.DispatcherComposeInterceptor + export function redirect (opts?: RedirectInterceptorOpts): Dispatcher.DispatcherComposeInterceptor + export function decompress (opts?: DecompressInterceptorOpts): Dispatcher.DispatcherComposeInterceptor + export function responseError (opts?: ResponseErrorInterceptorOpts): Dispatcher.DispatcherComposeInterceptor + export function dns (opts?: DNSInterceptorOpts): Dispatcher.DispatcherComposeInterceptor + export function cache (opts?: CacheInterceptorOpts): Dispatcher.DispatcherComposeInterceptor +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/mock-agent.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/mock-agent.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..330926be1919b19d6aa1c5e1bd4efc9bdfb53401 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/mock-agent.d.ts @@ -0,0 +1,68 @@ +import Agent from './agent' +import Dispatcher from './dispatcher' +import { Interceptable, MockInterceptor } from './mock-interceptor' +import MockDispatch = MockInterceptor.MockDispatch +import { MockCallHistory } from './mock-call-history' + +export default MockAgent + +interface PendingInterceptor extends MockDispatch { + origin: string; +} + +/** A mocked Agent class that implements the Agent API. It allows one to intercept HTTP requests made through undici and return mocked responses instead. */ +declare class MockAgent extends Dispatcher { + constructor (options?: TMockAgentOptions) + /** Creates and retrieves mock Dispatcher instances which can then be used to intercept HTTP requests. If the number of connections on the mock agent is set to 1, a MockClient instance is returned. Otherwise a MockPool instance is returned. */ + get(origin: string): TInterceptable + get(origin: RegExp): TInterceptable + get(origin: ((origin: string) => boolean)): TInterceptable + /** Dispatches a mocked request. */ + dispatch (options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandler): boolean + /** Closes the mock agent and waits for registered mock pools and clients to also close before resolving. */ + close (): Promise + /** Disables mocking in MockAgent. */ + deactivate (): void + /** Enables mocking in a MockAgent instance. When instantiated, a MockAgent is automatically activated. Therefore, this method is only effective after `MockAgent.deactivate` has been called. */ + activate (): void + /** Define host matchers so only matching requests that aren't intercepted by the mock dispatchers will be attempted. */ + enableNetConnect (): void + enableNetConnect (host: string): void + enableNetConnect (host: RegExp): void + enableNetConnect (host: ((host: string) => boolean)): void + /** Causes all requests to throw when requests are not matched in a MockAgent intercept. */ + disableNetConnect (): void + /** get call history. returns the MockAgent call history or undefined if the option is not enabled. */ + getCallHistory (): MockCallHistory | undefined + /** clear every call history. Any MockCallHistoryLog will be deleted on the MockCallHistory instance */ + clearCallHistory (): void + /** Enable call history. Any subsequence calls will then be registered. */ + enableCallHistory (): this + /** Disable call history. Any subsequence calls will then not be registered. */ + disableCallHistory (): this + pendingInterceptors (): PendingInterceptor[] + assertNoPendingInterceptors (options?: { + pendingInterceptorsFormatter?: PendingInterceptorsFormatter; + }): void +} + +interface PendingInterceptorsFormatter { + format(pendingInterceptors: readonly PendingInterceptor[]): string; +} + +declare namespace MockAgent { + /** MockAgent options. */ + export interface Options extends Agent.Options { + /** A custom agent to be encapsulated by the MockAgent. */ + agent?: Dispatcher; + + /** Ignore trailing slashes in the path */ + ignoreTrailingSlash?: boolean; + + /** Accept URLs with search parameters using non standard syntaxes. default false */ + acceptNonStandardSearchParameters?: boolean; + + /** Enable call history. you can either call MockAgent.enableCallHistory(). default false */ + enableCallHistory?: boolean + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/mock-call-history.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/mock-call-history.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..df07fa0dca09be2221fd4cfb74093682891012bf --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/mock-call-history.d.ts @@ -0,0 +1,111 @@ +import Dispatcher from './dispatcher' + +declare namespace MockCallHistoryLog { + /** request's configuration properties */ + export type MockCallHistoryLogProperties = 'protocol' | 'host' | 'port' | 'origin' | 'path' | 'hash' | 'fullUrl' | 'method' | 'searchParams' | 'body' | 'headers' +} + +/** a log reflecting request configuration */ +declare class MockCallHistoryLog { + constructor (requestInit: Dispatcher.DispatchOptions) + /** protocol used. ie. 'https:' or 'http:' etc... */ + protocol: string + /** request's host. */ + host: string + /** request's port. */ + port: string + /** request's origin. ie. https://localhost:3000. */ + origin: string + /** path. never contains searchParams. */ + path: string + /** request's hash. */ + hash: string + /** the full url requested. */ + fullUrl: string + /** request's method. */ + method: string + /** search params. */ + searchParams: Record + /** request's body */ + body: string | null | undefined + /** request's headers */ + headers: Record | null | undefined + + /** returns an Map of property / value pair */ + toMap (): Map | null | undefined> + + /** returns a string computed with all key value pair */ + toString (): string +} + +declare namespace MockCallHistory { + export type FilterCallsOperator = 'AND' | 'OR' + + /** modify the filtering behavior */ + export interface FilterCallsOptions { + /** the operator to apply when filtering. 'OR' will adds any MockCallHistoryLog matching any criteria given. 'AND' will adds only MockCallHistoryLog matching every criteria given. (default 'OR') */ + operator?: FilterCallsOperator | Lowercase + } + /** a function to be executed for filtering MockCallHistoryLog */ + export type FilterCallsFunctionCriteria = (log: MockCallHistoryLog) => boolean + + /** parameter to filter MockCallHistoryLog */ + export type FilterCallsParameter = string | RegExp | undefined | null + + /** an object to execute multiple filtering at once */ + export interface FilterCallsObjectCriteria extends Record { + /** filter by request protocol. ie https: */ + protocol?: FilterCallsParameter; + /** filter by request host. */ + host?: FilterCallsParameter; + /** filter by request port. */ + port?: FilterCallsParameter; + /** filter by request origin. */ + origin?: FilterCallsParameter; + /** filter by request path. */ + path?: FilterCallsParameter; + /** filter by request hash. */ + hash?: FilterCallsParameter; + /** filter by request fullUrl. */ + fullUrl?: FilterCallsParameter; + /** filter by request method. */ + method?: FilterCallsParameter; + } +} + +/** a call history to track requests configuration */ +declare class MockCallHistory { + constructor (name: string) + /** returns an array of MockCallHistoryLog. */ + calls (): Array + /** returns the first MockCallHistoryLog */ + firstCall (): MockCallHistoryLog | undefined + /** returns the last MockCallHistoryLog. */ + lastCall (): MockCallHistoryLog | undefined + /** returns the nth MockCallHistoryLog. */ + nthCall (position: number): MockCallHistoryLog | undefined + /** return all MockCallHistoryLog matching any of criteria given. if an object is used with multiple properties, you can change the operator to apply during filtering on options */ + filterCalls (criteria: MockCallHistory.FilterCallsFunctionCriteria | MockCallHistory.FilterCallsObjectCriteria | RegExp, options?: MockCallHistory.FilterCallsOptions): Array + /** return all MockCallHistoryLog matching the given protocol. if a string is given, it is matched with includes */ + filterCallsByProtocol (protocol: MockCallHistory.FilterCallsParameter): Array + /** return all MockCallHistoryLog matching the given host. if a string is given, it is matched with includes */ + filterCallsByHost (host: MockCallHistory.FilterCallsParameter): Array + /** return all MockCallHistoryLog matching the given port. if a string is given, it is matched with includes */ + filterCallsByPort (port: MockCallHistory.FilterCallsParameter): Array + /** return all MockCallHistoryLog matching the given origin. if a string is given, it is matched with includes */ + filterCallsByOrigin (origin: MockCallHistory.FilterCallsParameter): Array + /** return all MockCallHistoryLog matching the given path. if a string is given, it is matched with includes */ + filterCallsByPath (path: MockCallHistory.FilterCallsParameter): Array + /** return all MockCallHistoryLog matching the given hash. if a string is given, it is matched with includes */ + filterCallsByHash (hash: MockCallHistory.FilterCallsParameter): Array + /** return all MockCallHistoryLog matching the given fullUrl. if a string is given, it is matched with includes */ + filterCallsByFullUrl (fullUrl: MockCallHistory.FilterCallsParameter): Array + /** return all MockCallHistoryLog matching the given method. if a string is given, it is matched with includes */ + filterCallsByMethod (method: MockCallHistory.FilterCallsParameter): Array + /** clear all MockCallHistoryLog on this MockCallHistory. */ + clear (): void + /** use it with for..of loop or spread operator */ + [Symbol.iterator]: () => Generator +} + +export { MockCallHistoryLog, MockCallHistory } diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/mock-client.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/mock-client.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..702e82464942a643ef3249691be7a8ecc5aa4474 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/mock-client.d.ts @@ -0,0 +1,27 @@ +import Client from './client' +import Dispatcher from './dispatcher' +import MockAgent from './mock-agent' +import { MockInterceptor, Interceptable } from './mock-interceptor' + +export default MockClient + +/** MockClient extends the Client API and allows one to mock requests. */ +declare class MockClient extends Client implements Interceptable { + constructor (origin: string, options: MockClient.Options) + /** Intercepts any matching requests that use the same origin as this mock client. */ + intercept (options: MockInterceptor.Options): MockInterceptor + /** Dispatches a mocked request. */ + dispatch (options: Dispatcher.DispatchOptions, handlers: Dispatcher.DispatchHandler): boolean + /** Closes the mock client and gracefully waits for enqueued requests to complete. */ + close (): Promise + /** Clean up all the prepared mocks. */ + cleanMocks (): void +} + +declare namespace MockClient { + /** MockClient options. */ + export interface Options extends Client.Options { + /** The agent to associate this MockClient with. */ + agent: MockAgent; + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/mock-errors.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/mock-errors.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..eefeecd62ee909d24faec88a3db00e23d0fbf602 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/mock-errors.d.ts @@ -0,0 +1,12 @@ +import Errors from './errors' + +export default MockErrors + +declare namespace MockErrors { + /** The request does not match any registered mock dispatches. */ + export class MockNotMatchedError extends Errors.UndiciError { + constructor (message?: string) + name: 'MockNotMatchedError' + code: 'UND_MOCK_ERR_MOCK_NOT_MATCHED' + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/mock-interceptor.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/mock-interceptor.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a48d715a4cd094e6e0c301651dbb9d3efe710f07 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/mock-interceptor.d.ts @@ -0,0 +1,94 @@ +import { IncomingHttpHeaders } from './header' +import Dispatcher from './dispatcher' +import { BodyInit, Headers } from './fetch' + +/** The scope associated with a mock dispatch. */ +declare class MockScope { + constructor (mockDispatch: MockInterceptor.MockDispatch) + /** Delay a reply by a set amount of time in ms. */ + delay (waitInMs: number): MockScope + /** Persist the defined mock data for the associated reply. It will return the defined mock data indefinitely. */ + persist (): MockScope + /** Define a reply for a set amount of matching requests. */ + times (repeatTimes: number): MockScope +} + +/** The interceptor for a Mock. */ +declare class MockInterceptor { + constructor (options: MockInterceptor.Options, mockDispatches: MockInterceptor.MockDispatch[]) + /** Mock an undici request with the defined reply. */ + reply(replyOptionsCallback: MockInterceptor.MockReplyOptionsCallback): MockScope + reply( + statusCode: number, + data?: TData | Buffer | string | MockInterceptor.MockResponseDataHandler, + responseOptions?: MockInterceptor.MockResponseOptions + ): MockScope + /** Mock an undici request by throwing the defined reply error. */ + replyWithError(error: TError): MockScope + /** Set default reply headers on the interceptor for subsequent mocked replies. */ + defaultReplyHeaders (headers: IncomingHttpHeaders): MockInterceptor + /** Set default reply trailers on the interceptor for subsequent mocked replies. */ + defaultReplyTrailers (trailers: Record): MockInterceptor + /** Set automatically calculated content-length header on subsequent mocked replies. */ + replyContentLength (): MockInterceptor +} + +declare namespace MockInterceptor { + /** MockInterceptor options. */ + export interface Options { + /** Path to intercept on. */ + path: string | RegExp | ((path: string) => boolean); + /** Method to intercept on. Defaults to GET. */ + method?: string | RegExp | ((method: string) => boolean); + /** Body to intercept on. */ + body?: string | RegExp | ((body: string) => boolean); + /** Headers to intercept on. */ + headers?: Record boolean)> | ((headers: Record) => boolean); + /** Query params to intercept on */ + query?: Record; + } + export interface MockDispatch extends Options { + times: number | null; + persist: boolean; + consumed: boolean; + data: MockDispatchData; + } + export interface MockDispatchData extends MockResponseOptions { + error: TError | null; + statusCode?: number; + data?: TData | string; + } + export interface MockResponseOptions { + headers?: IncomingHttpHeaders; + trailers?: Record; + } + + export interface MockResponseCallbackOptions { + path: string; + method: string; + headers?: Headers | Record; + origin?: string; + body?: BodyInit | Dispatcher.DispatchOptions['body'] | null; + } + + export type MockResponseDataHandler = ( + opts: MockResponseCallbackOptions + ) => TData | Buffer | string + + export type MockReplyOptionsCallback = ( + opts: MockResponseCallbackOptions + ) => { statusCode: number, data?: TData | Buffer | string, responseOptions?: MockResponseOptions } +} + +interface Interceptable extends Dispatcher { + /** Intercepts any matching requests that use the same origin as this mock client. */ + intercept(options: MockInterceptor.Options): MockInterceptor; + /** Clean up all the prepared mocks. */ + cleanMocks (): void +} + +export { + Interceptable, + MockInterceptor, + MockScope +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/mock-pool.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/mock-pool.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f35f357bc136e96f45968f6bbb86a82800e44f5e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/mock-pool.d.ts @@ -0,0 +1,27 @@ +import Pool from './pool' +import MockAgent from './mock-agent' +import { Interceptable, MockInterceptor } from './mock-interceptor' +import Dispatcher from './dispatcher' + +export default MockPool + +/** MockPool extends the Pool API and allows one to mock requests. */ +declare class MockPool extends Pool implements Interceptable { + constructor (origin: string, options: MockPool.Options) + /** Intercepts any matching requests that use the same origin as this mock pool. */ + intercept (options: MockInterceptor.Options): MockInterceptor + /** Dispatches a mocked request. */ + dispatch (options: Dispatcher.DispatchOptions, handlers: Dispatcher.DispatchHandler): boolean + /** Closes the mock pool and gracefully waits for enqueued requests to complete. */ + close (): Promise + /** Clean up all the prepared mocks. */ + cleanMocks (): void +} + +declare namespace MockPool { + /** MockPool options. */ + export interface Options extends Pool.Options { + /** The agent to associate this MockPool with. */ + agent: MockAgent; + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/patch.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/patch.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8f7acbb069eb7249b7cc75bb7decd843e6471ebb --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/patch.d.ts @@ -0,0 +1,29 @@ +/// + +// See https://github.com/nodejs/undici/issues/1740 + +export interface EventInit { + bubbles?: boolean + cancelable?: boolean + composed?: boolean +} + +export interface EventListenerOptions { + capture?: boolean +} + +export interface AddEventListenerOptions extends EventListenerOptions { + once?: boolean + passive?: boolean + signal?: AbortSignal +} + +export type EventListenerOrEventListenerObject = EventListener | EventListenerObject + +export interface EventListenerObject { + handleEvent (object: Event): void +} + +export interface EventListener { + (evt: Event): void +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/pool-stats.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/pool-stats.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f76a5f61dddf89cf4fb863a040a99e3aa20260d1 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/pool-stats.d.ts @@ -0,0 +1,19 @@ +import Pool from './pool' + +export default PoolStats + +declare class PoolStats { + constructor (pool: Pool) + /** Number of open socket connections in this pool. */ + connected: number + /** Number of open socket connections in this pool that do not have an active request. */ + free: number + /** Number of pending requests across all clients in this pool. */ + pending: number + /** Number of queued requests across all clients in this pool. */ + queued: number + /** Number of currently active requests across all clients in this pool. */ + running: number + /** Number of active, pending, or queued requests across all clients in this pool. */ + size: number +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/pool.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/pool.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5198476eb9c78f0b28b1fed73c306957fff13f50 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/pool.d.ts @@ -0,0 +1,41 @@ +import Client from './client' +import TPoolStats from './pool-stats' +import { URL } from 'url' +import Dispatcher from './dispatcher' + +export default Pool + +type PoolConnectOptions = Omit + +declare class Pool extends Dispatcher { + constructor (url: string | URL, options?: Pool.Options) + /** `true` after `pool.close()` has been called. */ + closed: boolean + /** `true` after `pool.destroyed()` has been called or `pool.close()` has been called and the pool shutdown has completed. */ + destroyed: boolean + /** Aggregate stats for a Pool. */ + readonly stats: TPoolStats + + // Override dispatcher APIs. + override connect ( + options: PoolConnectOptions + ): Promise + override connect ( + options: PoolConnectOptions, + callback: (err: Error | null, data: Dispatcher.ConnectData) => void + ): void +} + +declare namespace Pool { + export type PoolStats = TPoolStats + export interface Options extends Client.Options { + /** Default: `(origin, opts) => new Client(origin, opts)`. */ + factory?(origin: URL, opts: object): Dispatcher; + /** The max number of clients to create. `null` if no limit. Default `null`. */ + connections?: number | null; + /** The amount of time before a client is removed from the pool and closed. `null` if no time limit. Default `null` */ + clientTtl?: number | null; + + interceptors?: { Pool?: readonly Dispatcher.DispatchInterceptor[] } & Client.Options['interceptors'] + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/proxy-agent.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/proxy-agent.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..41555422178b578b7e68d355f171d39bf8e5915c --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/proxy-agent.d.ts @@ -0,0 +1,29 @@ +import Agent from './agent' +import buildConnector from './connector' +import Dispatcher from './dispatcher' +import { IncomingHttpHeaders } from './header' + +export default ProxyAgent + +declare class ProxyAgent extends Dispatcher { + constructor (options: ProxyAgent.Options | string) + + dispatch (options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandler): boolean + close (): Promise +} + +declare namespace ProxyAgent { + export interface Options extends Agent.Options { + uri: string; + /** + * @deprecated use opts.token + */ + auth?: string; + token?: string; + headers?: IncomingHttpHeaders; + requestTls?: buildConnector.BuildOptions; + proxyTls?: buildConnector.BuildOptions; + clientFactory?(origin: URL, opts: object): Dispatcher; + proxyTunnel?: boolean; + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/readable.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/readable.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e4f314b4a0ec333b91401832470eefcd86332ca7 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/readable.d.ts @@ -0,0 +1,68 @@ +import { Readable } from 'stream' +import { Blob } from 'buffer' + +export default BodyReadable + +declare class BodyReadable extends Readable { + constructor (opts: { + resume: (this: Readable, size: number) => void | null; + abort: () => void | null; + contentType?: string; + contentLength?: number; + highWaterMark?: number; + }) + + /** Consumes and returns the body as a string + * https://fetch.spec.whatwg.org/#dom-body-text + */ + text (): Promise + + /** Consumes and returns the body as a JavaScript Object + * https://fetch.spec.whatwg.org/#dom-body-json + */ + json (): Promise + + /** Consumes and returns the body as a Blob + * https://fetch.spec.whatwg.org/#dom-body-blob + */ + blob (): Promise + + /** Consumes and returns the body as an Uint8Array + * https://fetch.spec.whatwg.org/#dom-body-bytes + */ + bytes (): Promise + + /** Consumes and returns the body as an ArrayBuffer + * https://fetch.spec.whatwg.org/#dom-body-arraybuffer + */ + arrayBuffer (): Promise + + /** Not implemented + * + * https://fetch.spec.whatwg.org/#dom-body-formdata + */ + formData (): Promise + + /** Returns true if the body is not null and the body has been consumed + * + * Otherwise, returns false + * + * https://fetch.spec.whatwg.org/#dom-body-bodyused + */ + readonly bodyUsed: boolean + + /** + * If body is null, it should return null as the body + * + * If body is not null, should return the body as a ReadableStream + * + * https://fetch.spec.whatwg.org/#dom-body-body + */ + readonly body: never | undefined + + /** Dumps the response body by reading `limit` number of bytes. + * @param opts.limit Number of bytes to read (optional) - Default: 131072 + * @param opts.signal AbortSignal to cancel the operation (optional) + */ + dump (opts?: { limit: number; signal?: AbortSignal }): Promise +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/retry-agent.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/retry-agent.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..82268c373888338b27237d9a11a6193f511d5873 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/retry-agent.d.ts @@ -0,0 +1,8 @@ +import Dispatcher from './dispatcher' +import RetryHandler from './retry-handler' + +export default RetryAgent + +declare class RetryAgent extends Dispatcher { + constructor (dispatcher: Dispatcher, options?: RetryHandler.RetryOptions) +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/retry-handler.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/retry-handler.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3bc484b2d0705407f38eea25022ae20bd2a47c80 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/retry-handler.d.ts @@ -0,0 +1,125 @@ +import Dispatcher from './dispatcher' + +export default RetryHandler + +declare class RetryHandler implements Dispatcher.DispatchHandler { + constructor ( + options: Dispatcher.DispatchOptions & { + retryOptions?: RetryHandler.RetryOptions; + }, + retryHandlers: RetryHandler.RetryHandlers + ) +} + +declare namespace RetryHandler { + export type RetryState = { counter: number; } + + export type RetryContext = { + state: RetryState; + opts: Dispatcher.DispatchOptions & { + retryOptions?: RetryHandler.RetryOptions; + }; + } + + export type OnRetryCallback = (result?: Error | null) => void + + export type RetryCallback = ( + err: Error, + context: { + state: RetryState; + opts: Dispatcher.DispatchOptions & { + retryOptions?: RetryHandler.RetryOptions; + }; + }, + callback: OnRetryCallback + ) => void + + export interface RetryOptions { + /** + * If true, the retry handler will throw an error if the request fails, + * this will prevent the folling handlers from being called, and will destroy the socket. + * + * @type {boolean} + * @memberof RetryOptions + * @default true + */ + throwOnError?: boolean; + /** + * Callback to be invoked on every retry iteration. + * It receives the error, current state of the retry object and the options object + * passed when instantiating the retry handler. + * + * @type {RetryCallback} + * @memberof RetryOptions + */ + retry?: RetryCallback; + /** + * Maximum number of retries to allow. + * + * @type {number} + * @memberof RetryOptions + * @default 5 + */ + maxRetries?: number; + /** + * Max number of milliseconds allow between retries + * + * @type {number} + * @memberof RetryOptions + * @default 30000 + */ + maxTimeout?: number; + /** + * Initial number of milliseconds to wait before retrying for the first time. + * + * @type {number} + * @memberof RetryOptions + * @default 500 + */ + minTimeout?: number; + /** + * Factior to multiply the timeout factor between retries. + * + * @type {number} + * @memberof RetryOptions + * @default 2 + */ + timeoutFactor?: number; + /** + * It enables to automatically infer timeout between retries based on the `Retry-After` header. + * + * @type {boolean} + * @memberof RetryOptions + * @default true + */ + retryAfter?: boolean; + /** + * HTTP methods to retry. + * + * @type {Dispatcher.HttpMethod[]} + * @memberof RetryOptions + * @default ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'], + */ + methods?: Dispatcher.HttpMethod[]; + /** + * Error codes to be retried. e.g. `ECONNRESET`, `ENOTFOUND`, `ETIMEDOUT`, `ECONNREFUSED`, etc. + * + * @type {string[]} + * @default ['ECONNRESET','ECONNREFUSED','ENOTFOUND','ENETDOWN','ENETUNREACH','EHOSTDOWN','EHOSTUNREACH','EPIPE'] + */ + errorCodes?: string[]; + /** + * HTTP status codes to be retried. + * + * @type {number[]} + * @memberof RetryOptions + * @default [500, 502, 503, 504, 429], + */ + statusCodes?: number[]; + } + + export interface RetryHandlers { + dispatch: Dispatcher['dispatch']; + handler: Dispatcher.DispatchHandler; + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/snapshot-agent.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/snapshot-agent.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f1d1ccdbb4d2f2e5f03e6516b47bff7c8b69880f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/snapshot-agent.d.ts @@ -0,0 +1,109 @@ +import MockAgent from './mock-agent' + +declare class SnapshotRecorder { + constructor (options?: SnapshotRecorder.Options) + + record (requestOpts: any, response: any): Promise + findSnapshot (requestOpts: any): SnapshotRecorder.Snapshot | undefined + loadSnapshots (filePath?: string): Promise + saveSnapshots (filePath?: string): Promise + clear (): void + getSnapshots (): SnapshotRecorder.Snapshot[] + size (): number + resetCallCounts (): void + deleteSnapshot (requestOpts: any): boolean + getSnapshotInfo (requestOpts: any): SnapshotRecorder.SnapshotInfo | null + replaceSnapshots (snapshotData: SnapshotRecorder.SnapshotData[]): void + destroy (): void +} + +declare namespace SnapshotRecorder { + type SnapshotRecorderMode = 'record' | 'playback' | 'update' + + export interface Options { + snapshotPath?: string + mode?: SnapshotRecorderMode + maxSnapshots?: number + autoFlush?: boolean + flushInterval?: number + matchHeaders?: string[] + ignoreHeaders?: string[] + excludeHeaders?: string[] + matchBody?: boolean + matchQuery?: boolean + caseSensitive?: boolean + shouldRecord?: (requestOpts: any) => boolean + shouldPlayback?: (requestOpts: any) => boolean + excludeUrls?: (string | RegExp)[] + } + + export interface Snapshot { + request: { + method: string + url: string + headers: Record + body?: string + } + responses: { + statusCode: number + headers: Record + body: string + trailers: Record + }[] + callCount: number + timestamp: string + } + + export interface SnapshotInfo { + hash: string + request: { + method: string + url: string + headers: Record + body?: string + } + responseCount: number + callCount: number + timestamp: string + } + + export interface SnapshotData { + hash: string + snapshot: Snapshot + } +} + +declare class SnapshotAgent extends MockAgent { + constructor (options?: SnapshotAgent.Options) + + saveSnapshots (filePath?: string): Promise + loadSnapshots (filePath?: string): Promise + getRecorder (): SnapshotRecorder + getMode (): SnapshotRecorder.SnapshotRecorderMode + clearSnapshots (): void + resetCallCounts (): void + deleteSnapshot (requestOpts: any): boolean + getSnapshotInfo (requestOpts: any): SnapshotRecorder.SnapshotInfo | null + replaceSnapshots (snapshotData: SnapshotRecorder.SnapshotData[]): void +} + +declare namespace SnapshotAgent { + export interface Options extends MockAgent.Options { + mode?: SnapshotRecorder.SnapshotRecorderMode + snapshotPath?: string + maxSnapshots?: number + autoFlush?: boolean + flushInterval?: number + matchHeaders?: string[] + ignoreHeaders?: string[] + excludeHeaders?: string[] + matchBody?: boolean + matchQuery?: boolean + caseSensitive?: boolean + shouldRecord?: (requestOpts: any) => boolean + shouldPlayback?: (requestOpts: any) => boolean + excludeUrls?: (string | RegExp)[] + } +} + +export { SnapshotAgent, SnapshotRecorder } diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/util.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/util.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8fc50cc4243fcbf903caf6bac3b2cdae462f010e --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/util.d.ts @@ -0,0 +1,18 @@ +export namespace util { + /** + * Retrieves a header name and returns its lowercase value. + * @param value Header name + */ + export function headerNameToString (value: string | Buffer): string + + /** + * Receives a header object and returns the parsed value. + * @param headers Header object + * @param obj Object to specify a proxy object. Used to assign parsed values. + * @returns If `obj` is specified, it is equivalent to `obj`. + */ + export function parseHeaders ( + headers: (Buffer | string | (Buffer | string)[])[], + obj?: Record + ): Record +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/utility.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/utility.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bfb3ca7700c4cf98497774707cc6a6af754674b2 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/utility.d.ts @@ -0,0 +1,7 @@ +type AutocompletePrimitiveBaseType = + T extends string ? string : + T extends number ? number : + T extends boolean ? boolean : + never + +export type Autocomplete = T | (AutocompletePrimitiveBaseType & Record) diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/webidl.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/webidl.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f15d699d3fe27900cd33e216ef3d8ecc40eb3a06 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/webidl.d.ts @@ -0,0 +1,280 @@ +// These types are not exported, and are only used internally +import * as undici from './index' + +/** + * Take in an unknown value and return one that is of type T + */ +type Converter = (object: unknown) => T + +type SequenceConverter = (object: unknown, iterable?: IterableIterator) => T[] + +type RecordConverter = (object: unknown) => Record + +interface ConvertToIntOpts { + clamp?: boolean + enforceRange?: boolean +} + +interface WebidlErrors { + /** + * @description Instantiate an error + */ + exception (opts: { header: string, message: string }): TypeError + /** + * @description Instantiate an error when conversion from one type to another has failed + */ + conversionFailed (opts: { + prefix: string + argument: string + types: string[] + }): TypeError + /** + * @description Throw an error when an invalid argument is provided + */ + invalidArgument (opts: { + prefix: string + value: string + type: string + }): TypeError +} + +interface WebIDLTypes { + UNDEFINED: 1, + BOOLEAN: 2, + STRING: 3, + SYMBOL: 4, + NUMBER: 5, + BIGINT: 6, + NULL: 7 + OBJECT: 8 +} + +interface WebidlUtil { + /** + * @see https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values + */ + Type (object: unknown): WebIDLTypes[keyof WebIDLTypes] + + TypeValueToString (o: unknown): + | 'Undefined' + | 'Boolean' + | 'String' + | 'Symbol' + | 'Number' + | 'BigInt' + | 'Null' + | 'Object' + + Types: WebIDLTypes + + /** + * @see https://webidl.spec.whatwg.org/#abstract-opdef-converttoint + */ + ConvertToInt ( + V: unknown, + bitLength: number, + signedness: 'signed' | 'unsigned', + opts?: ConvertToIntOpts + ): number + + /** + * @see https://webidl.spec.whatwg.org/#abstract-opdef-integerpart + */ + IntegerPart (N: number): number + + /** + * Stringifies {@param V} + */ + Stringify (V: any): string + + MakeTypeAssertion (I: I): (arg: any) => arg is I + + /** + * Mark a value as uncloneable for Node.js. + * This is only effective in some newer Node.js versions. + */ + markAsUncloneable (V: any): void +} + +interface WebidlConverters { + /** + * @see https://webidl.spec.whatwg.org/#es-DOMString + */ + DOMString (V: unknown, prefix: string, argument: string, opts?: { + legacyNullToEmptyString: boolean + }): string + + /** + * @see https://webidl.spec.whatwg.org/#es-ByteString + */ + ByteString (V: unknown, prefix: string, argument: string): string + + /** + * @see https://webidl.spec.whatwg.org/#es-USVString + */ + USVString (V: unknown): string + + /** + * @see https://webidl.spec.whatwg.org/#es-boolean + */ + boolean (V: unknown): boolean + + /** + * @see https://webidl.spec.whatwg.org/#es-any + */ + any (V: Value): Value + + /** + * @see https://webidl.spec.whatwg.org/#es-long-long + */ + ['long long'] (V: unknown): number + + /** + * @see https://webidl.spec.whatwg.org/#es-unsigned-long-long + */ + ['unsigned long long'] (V: unknown): number + + /** + * @see https://webidl.spec.whatwg.org/#es-unsigned-long + */ + ['unsigned long'] (V: unknown): number + + /** + * @see https://webidl.spec.whatwg.org/#es-unsigned-short + */ + ['unsigned short'] (V: unknown, opts?: ConvertToIntOpts): number + + /** + * @see https://webidl.spec.whatwg.org/#idl-ArrayBuffer + */ + ArrayBuffer (V: unknown): ArrayBufferLike + ArrayBuffer (V: unknown, opts: { allowShared: false }): ArrayBuffer + + /** + * @see https://webidl.spec.whatwg.org/#es-buffer-source-types + */ + TypedArray ( + V: unknown, + TypedArray: NodeJS.TypedArray | ArrayBufferLike + ): NodeJS.TypedArray | ArrayBufferLike + TypedArray ( + V: unknown, + TypedArray: NodeJS.TypedArray | ArrayBufferLike, + opts?: { allowShared: false } + ): NodeJS.TypedArray | ArrayBuffer + + /** + * @see https://webidl.spec.whatwg.org/#es-buffer-source-types + */ + DataView (V: unknown, opts?: { allowShared: boolean }): DataView + + /** + * @see https://webidl.spec.whatwg.org/#BufferSource + */ + BufferSource ( + V: unknown, + opts?: { allowShared: boolean } + ): NodeJS.TypedArray | ArrayBufferLike | DataView + + ['sequence']: SequenceConverter + + ['sequence>']: SequenceConverter + + ['record']: RecordConverter + + /** + * @see https://fetch.spec.whatwg.org/#requestinfo + */ + RequestInfo (V: unknown): undici.Request | string + + /** + * @see https://fetch.spec.whatwg.org/#requestinit + */ + RequestInit (V: unknown): undici.RequestInit + + [Key: string]: (...args: any[]) => unknown +} + +type WebidlIsFunction = (arg: any) => arg is T + +interface WebidlIs { + Request: WebidlIsFunction + Response: WebidlIsFunction + ReadableStream: WebidlIsFunction + Blob: WebidlIsFunction + URLSearchParams: WebidlIsFunction + File: WebidlIsFunction + FormData: WebidlIsFunction + URL: WebidlIsFunction + WebSocketError: WebidlIsFunction + AbortSignal: WebidlIsFunction + MessagePort: WebidlIsFunction + USVString: WebidlIsFunction +} + +export interface Webidl { + errors: WebidlErrors + util: WebidlUtil + converters: WebidlConverters + is: WebidlIs + + /** + * @description Performs a brand-check on {@param V} to ensure it is a + * {@param cls} object. + */ + brandCheck unknown>(V: unknown, cls: Interface): asserts V is Interface + + brandCheckMultiple unknown)[]> (list: Interfaces): (V: any) => asserts V is Interfaces[number] + + /** + * @see https://webidl.spec.whatwg.org/#es-sequence + * @description Convert a value, V, to a WebIDL sequence type. + */ + sequenceConverter (C: Converter): SequenceConverter + + illegalConstructor (): never + + /** + * @see https://webidl.spec.whatwg.org/#es-to-record + * @description Convert a value, V, to a WebIDL record type. + */ + recordConverter ( + keyConverter: Converter, + valueConverter: Converter + ): RecordConverter + + /** + * Similar to {@link Webidl.brandCheck} but allows skipping the check if third party + * interfaces are allowed. + */ + interfaceConverter (typeCheck: WebidlIsFunction, name: string): ( + V: unknown, + prefix: string, + argument: string + ) => asserts V is Interface + + // TODO(@KhafraDev): a type could likely be implemented that can infer the return type + // from the converters given? + /** + * Converts a value, V, to a WebIDL dictionary types. Allows limiting which keys are + * allowed, values allowed, optional and required keys. Auto converts the value to + * a type given a converter. + */ + dictionaryConverter (converters: { + key: string, + defaultValue?: () => unknown, + required?: boolean, + converter: (...args: unknown[]) => unknown, + allowedValues?: unknown[] + }[]): (V: unknown) => Record + + /** + * @see https://webidl.spec.whatwg.org/#idl-nullable-type + * @description allows a type, V, to be null + */ + nullableConverter ( + converter: Converter + ): (V: unknown) => ReturnType | null + + argumentLengthCheck (args: { length: number }, min: number, context: string): void +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/websocket.d.ts b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/websocket.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a8477c1c948d71eafef0470ee6a4bc92160b620a --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/undici/types/websocket.d.ts @@ -0,0 +1,186 @@ +/// + +import type { Blob } from 'buffer' +import type { ReadableStream, WritableStream } from 'stream/web' +import type { MessagePort } from 'worker_threads' +import { + EventInit, + EventListenerOptions, + AddEventListenerOptions, + EventListenerOrEventListenerObject +} from './patch' +import Dispatcher from './dispatcher' +import { HeadersInit } from './fetch' + +export type BinaryType = 'blob' | 'arraybuffer' + +interface WebSocketEventMap { + close: CloseEvent + error: ErrorEvent + message: MessageEvent + open: Event +} + +interface WebSocket extends EventTarget { + binaryType: BinaryType + + readonly bufferedAmount: number + readonly extensions: string + + onclose: ((this: WebSocket, ev: WebSocketEventMap['close']) => any) | null + onerror: ((this: WebSocket, ev: WebSocketEventMap['error']) => any) | null + onmessage: ((this: WebSocket, ev: WebSocketEventMap['message']) => any) | null + onopen: ((this: WebSocket, ev: WebSocketEventMap['open']) => any) | null + + readonly protocol: string + readonly readyState: number + readonly url: string + + close(code?: number, reason?: string): void + send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void + + readonly CLOSED: number + readonly CLOSING: number + readonly CONNECTING: number + readonly OPEN: number + + addEventListener( + type: K, + listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, + options?: boolean | AddEventListenerOptions + ): void + addEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions + ): void + removeEventListener( + type: K, + listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, + options?: boolean | EventListenerOptions + ): void + removeEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | EventListenerOptions + ): void +} + +export declare const WebSocket: { + prototype: WebSocket + new (url: string | URL, protocols?: string | string[] | WebSocketInit): WebSocket + readonly CLOSED: number + readonly CLOSING: number + readonly CONNECTING: number + readonly OPEN: number +} + +interface CloseEventInit extends EventInit { + code?: number + reason?: string + wasClean?: boolean +} + +interface CloseEvent extends Event { + readonly code: number + readonly reason: string + readonly wasClean: boolean +} + +export declare const CloseEvent: { + prototype: CloseEvent + new (type: string, eventInitDict?: CloseEventInit): CloseEvent +} + +interface MessageEventInit extends EventInit { + data?: T + lastEventId?: string + origin?: string + ports?: (typeof MessagePort)[] + source?: typeof MessagePort | null +} + +interface MessageEvent extends Event { + readonly data: T + readonly lastEventId: string + readonly origin: string + readonly ports: ReadonlyArray + readonly source: typeof MessagePort | null + initMessageEvent( + type: string, + bubbles?: boolean, + cancelable?: boolean, + data?: any, + origin?: string, + lastEventId?: string, + source?: typeof MessagePort | null, + ports?: (typeof MessagePort)[] + ): void; +} + +export declare const MessageEvent: { + prototype: MessageEvent + new(type: string, eventInitDict?: MessageEventInit): MessageEvent +} + +interface ErrorEventInit extends EventInit { + message?: string + filename?: string + lineno?: number + colno?: number + error?: any +} + +interface ErrorEvent extends Event { + readonly message: string + readonly filename: string + readonly lineno: number + readonly colno: number + readonly error: Error +} + +export declare const ErrorEvent: { + prototype: ErrorEvent + new (type: string, eventInitDict?: ErrorEventInit): ErrorEvent +} + +interface WebSocketInit { + protocols?: string | string[], + dispatcher?: Dispatcher, + headers?: HeadersInit +} + +interface WebSocketStreamOptions { + protocols?: string | string[] + signal?: AbortSignal +} + +interface WebSocketCloseInfo { + closeCode: number + reason: string +} + +interface WebSocketStream { + closed: Promise + opened: Promise<{ + extensions: string + protocol: string + readable: ReadableStream + writable: WritableStream + }> + url: string +} + +export declare const WebSocketStream: { + prototype: WebSocketStream + new (url: string | URL, options?: WebSocketStreamOptions): WebSocketStream +} + +interface WebSocketError extends Event, WebSocketCloseInfo {} + +export declare const WebSocketError: { + prototype: WebSocketError + new (type: string, init?: WebSocketCloseInfo): WebSocketError +} + +export declare const ping: (ws: WebSocket, body?: Buffer) => void diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/buffer-util.js b/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/buffer-util.js new file mode 100644 index 0000000000000000000000000000000000000000..f7536e28efa570277e30e9ea001200ee11595fee --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/buffer-util.js @@ -0,0 +1,131 @@ +'use strict'; + +const { EMPTY_BUFFER } = require('./constants'); + +const FastBuffer = Buffer[Symbol.species]; + +/** + * Merges an array of buffers into a new buffer. + * + * @param {Buffer[]} list The array of buffers to concat + * @param {Number} totalLength The total length of buffers in the list + * @return {Buffer} The resulting buffer + * @public + */ +function concat(list, totalLength) { + if (list.length === 0) return EMPTY_BUFFER; + if (list.length === 1) return list[0]; + + const target = Buffer.allocUnsafe(totalLength); + let offset = 0; + + for (let i = 0; i < list.length; i++) { + const buf = list[i]; + target.set(buf, offset); + offset += buf.length; + } + + if (offset < totalLength) { + return new FastBuffer(target.buffer, target.byteOffset, offset); + } + + return target; +} + +/** + * Masks a buffer using the given mask. + * + * @param {Buffer} source The buffer to mask + * @param {Buffer} mask The mask to use + * @param {Buffer} output The buffer where to store the result + * @param {Number} offset The offset at which to start writing + * @param {Number} length The number of bytes to mask. + * @public + */ +function _mask(source, mask, output, offset, length) { + for (let i = 0; i < length; i++) { + output[offset + i] = source[i] ^ mask[i & 3]; + } +} + +/** + * Unmasks a buffer using the given mask. + * + * @param {Buffer} buffer The buffer to unmask + * @param {Buffer} mask The mask to use + * @public + */ +function _unmask(buffer, mask) { + for (let i = 0; i < buffer.length; i++) { + buffer[i] ^= mask[i & 3]; + } +} + +/** + * Converts a buffer to an `ArrayBuffer`. + * + * @param {Buffer} buf The buffer to convert + * @return {ArrayBuffer} Converted buffer + * @public + */ +function toArrayBuffer(buf) { + if (buf.length === buf.buffer.byteLength) { + return buf.buffer; + } + + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length); +} + +/** + * Converts `data` to a `Buffer`. + * + * @param {*} data The data to convert + * @return {Buffer} The buffer + * @throws {TypeError} + * @public + */ +function toBuffer(data) { + toBuffer.readOnly = true; + + if (Buffer.isBuffer(data)) return data; + + let buf; + + if (data instanceof ArrayBuffer) { + buf = new FastBuffer(data); + } else if (ArrayBuffer.isView(data)) { + buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength); + } else { + buf = Buffer.from(data); + toBuffer.readOnly = false; + } + + return buf; +} + +module.exports = { + concat, + mask: _mask, + toArrayBuffer, + toBuffer, + unmask: _unmask +}; + +/* istanbul ignore else */ +if (!process.env.WS_NO_BUFFER_UTIL) { + try { + const bufferUtil = require('bufferutil'); + + module.exports.mask = function (source, mask, output, offset, length) { + if (length < 48) _mask(source, mask, output, offset, length); + else bufferUtil.mask(source, mask, output, offset, length); + }; + + module.exports.unmask = function (buffer, mask) { + if (buffer.length < 32) _unmask(buffer, mask); + else bufferUtil.unmask(buffer, mask); + }; + } catch (e) { + // Continue regardless of the error. + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/constants.js b/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/constants.js new file mode 100644 index 0000000000000000000000000000000000000000..74214d466a65a086f4b16050d1a8a7b6935276a8 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/constants.js @@ -0,0 +1,18 @@ +'use strict'; + +const BINARY_TYPES = ['nodebuffer', 'arraybuffer', 'fragments']; +const hasBlob = typeof Blob !== 'undefined'; + +if (hasBlob) BINARY_TYPES.push('blob'); + +module.exports = { + BINARY_TYPES, + EMPTY_BUFFER: Buffer.alloc(0), + GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', + hasBlob, + kForOnEventAttribute: Symbol('kIsForOnEventAttribute'), + kListener: Symbol('kListener'), + kStatusCode: Symbol('status-code'), + kWebSocket: Symbol('websocket'), + NOOP: () => {} +}; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/event-target.js b/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/event-target.js new file mode 100644 index 0000000000000000000000000000000000000000..fea4cbc52c3299d0bd5fea32245360594812b5a5 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/event-target.js @@ -0,0 +1,292 @@ +'use strict'; + +const { kForOnEventAttribute, kListener } = require('./constants'); + +const kCode = Symbol('kCode'); +const kData = Symbol('kData'); +const kError = Symbol('kError'); +const kMessage = Symbol('kMessage'); +const kReason = Symbol('kReason'); +const kTarget = Symbol('kTarget'); +const kType = Symbol('kType'); +const kWasClean = Symbol('kWasClean'); + +/** + * Class representing an event. + */ +class Event { + /** + * Create a new `Event`. + * + * @param {String} type The name of the event + * @throws {TypeError} If the `type` argument is not specified + */ + constructor(type) { + this[kTarget] = null; + this[kType] = type; + } + + /** + * @type {*} + */ + get target() { + return this[kTarget]; + } + + /** + * @type {String} + */ + get type() { + return this[kType]; + } +} + +Object.defineProperty(Event.prototype, 'target', { enumerable: true }); +Object.defineProperty(Event.prototype, 'type', { enumerable: true }); + +/** + * Class representing a close event. + * + * @extends Event + */ +class CloseEvent extends Event { + /** + * Create a new `CloseEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {Number} [options.code=0] The status code explaining why the + * connection was closed + * @param {String} [options.reason=''] A human-readable string explaining why + * the connection was closed + * @param {Boolean} [options.wasClean=false] Indicates whether or not the + * connection was cleanly closed + */ + constructor(type, options = {}) { + super(type); + + this[kCode] = options.code === undefined ? 0 : options.code; + this[kReason] = options.reason === undefined ? '' : options.reason; + this[kWasClean] = options.wasClean === undefined ? false : options.wasClean; + } + + /** + * @type {Number} + */ + get code() { + return this[kCode]; + } + + /** + * @type {String} + */ + get reason() { + return this[kReason]; + } + + /** + * @type {Boolean} + */ + get wasClean() { + return this[kWasClean]; + } +} + +Object.defineProperty(CloseEvent.prototype, 'code', { enumerable: true }); +Object.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true }); +Object.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true }); + +/** + * Class representing an error event. + * + * @extends Event + */ +class ErrorEvent extends Event { + /** + * Create a new `ErrorEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {*} [options.error=null] The error that generated this event + * @param {String} [options.message=''] The error message + */ + constructor(type, options = {}) { + super(type); + + this[kError] = options.error === undefined ? null : options.error; + this[kMessage] = options.message === undefined ? '' : options.message; + } + + /** + * @type {*} + */ + get error() { + return this[kError]; + } + + /** + * @type {String} + */ + get message() { + return this[kMessage]; + } +} + +Object.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true }); +Object.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true }); + +/** + * Class representing a message event. + * + * @extends Event + */ +class MessageEvent extends Event { + /** + * Create a new `MessageEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {*} [options.data=null] The message content + */ + constructor(type, options = {}) { + super(type); + + this[kData] = options.data === undefined ? null : options.data; + } + + /** + * @type {*} + */ + get data() { + return this[kData]; + } +} + +Object.defineProperty(MessageEvent.prototype, 'data', { enumerable: true }); + +/** + * This provides methods for emulating the `EventTarget` interface. It's not + * meant to be used directly. + * + * @mixin + */ +const EventTarget = { + /** + * Register an event listener. + * + * @param {String} type A string representing the event type to listen for + * @param {(Function|Object)} handler The listener to add + * @param {Object} [options] An options object specifies characteristics about + * the event listener + * @param {Boolean} [options.once=false] A `Boolean` indicating that the + * listener should be invoked at most once after being added. If `true`, + * the listener would be automatically removed when invoked. + * @public + */ + addEventListener(type, handler, options = {}) { + for (const listener of this.listeners(type)) { + if ( + !options[kForOnEventAttribute] && + listener[kListener] === handler && + !listener[kForOnEventAttribute] + ) { + return; + } + } + + let wrapper; + + if (type === 'message') { + wrapper = function onMessage(data, isBinary) { + const event = new MessageEvent('message', { + data: isBinary ? data : data.toString() + }); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === 'close') { + wrapper = function onClose(code, message) { + const event = new CloseEvent('close', { + code, + reason: message.toString(), + wasClean: this._closeFrameReceived && this._closeFrameSent + }); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === 'error') { + wrapper = function onError(error) { + const event = new ErrorEvent('error', { + error, + message: error.message + }); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === 'open') { + wrapper = function onOpen() { + const event = new Event('open'); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else { + return; + } + + wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute]; + wrapper[kListener] = handler; + + if (options.once) { + this.once(type, wrapper); + } else { + this.on(type, wrapper); + } + }, + + /** + * Remove an event listener. + * + * @param {String} type A string representing the event type to remove + * @param {(Function|Object)} handler The listener to remove + * @public + */ + removeEventListener(type, handler) { + for (const listener of this.listeners(type)) { + if (listener[kListener] === handler && !listener[kForOnEventAttribute]) { + this.removeListener(type, listener); + break; + } + } + } +}; + +module.exports = { + CloseEvent, + ErrorEvent, + Event, + EventTarget, + MessageEvent +}; + +/** + * Call an event listener + * + * @param {(Function|Object)} listener The listener to call + * @param {*} thisArg The value to use as `this`` when calling the listener + * @param {Event} event The event to pass to the listener + * @private + */ +function callListener(listener, thisArg, event) { + if (typeof listener === 'object' && listener.handleEvent) { + listener.handleEvent.call(listener, event); + } else { + listener.call(thisArg, event); + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/extension.js b/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/extension.js new file mode 100644 index 0000000000000000000000000000000000000000..3d7895c1b0608d4bef7073a6acea9be39a4f8b74 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/extension.js @@ -0,0 +1,203 @@ +'use strict'; + +const { tokenChars } = require('./validation'); + +/** + * Adds an offer to the map of extension offers or a parameter to the map of + * parameters. + * + * @param {Object} dest The map of extension offers or parameters + * @param {String} name The extension or parameter name + * @param {(Object|Boolean|String)} elem The extension parameters or the + * parameter value + * @private + */ +function push(dest, name, elem) { + if (dest[name] === undefined) dest[name] = [elem]; + else dest[name].push(elem); +} + +/** + * Parses the `Sec-WebSocket-Extensions` header into an object. + * + * @param {String} header The field value of the header + * @return {Object} The parsed object + * @public + */ +function parse(header) { + const offers = Object.create(null); + let params = Object.create(null); + let mustUnescape = false; + let isEscaping = false; + let inQuotes = false; + let extensionName; + let paramName; + let start = -1; + let code = -1; + let end = -1; + let i = 0; + + for (; i < header.length; i++) { + code = header.charCodeAt(i); + + if (extensionName === undefined) { + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if ( + i !== 0 && + (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */ + ) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + const name = header.slice(start, end); + if (code === 0x2c) { + push(offers, name, params); + params = Object.create(null); + } else { + extensionName = name; + } + + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else if (paramName === undefined) { + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (code === 0x20 || code === 0x09) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x3b || code === 0x2c) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + push(params, header.slice(start, end), true); + if (code === 0x2c) { + push(offers, extensionName, params); + params = Object.create(null); + extensionName = undefined; + } + + start = end = -1; + } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) { + paramName = header.slice(start, i); + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else { + // + // The value of a quoted-string after unescaping must conform to the + // token ABNF, so only token characters are valid. + // Ref: https://tools.ietf.org/html/rfc6455#section-9.1 + // + if (isEscaping) { + if (tokenChars[code] !== 1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + if (start === -1) start = i; + else if (!mustUnescape) mustUnescape = true; + isEscaping = false; + } else if (inQuotes) { + if (tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (code === 0x22 /* '"' */ && start !== -1) { + inQuotes = false; + end = i; + } else if (code === 0x5c /* '\' */) { + isEscaping = true; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) { + inQuotes = true; + } else if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (start !== -1 && (code === 0x20 || code === 0x09)) { + if (end === -1) end = i; + } else if (code === 0x3b || code === 0x2c) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + let value = header.slice(start, end); + if (mustUnescape) { + value = value.replace(/\\/g, ''); + mustUnescape = false; + } + push(params, paramName, value); + if (code === 0x2c) { + push(offers, extensionName, params); + params = Object.create(null); + extensionName = undefined; + } + + paramName = undefined; + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } + } + + if (start === -1 || inQuotes || code === 0x20 || code === 0x09) { + throw new SyntaxError('Unexpected end of input'); + } + + if (end === -1) end = i; + const token = header.slice(start, end); + if (extensionName === undefined) { + push(offers, token, params); + } else { + if (paramName === undefined) { + push(params, token, true); + } else if (mustUnescape) { + push(params, paramName, token.replace(/\\/g, '')); + } else { + push(params, paramName, token); + } + push(offers, extensionName, params); + } + + return offers; +} + +/** + * Builds the `Sec-WebSocket-Extensions` header field value. + * + * @param {Object} extensions The map of extensions and parameters to format + * @return {String} A string representing the given object + * @public + */ +function format(extensions) { + return Object.keys(extensions) + .map((extension) => { + let configurations = extensions[extension]; + if (!Array.isArray(configurations)) configurations = [configurations]; + return configurations + .map((params) => { + return [extension] + .concat( + Object.keys(params).map((k) => { + let values = params[k]; + if (!Array.isArray(values)) values = [values]; + return values + .map((v) => (v === true ? k : `${k}=${v}`)) + .join('; '); + }) + ) + .join('; '); + }) + .join(', '); + }) + .join(', '); +} + +module.exports = { format, parse }; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/limiter.js b/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/limiter.js new file mode 100644 index 0000000000000000000000000000000000000000..3fd35784ea9ea59cff8c112b6556a89cde7f7b6f --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/limiter.js @@ -0,0 +1,55 @@ +'use strict'; + +const kDone = Symbol('kDone'); +const kRun = Symbol('kRun'); + +/** + * A very simple job queue with adjustable concurrency. Adapted from + * https://github.com/STRML/async-limiter + */ +class Limiter { + /** + * Creates a new `Limiter`. + * + * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed + * to run concurrently + */ + constructor(concurrency) { + this[kDone] = () => { + this.pending--; + this[kRun](); + }; + this.concurrency = concurrency || Infinity; + this.jobs = []; + this.pending = 0; + } + + /** + * Adds a job to the queue. + * + * @param {Function} job The job to run + * @public + */ + add(job) { + this.jobs.push(job); + this[kRun](); + } + + /** + * Removes a job from the queue and runs it if possible. + * + * @private + */ + [kRun]() { + if (this.pending === this.concurrency) return; + + if (this.jobs.length) { + const job = this.jobs.shift(); + + this.pending++; + job(this[kDone]); + } + } +} + +module.exports = Limiter; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/permessage-deflate.js b/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/permessage-deflate.js new file mode 100644 index 0000000000000000000000000000000000000000..41ff70e27d7bad779c0b1a6430af21bed1113282 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/permessage-deflate.js @@ -0,0 +1,528 @@ +'use strict'; + +const zlib = require('zlib'); + +const bufferUtil = require('./buffer-util'); +const Limiter = require('./limiter'); +const { kStatusCode } = require('./constants'); + +const FastBuffer = Buffer[Symbol.species]; +const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]); +const kPerMessageDeflate = Symbol('permessage-deflate'); +const kTotalLength = Symbol('total-length'); +const kCallback = Symbol('callback'); +const kBuffers = Symbol('buffers'); +const kError = Symbol('error'); + +// +// We limit zlib concurrency, which prevents severe memory fragmentation +// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913 +// and https://github.com/websockets/ws/issues/1202 +// +// Intentionally global; it's the global thread pool that's an issue. +// +let zlibLimiter; + +/** + * permessage-deflate implementation. + */ +class PerMessageDeflate { + /** + * Creates a PerMessageDeflate instance. + * + * @param {Object} [options] Configuration options + * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support + * for, or request, a custom client window size + * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/ + * acknowledge disabling of client context takeover + * @param {Number} [options.concurrencyLimit=10] The number of concurrent + * calls to zlib + * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the + * use of a custom server window size + * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept + * disabling of server context takeover + * @param {Number} [options.threshold=1024] Size (in bytes) below which + * messages should not be compressed if context takeover is disabled + * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on + * deflate + * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on + * inflate + * @param {Boolean} [isServer=false] Create the instance in either server or + * client mode + * @param {Number} [maxPayload=0] The maximum allowed message length + */ + constructor(options, isServer, maxPayload) { + this._maxPayload = maxPayload | 0; + this._options = options || {}; + this._threshold = + this._options.threshold !== undefined ? this._options.threshold : 1024; + this._isServer = !!isServer; + this._deflate = null; + this._inflate = null; + + this.params = null; + + if (!zlibLimiter) { + const concurrency = + this._options.concurrencyLimit !== undefined + ? this._options.concurrencyLimit + : 10; + zlibLimiter = new Limiter(concurrency); + } + } + + /** + * @type {String} + */ + static get extensionName() { + return 'permessage-deflate'; + } + + /** + * Create an extension negotiation offer. + * + * @return {Object} Extension parameters + * @public + */ + offer() { + const params = {}; + + if (this._options.serverNoContextTakeover) { + params.server_no_context_takeover = true; + } + if (this._options.clientNoContextTakeover) { + params.client_no_context_takeover = true; + } + if (this._options.serverMaxWindowBits) { + params.server_max_window_bits = this._options.serverMaxWindowBits; + } + if (this._options.clientMaxWindowBits) { + params.client_max_window_bits = this._options.clientMaxWindowBits; + } else if (this._options.clientMaxWindowBits == null) { + params.client_max_window_bits = true; + } + + return params; + } + + /** + * Accept an extension negotiation offer/response. + * + * @param {Array} configurations The extension negotiation offers/reponse + * @return {Object} Accepted configuration + * @public + */ + accept(configurations) { + configurations = this.normalizeParams(configurations); + + this.params = this._isServer + ? this.acceptAsServer(configurations) + : this.acceptAsClient(configurations); + + return this.params; + } + + /** + * Releases all resources used by the extension. + * + * @public + */ + cleanup() { + if (this._inflate) { + this._inflate.close(); + this._inflate = null; + } + + if (this._deflate) { + const callback = this._deflate[kCallback]; + + this._deflate.close(); + this._deflate = null; + + if (callback) { + callback( + new Error( + 'The deflate stream was closed while data was being processed' + ) + ); + } + } + } + + /** + * Accept an extension negotiation offer. + * + * @param {Array} offers The extension negotiation offers + * @return {Object} Accepted configuration + * @private + */ + acceptAsServer(offers) { + const opts = this._options; + const accepted = offers.find((params) => { + if ( + (opts.serverNoContextTakeover === false && + params.server_no_context_takeover) || + (params.server_max_window_bits && + (opts.serverMaxWindowBits === false || + (typeof opts.serverMaxWindowBits === 'number' && + opts.serverMaxWindowBits > params.server_max_window_bits))) || + (typeof opts.clientMaxWindowBits === 'number' && + !params.client_max_window_bits) + ) { + return false; + } + + return true; + }); + + if (!accepted) { + throw new Error('None of the extension offers can be accepted'); + } + + if (opts.serverNoContextTakeover) { + accepted.server_no_context_takeover = true; + } + if (opts.clientNoContextTakeover) { + accepted.client_no_context_takeover = true; + } + if (typeof opts.serverMaxWindowBits === 'number') { + accepted.server_max_window_bits = opts.serverMaxWindowBits; + } + if (typeof opts.clientMaxWindowBits === 'number') { + accepted.client_max_window_bits = opts.clientMaxWindowBits; + } else if ( + accepted.client_max_window_bits === true || + opts.clientMaxWindowBits === false + ) { + delete accepted.client_max_window_bits; + } + + return accepted; + } + + /** + * Accept the extension negotiation response. + * + * @param {Array} response The extension negotiation response + * @return {Object} Accepted configuration + * @private + */ + acceptAsClient(response) { + const params = response[0]; + + if ( + this._options.clientNoContextTakeover === false && + params.client_no_context_takeover + ) { + throw new Error('Unexpected parameter "client_no_context_takeover"'); + } + + if (!params.client_max_window_bits) { + if (typeof this._options.clientMaxWindowBits === 'number') { + params.client_max_window_bits = this._options.clientMaxWindowBits; + } + } else if ( + this._options.clientMaxWindowBits === false || + (typeof this._options.clientMaxWindowBits === 'number' && + params.client_max_window_bits > this._options.clientMaxWindowBits) + ) { + throw new Error( + 'Unexpected or invalid parameter "client_max_window_bits"' + ); + } + + return params; + } + + /** + * Normalize parameters. + * + * @param {Array} configurations The extension negotiation offers/reponse + * @return {Array} The offers/response with normalized parameters + * @private + */ + normalizeParams(configurations) { + configurations.forEach((params) => { + Object.keys(params).forEach((key) => { + let value = params[key]; + + if (value.length > 1) { + throw new Error(`Parameter "${key}" must have only a single value`); + } + + value = value[0]; + + if (key === 'client_max_window_bits') { + if (value !== true) { + const num = +value; + if (!Number.isInteger(num) || num < 8 || num > 15) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + value = num; + } else if (!this._isServer) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + } else if (key === 'server_max_window_bits') { + const num = +value; + if (!Number.isInteger(num) || num < 8 || num > 15) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + value = num; + } else if ( + key === 'client_no_context_takeover' || + key === 'server_no_context_takeover' + ) { + if (value !== true) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + } else { + throw new Error(`Unknown parameter "${key}"`); + } + + params[key] = value; + }); + }); + + return configurations; + } + + /** + * Decompress data. Concurrency limited. + * + * @param {Buffer} data Compressed data + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @public + */ + decompress(data, fin, callback) { + zlibLimiter.add((done) => { + this._decompress(data, fin, (err, result) => { + done(); + callback(err, result); + }); + }); + } + + /** + * Compress data. Concurrency limited. + * + * @param {(Buffer|String)} data Data to compress + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @public + */ + compress(data, fin, callback) { + zlibLimiter.add((done) => { + this._compress(data, fin, (err, result) => { + done(); + callback(err, result); + }); + }); + } + + /** + * Decompress data. + * + * @param {Buffer} data Compressed data + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @private + */ + _decompress(data, fin, callback) { + const endpoint = this._isServer ? 'client' : 'server'; + + if (!this._inflate) { + const key = `${endpoint}_max_window_bits`; + const windowBits = + typeof this.params[key] !== 'number' + ? zlib.Z_DEFAULT_WINDOWBITS + : this.params[key]; + + this._inflate = zlib.createInflateRaw({ + ...this._options.zlibInflateOptions, + windowBits + }); + this._inflate[kPerMessageDeflate] = this; + this._inflate[kTotalLength] = 0; + this._inflate[kBuffers] = []; + this._inflate.on('error', inflateOnError); + this._inflate.on('data', inflateOnData); + } + + this._inflate[kCallback] = callback; + + this._inflate.write(data); + if (fin) this._inflate.write(TRAILER); + + this._inflate.flush(() => { + const err = this._inflate[kError]; + + if (err) { + this._inflate.close(); + this._inflate = null; + callback(err); + return; + } + + const data = bufferUtil.concat( + this._inflate[kBuffers], + this._inflate[kTotalLength] + ); + + if (this._inflate._readableState.endEmitted) { + this._inflate.close(); + this._inflate = null; + } else { + this._inflate[kTotalLength] = 0; + this._inflate[kBuffers] = []; + + if (fin && this.params[`${endpoint}_no_context_takeover`]) { + this._inflate.reset(); + } + } + + callback(null, data); + }); + } + + /** + * Compress data. + * + * @param {(Buffer|String)} data Data to compress + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @private + */ + _compress(data, fin, callback) { + const endpoint = this._isServer ? 'server' : 'client'; + + if (!this._deflate) { + const key = `${endpoint}_max_window_bits`; + const windowBits = + typeof this.params[key] !== 'number' + ? zlib.Z_DEFAULT_WINDOWBITS + : this.params[key]; + + this._deflate = zlib.createDeflateRaw({ + ...this._options.zlibDeflateOptions, + windowBits + }); + + this._deflate[kTotalLength] = 0; + this._deflate[kBuffers] = []; + + this._deflate.on('data', deflateOnData); + } + + this._deflate[kCallback] = callback; + + this._deflate.write(data); + this._deflate.flush(zlib.Z_SYNC_FLUSH, () => { + if (!this._deflate) { + // + // The deflate stream was closed while data was being processed. + // + return; + } + + let data = bufferUtil.concat( + this._deflate[kBuffers], + this._deflate[kTotalLength] + ); + + if (fin) { + data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4); + } + + // + // Ensure that the callback will not be called again in + // `PerMessageDeflate#cleanup()`. + // + this._deflate[kCallback] = null; + + this._deflate[kTotalLength] = 0; + this._deflate[kBuffers] = []; + + if (fin && this.params[`${endpoint}_no_context_takeover`]) { + this._deflate.reset(); + } + + callback(null, data); + }); + } +} + +module.exports = PerMessageDeflate; + +/** + * The listener of the `zlib.DeflateRaw` stream `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function deflateOnData(chunk) { + this[kBuffers].push(chunk); + this[kTotalLength] += chunk.length; +} + +/** + * The listener of the `zlib.InflateRaw` stream `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function inflateOnData(chunk) { + this[kTotalLength] += chunk.length; + + if ( + this[kPerMessageDeflate]._maxPayload < 1 || + this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload + ) { + this[kBuffers].push(chunk); + return; + } + + this[kError] = new RangeError('Max payload size exceeded'); + this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'; + this[kError][kStatusCode] = 1009; + this.removeListener('data', inflateOnData); + + // + // The choice to employ `zlib.reset()` over `zlib.close()` is dictated by the + // fact that in Node.js versions prior to 13.10.0, the callback for + // `zlib.flush()` is not called if `zlib.close()` is used. Utilizing + // `zlib.reset()` ensures that either the callback is invoked or an error is + // emitted. + // + this.reset(); +} + +/** + * The listener of the `zlib.InflateRaw` stream `'error'` event. + * + * @param {Error} err The emitted error + * @private + */ +function inflateOnError(err) { + // + // There is no need to call `Zlib#close()` as the handle is automatically + // closed when an error is emitted. + // + this[kPerMessageDeflate]._inflate = null; + + if (this[kError]) { + this[kCallback](this[kError]); + return; + } + + err[kStatusCode] = 1007; + this[kCallback](err); +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/receiver.js b/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/receiver.js new file mode 100644 index 0000000000000000000000000000000000000000..54d9b4fadb47f697d35a42cebedd2a2851b85689 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/receiver.js @@ -0,0 +1,706 @@ +'use strict'; + +const { Writable } = require('stream'); + +const PerMessageDeflate = require('./permessage-deflate'); +const { + BINARY_TYPES, + EMPTY_BUFFER, + kStatusCode, + kWebSocket +} = require('./constants'); +const { concat, toArrayBuffer, unmask } = require('./buffer-util'); +const { isValidStatusCode, isValidUTF8 } = require('./validation'); + +const FastBuffer = Buffer[Symbol.species]; + +const GET_INFO = 0; +const GET_PAYLOAD_LENGTH_16 = 1; +const GET_PAYLOAD_LENGTH_64 = 2; +const GET_MASK = 3; +const GET_DATA = 4; +const INFLATING = 5; +const DEFER_EVENT = 6; + +/** + * HyBi Receiver implementation. + * + * @extends Writable + */ +class Receiver extends Writable { + /** + * Creates a Receiver instance. + * + * @param {Object} [options] Options object + * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether + * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted + * multiple times in the same tick + * @param {String} [options.binaryType=nodebuffer] The type for binary data + * @param {Object} [options.extensions] An object containing the negotiated + * extensions + * @param {Boolean} [options.isServer=false] Specifies whether to operate in + * client or server mode + * @param {Number} [options.maxPayload=0] The maximum allowed message length + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + */ + constructor(options = {}) { + super(); + + this._allowSynchronousEvents = + options.allowSynchronousEvents !== undefined + ? options.allowSynchronousEvents + : true; + this._binaryType = options.binaryType || BINARY_TYPES[0]; + this._extensions = options.extensions || {}; + this._isServer = !!options.isServer; + this._maxPayload = options.maxPayload | 0; + this._skipUTF8Validation = !!options.skipUTF8Validation; + this[kWebSocket] = undefined; + + this._bufferedBytes = 0; + this._buffers = []; + + this._compressed = false; + this._payloadLength = 0; + this._mask = undefined; + this._fragmented = 0; + this._masked = false; + this._fin = false; + this._opcode = 0; + + this._totalPayloadLength = 0; + this._messageLength = 0; + this._fragments = []; + + this._errored = false; + this._loop = false; + this._state = GET_INFO; + } + + /** + * Implements `Writable.prototype._write()`. + * + * @param {Buffer} chunk The chunk of data to write + * @param {String} encoding The character encoding of `chunk` + * @param {Function} cb Callback + * @private + */ + _write(chunk, encoding, cb) { + if (this._opcode === 0x08 && this._state == GET_INFO) return cb(); + + this._bufferedBytes += chunk.length; + this._buffers.push(chunk); + this.startLoop(cb); + } + + /** + * Consumes `n` bytes from the buffered data. + * + * @param {Number} n The number of bytes to consume + * @return {Buffer} The consumed bytes + * @private + */ + consume(n) { + this._bufferedBytes -= n; + + if (n === this._buffers[0].length) return this._buffers.shift(); + + if (n < this._buffers[0].length) { + const buf = this._buffers[0]; + this._buffers[0] = new FastBuffer( + buf.buffer, + buf.byteOffset + n, + buf.length - n + ); + + return new FastBuffer(buf.buffer, buf.byteOffset, n); + } + + const dst = Buffer.allocUnsafe(n); + + do { + const buf = this._buffers[0]; + const offset = dst.length - n; + + if (n >= buf.length) { + dst.set(this._buffers.shift(), offset); + } else { + dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset); + this._buffers[0] = new FastBuffer( + buf.buffer, + buf.byteOffset + n, + buf.length - n + ); + } + + n -= buf.length; + } while (n > 0); + + return dst; + } + + /** + * Starts the parsing loop. + * + * @param {Function} cb Callback + * @private + */ + startLoop(cb) { + this._loop = true; + + do { + switch (this._state) { + case GET_INFO: + this.getInfo(cb); + break; + case GET_PAYLOAD_LENGTH_16: + this.getPayloadLength16(cb); + break; + case GET_PAYLOAD_LENGTH_64: + this.getPayloadLength64(cb); + break; + case GET_MASK: + this.getMask(); + break; + case GET_DATA: + this.getData(cb); + break; + case INFLATING: + case DEFER_EVENT: + this._loop = false; + return; + } + } while (this._loop); + + if (!this._errored) cb(); + } + + /** + * Reads the first two bytes of a frame. + * + * @param {Function} cb Callback + * @private + */ + getInfo(cb) { + if (this._bufferedBytes < 2) { + this._loop = false; + return; + } + + const buf = this.consume(2); + + if ((buf[0] & 0x30) !== 0x00) { + const error = this.createError( + RangeError, + 'RSV2 and RSV3 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_2_3' + ); + + cb(error); + return; + } + + const compressed = (buf[0] & 0x40) === 0x40; + + if (compressed && !this._extensions[PerMessageDeflate.extensionName]) { + const error = this.createError( + RangeError, + 'RSV1 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_1' + ); + + cb(error); + return; + } + + this._fin = (buf[0] & 0x80) === 0x80; + this._opcode = buf[0] & 0x0f; + this._payloadLength = buf[1] & 0x7f; + + if (this._opcode === 0x00) { + if (compressed) { + const error = this.createError( + RangeError, + 'RSV1 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_1' + ); + + cb(error); + return; + } + + if (!this._fragmented) { + const error = this.createError( + RangeError, + 'invalid opcode 0', + true, + 1002, + 'WS_ERR_INVALID_OPCODE' + ); + + cb(error); + return; + } + + this._opcode = this._fragmented; + } else if (this._opcode === 0x01 || this._opcode === 0x02) { + if (this._fragmented) { + const error = this.createError( + RangeError, + `invalid opcode ${this._opcode}`, + true, + 1002, + 'WS_ERR_INVALID_OPCODE' + ); + + cb(error); + return; + } + + this._compressed = compressed; + } else if (this._opcode > 0x07 && this._opcode < 0x0b) { + if (!this._fin) { + const error = this.createError( + RangeError, + 'FIN must be set', + true, + 1002, + 'WS_ERR_EXPECTED_FIN' + ); + + cb(error); + return; + } + + if (compressed) { + const error = this.createError( + RangeError, + 'RSV1 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_1' + ); + + cb(error); + return; + } + + if ( + this._payloadLength > 0x7d || + (this._opcode === 0x08 && this._payloadLength === 1) + ) { + const error = this.createError( + RangeError, + `invalid payload length ${this._payloadLength}`, + true, + 1002, + 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH' + ); + + cb(error); + return; + } + } else { + const error = this.createError( + RangeError, + `invalid opcode ${this._opcode}`, + true, + 1002, + 'WS_ERR_INVALID_OPCODE' + ); + + cb(error); + return; + } + + if (!this._fin && !this._fragmented) this._fragmented = this._opcode; + this._masked = (buf[1] & 0x80) === 0x80; + + if (this._isServer) { + if (!this._masked) { + const error = this.createError( + RangeError, + 'MASK must be set', + true, + 1002, + 'WS_ERR_EXPECTED_MASK' + ); + + cb(error); + return; + } + } else if (this._masked) { + const error = this.createError( + RangeError, + 'MASK must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_MASK' + ); + + cb(error); + return; + } + + if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16; + else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64; + else this.haveLength(cb); + } + + /** + * Gets extended payload length (7+16). + * + * @param {Function} cb Callback + * @private + */ + getPayloadLength16(cb) { + if (this._bufferedBytes < 2) { + this._loop = false; + return; + } + + this._payloadLength = this.consume(2).readUInt16BE(0); + this.haveLength(cb); + } + + /** + * Gets extended payload length (7+64). + * + * @param {Function} cb Callback + * @private + */ + getPayloadLength64(cb) { + if (this._bufferedBytes < 8) { + this._loop = false; + return; + } + + const buf = this.consume(8); + const num = buf.readUInt32BE(0); + + // + // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned + // if payload length is greater than this number. + // + if (num > Math.pow(2, 53 - 32) - 1) { + const error = this.createError( + RangeError, + 'Unsupported WebSocket frame: payload length > 2^53 - 1', + false, + 1009, + 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH' + ); + + cb(error); + return; + } + + this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4); + this.haveLength(cb); + } + + /** + * Payload length has been read. + * + * @param {Function} cb Callback + * @private + */ + haveLength(cb) { + if (this._payloadLength && this._opcode < 0x08) { + this._totalPayloadLength += this._payloadLength; + if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) { + const error = this.createError( + RangeError, + 'Max payload size exceeded', + false, + 1009, + 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH' + ); + + cb(error); + return; + } + } + + if (this._masked) this._state = GET_MASK; + else this._state = GET_DATA; + } + + /** + * Reads mask bytes. + * + * @private + */ + getMask() { + if (this._bufferedBytes < 4) { + this._loop = false; + return; + } + + this._mask = this.consume(4); + this._state = GET_DATA; + } + + /** + * Reads data bytes. + * + * @param {Function} cb Callback + * @private + */ + getData(cb) { + let data = EMPTY_BUFFER; + + if (this._payloadLength) { + if (this._bufferedBytes < this._payloadLength) { + this._loop = false; + return; + } + + data = this.consume(this._payloadLength); + + if ( + this._masked && + (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0 + ) { + unmask(data, this._mask); + } + } + + if (this._opcode > 0x07) { + this.controlMessage(data, cb); + return; + } + + if (this._compressed) { + this._state = INFLATING; + this.decompress(data, cb); + return; + } + + if (data.length) { + // + // This message is not compressed so its length is the sum of the payload + // length of all fragments. + // + this._messageLength = this._totalPayloadLength; + this._fragments.push(data); + } + + this.dataMessage(cb); + } + + /** + * Decompresses data. + * + * @param {Buffer} data Compressed data + * @param {Function} cb Callback + * @private + */ + decompress(data, cb) { + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + + perMessageDeflate.decompress(data, this._fin, (err, buf) => { + if (err) return cb(err); + + if (buf.length) { + this._messageLength += buf.length; + if (this._messageLength > this._maxPayload && this._maxPayload > 0) { + const error = this.createError( + RangeError, + 'Max payload size exceeded', + false, + 1009, + 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH' + ); + + cb(error); + return; + } + + this._fragments.push(buf); + } + + this.dataMessage(cb); + if (this._state === GET_INFO) this.startLoop(cb); + }); + } + + /** + * Handles a data message. + * + * @param {Function} cb Callback + * @private + */ + dataMessage(cb) { + if (!this._fin) { + this._state = GET_INFO; + return; + } + + const messageLength = this._messageLength; + const fragments = this._fragments; + + this._totalPayloadLength = 0; + this._messageLength = 0; + this._fragmented = 0; + this._fragments = []; + + if (this._opcode === 2) { + let data; + + if (this._binaryType === 'nodebuffer') { + data = concat(fragments, messageLength); + } else if (this._binaryType === 'arraybuffer') { + data = toArrayBuffer(concat(fragments, messageLength)); + } else if (this._binaryType === 'blob') { + data = new Blob(fragments); + } else { + data = fragments; + } + + if (this._allowSynchronousEvents) { + this.emit('message', data, true); + this._state = GET_INFO; + } else { + this._state = DEFER_EVENT; + setImmediate(() => { + this.emit('message', data, true); + this._state = GET_INFO; + this.startLoop(cb); + }); + } + } else { + const buf = concat(fragments, messageLength); + + if (!this._skipUTF8Validation && !isValidUTF8(buf)) { + const error = this.createError( + Error, + 'invalid UTF-8 sequence', + true, + 1007, + 'WS_ERR_INVALID_UTF8' + ); + + cb(error); + return; + } + + if (this._state === INFLATING || this._allowSynchronousEvents) { + this.emit('message', buf, false); + this._state = GET_INFO; + } else { + this._state = DEFER_EVENT; + setImmediate(() => { + this.emit('message', buf, false); + this._state = GET_INFO; + this.startLoop(cb); + }); + } + } + } + + /** + * Handles a control message. + * + * @param {Buffer} data Data to handle + * @return {(Error|RangeError|undefined)} A possible error + * @private + */ + controlMessage(data, cb) { + if (this._opcode === 0x08) { + if (data.length === 0) { + this._loop = false; + this.emit('conclude', 1005, EMPTY_BUFFER); + this.end(); + } else { + const code = data.readUInt16BE(0); + + if (!isValidStatusCode(code)) { + const error = this.createError( + RangeError, + `invalid status code ${code}`, + true, + 1002, + 'WS_ERR_INVALID_CLOSE_CODE' + ); + + cb(error); + return; + } + + const buf = new FastBuffer( + data.buffer, + data.byteOffset + 2, + data.length - 2 + ); + + if (!this._skipUTF8Validation && !isValidUTF8(buf)) { + const error = this.createError( + Error, + 'invalid UTF-8 sequence', + true, + 1007, + 'WS_ERR_INVALID_UTF8' + ); + + cb(error); + return; + } + + this._loop = false; + this.emit('conclude', code, buf); + this.end(); + } + + this._state = GET_INFO; + return; + } + + if (this._allowSynchronousEvents) { + this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data); + this._state = GET_INFO; + } else { + this._state = DEFER_EVENT; + setImmediate(() => { + this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data); + this._state = GET_INFO; + this.startLoop(cb); + }); + } + } + + /** + * Builds an error object. + * + * @param {function(new:Error|RangeError)} ErrorCtor The error constructor + * @param {String} message The error message + * @param {Boolean} prefix Specifies whether or not to add a default prefix to + * `message` + * @param {Number} statusCode The status code + * @param {String} errorCode The exposed error code + * @return {(Error|RangeError)} The error + * @private + */ + createError(ErrorCtor, message, prefix, statusCode, errorCode) { + this._loop = false; + this._errored = true; + + const err = new ErrorCtor( + prefix ? `Invalid WebSocket frame: ${message}` : message + ); + + Error.captureStackTrace(err, this.createError); + err.code = errorCode; + err[kStatusCode] = statusCode; + return err; + } +} + +module.exports = Receiver; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/sender.js b/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/sender.js new file mode 100644 index 0000000000000000000000000000000000000000..a8b1da3a997767186e4cc29a6d34f42a2c54e3d9 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/sender.js @@ -0,0 +1,602 @@ +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex" }] */ + +'use strict'; + +const { Duplex } = require('stream'); +const { randomFillSync } = require('crypto'); + +const PerMessageDeflate = require('./permessage-deflate'); +const { EMPTY_BUFFER, kWebSocket, NOOP } = require('./constants'); +const { isBlob, isValidStatusCode } = require('./validation'); +const { mask: applyMask, toBuffer } = require('./buffer-util'); + +const kByteLength = Symbol('kByteLength'); +const maskBuffer = Buffer.alloc(4); +const RANDOM_POOL_SIZE = 8 * 1024; +let randomPool; +let randomPoolPointer = RANDOM_POOL_SIZE; + +const DEFAULT = 0; +const DEFLATING = 1; +const GET_BLOB_DATA = 2; + +/** + * HyBi Sender implementation. + */ +class Sender { + /** + * Creates a Sender instance. + * + * @param {Duplex} socket The connection socket + * @param {Object} [extensions] An object containing the negotiated extensions + * @param {Function} [generateMask] The function used to generate the masking + * key + */ + constructor(socket, extensions, generateMask) { + this._extensions = extensions || {}; + + if (generateMask) { + this._generateMask = generateMask; + this._maskBuffer = Buffer.alloc(4); + } + + this._socket = socket; + + this._firstFragment = true; + this._compress = false; + + this._bufferedBytes = 0; + this._queue = []; + this._state = DEFAULT; + this.onerror = NOOP; + this[kWebSocket] = undefined; + } + + /** + * Frames a piece of data according to the HyBi WebSocket protocol. + * + * @param {(Buffer|String)} data The data to frame + * @param {Object} options Options object + * @param {Boolean} [options.fin=false] Specifies whether or not to set the + * FIN bit + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Buffer} [options.maskBuffer] The buffer used to store the masking + * key + * @param {Number} options.opcode The opcode + * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be + * modified + * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the + * RSV1 bit + * @return {(Buffer|String)[]} The framed data + * @public + */ + static frame(data, options) { + let mask; + let merge = false; + let offset = 2; + let skipMasking = false; + + if (options.mask) { + mask = options.maskBuffer || maskBuffer; + + if (options.generateMask) { + options.generateMask(mask); + } else { + if (randomPoolPointer === RANDOM_POOL_SIZE) { + /* istanbul ignore else */ + if (randomPool === undefined) { + // + // This is lazily initialized because server-sent frames must not + // be masked so it may never be used. + // + randomPool = Buffer.alloc(RANDOM_POOL_SIZE); + } + + randomFillSync(randomPool, 0, RANDOM_POOL_SIZE); + randomPoolPointer = 0; + } + + mask[0] = randomPool[randomPoolPointer++]; + mask[1] = randomPool[randomPoolPointer++]; + mask[2] = randomPool[randomPoolPointer++]; + mask[3] = randomPool[randomPoolPointer++]; + } + + skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0; + offset = 6; + } + + let dataLength; + + if (typeof data === 'string') { + if ( + (!options.mask || skipMasking) && + options[kByteLength] !== undefined + ) { + dataLength = options[kByteLength]; + } else { + data = Buffer.from(data); + dataLength = data.length; + } + } else { + dataLength = data.length; + merge = options.mask && options.readOnly && !skipMasking; + } + + let payloadLength = dataLength; + + if (dataLength >= 65536) { + offset += 8; + payloadLength = 127; + } else if (dataLength > 125) { + offset += 2; + payloadLength = 126; + } + + const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset); + + target[0] = options.fin ? options.opcode | 0x80 : options.opcode; + if (options.rsv1) target[0] |= 0x40; + + target[1] = payloadLength; + + if (payloadLength === 126) { + target.writeUInt16BE(dataLength, 2); + } else if (payloadLength === 127) { + target[2] = target[3] = 0; + target.writeUIntBE(dataLength, 4, 6); + } + + if (!options.mask) return [target, data]; + + target[1] |= 0x80; + target[offset - 4] = mask[0]; + target[offset - 3] = mask[1]; + target[offset - 2] = mask[2]; + target[offset - 1] = mask[3]; + + if (skipMasking) return [target, data]; + + if (merge) { + applyMask(data, mask, target, offset, dataLength); + return [target]; + } + + applyMask(data, mask, data, 0, dataLength); + return [target, data]; + } + + /** + * Sends a close message to the other peer. + * + * @param {Number} [code] The status code component of the body + * @param {(String|Buffer)} [data] The message component of the body + * @param {Boolean} [mask=false] Specifies whether or not to mask the message + * @param {Function} [cb] Callback + * @public + */ + close(code, data, mask, cb) { + let buf; + + if (code === undefined) { + buf = EMPTY_BUFFER; + } else if (typeof code !== 'number' || !isValidStatusCode(code)) { + throw new TypeError('First argument must be a valid error code number'); + } else if (data === undefined || !data.length) { + buf = Buffer.allocUnsafe(2); + buf.writeUInt16BE(code, 0); + } else { + const length = Buffer.byteLength(data); + + if (length > 123) { + throw new RangeError('The message must not be greater than 123 bytes'); + } + + buf = Buffer.allocUnsafe(2 + length); + buf.writeUInt16BE(code, 0); + + if (typeof data === 'string') { + buf.write(data, 2); + } else { + buf.set(data, 2); + } + } + + const options = { + [kByteLength]: buf.length, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 0x08, + readOnly: false, + rsv1: false + }; + + if (this._state !== DEFAULT) { + this.enqueue([this.dispatch, buf, false, options, cb]); + } else { + this.sendFrame(Sender.frame(buf, options), cb); + } + } + + /** + * Sends a ping message to the other peer. + * + * @param {*} data The message to send + * @param {Boolean} [mask=false] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback + * @public + */ + ping(data, mask, cb) { + let byteLength; + let readOnly; + + if (typeof data === 'string') { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else if (isBlob(data)) { + byteLength = data.size; + readOnly = false; + } else { + data = toBuffer(data); + byteLength = data.length; + readOnly = toBuffer.readOnly; + } + + if (byteLength > 125) { + throw new RangeError('The data size must not be greater than 125 bytes'); + } + + const options = { + [kByteLength]: byteLength, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 0x09, + readOnly, + rsv1: false + }; + + if (isBlob(data)) { + if (this._state !== DEFAULT) { + this.enqueue([this.getBlobData, data, false, options, cb]); + } else { + this.getBlobData(data, false, options, cb); + } + } else if (this._state !== DEFAULT) { + this.enqueue([this.dispatch, data, false, options, cb]); + } else { + this.sendFrame(Sender.frame(data, options), cb); + } + } + + /** + * Sends a pong message to the other peer. + * + * @param {*} data The message to send + * @param {Boolean} [mask=false] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback + * @public + */ + pong(data, mask, cb) { + let byteLength; + let readOnly; + + if (typeof data === 'string') { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else if (isBlob(data)) { + byteLength = data.size; + readOnly = false; + } else { + data = toBuffer(data); + byteLength = data.length; + readOnly = toBuffer.readOnly; + } + + if (byteLength > 125) { + throw new RangeError('The data size must not be greater than 125 bytes'); + } + + const options = { + [kByteLength]: byteLength, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 0x0a, + readOnly, + rsv1: false + }; + + if (isBlob(data)) { + if (this._state !== DEFAULT) { + this.enqueue([this.getBlobData, data, false, options, cb]); + } else { + this.getBlobData(data, false, options, cb); + } + } else if (this._state !== DEFAULT) { + this.enqueue([this.dispatch, data, false, options, cb]); + } else { + this.sendFrame(Sender.frame(data, options), cb); + } + } + + /** + * Sends a data message to the other peer. + * + * @param {*} data The message to send + * @param {Object} options Options object + * @param {Boolean} [options.binary=false] Specifies whether `data` is binary + * or text + * @param {Boolean} [options.compress=false] Specifies whether or not to + * compress `data` + * @param {Boolean} [options.fin=false] Specifies whether the fragment is the + * last one + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Function} [cb] Callback + * @public + */ + send(data, options, cb) { + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + let opcode = options.binary ? 2 : 1; + let rsv1 = options.compress; + + let byteLength; + let readOnly; + + if (typeof data === 'string') { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else if (isBlob(data)) { + byteLength = data.size; + readOnly = false; + } else { + data = toBuffer(data); + byteLength = data.length; + readOnly = toBuffer.readOnly; + } + + if (this._firstFragment) { + this._firstFragment = false; + if ( + rsv1 && + perMessageDeflate && + perMessageDeflate.params[ + perMessageDeflate._isServer + ? 'server_no_context_takeover' + : 'client_no_context_takeover' + ] + ) { + rsv1 = byteLength >= perMessageDeflate._threshold; + } + this._compress = rsv1; + } else { + rsv1 = false; + opcode = 0; + } + + if (options.fin) this._firstFragment = true; + + const opts = { + [kByteLength]: byteLength, + fin: options.fin, + generateMask: this._generateMask, + mask: options.mask, + maskBuffer: this._maskBuffer, + opcode, + readOnly, + rsv1 + }; + + if (isBlob(data)) { + if (this._state !== DEFAULT) { + this.enqueue([this.getBlobData, data, this._compress, opts, cb]); + } else { + this.getBlobData(data, this._compress, opts, cb); + } + } else if (this._state !== DEFAULT) { + this.enqueue([this.dispatch, data, this._compress, opts, cb]); + } else { + this.dispatch(data, this._compress, opts, cb); + } + } + + /** + * Gets the contents of a blob as binary data. + * + * @param {Blob} blob The blob + * @param {Boolean} [compress=false] Specifies whether or not to compress + * the data + * @param {Object} options Options object + * @param {Boolean} [options.fin=false] Specifies whether or not to set the + * FIN bit + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Buffer} [options.maskBuffer] The buffer used to store the masking + * key + * @param {Number} options.opcode The opcode + * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be + * modified + * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the + * RSV1 bit + * @param {Function} [cb] Callback + * @private + */ + getBlobData(blob, compress, options, cb) { + this._bufferedBytes += options[kByteLength]; + this._state = GET_BLOB_DATA; + + blob + .arrayBuffer() + .then((arrayBuffer) => { + if (this._socket.destroyed) { + const err = new Error( + 'The socket was closed while the blob was being read' + ); + + // + // `callCallbacks` is called in the next tick to ensure that errors + // that might be thrown in the callbacks behave like errors thrown + // outside the promise chain. + // + process.nextTick(callCallbacks, this, err, cb); + return; + } + + this._bufferedBytes -= options[kByteLength]; + const data = toBuffer(arrayBuffer); + + if (!compress) { + this._state = DEFAULT; + this.sendFrame(Sender.frame(data, options), cb); + this.dequeue(); + } else { + this.dispatch(data, compress, options, cb); + } + }) + .catch((err) => { + // + // `onError` is called in the next tick for the same reason that + // `callCallbacks` above is. + // + process.nextTick(onError, this, err, cb); + }); + } + + /** + * Dispatches a message. + * + * @param {(Buffer|String)} data The message to send + * @param {Boolean} [compress=false] Specifies whether or not to compress + * `data` + * @param {Object} options Options object + * @param {Boolean} [options.fin=false] Specifies whether or not to set the + * FIN bit + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Buffer} [options.maskBuffer] The buffer used to store the masking + * key + * @param {Number} options.opcode The opcode + * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be + * modified + * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the + * RSV1 bit + * @param {Function} [cb] Callback + * @private + */ + dispatch(data, compress, options, cb) { + if (!compress) { + this.sendFrame(Sender.frame(data, options), cb); + return; + } + + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + + this._bufferedBytes += options[kByteLength]; + this._state = DEFLATING; + perMessageDeflate.compress(data, options.fin, (_, buf) => { + if (this._socket.destroyed) { + const err = new Error( + 'The socket was closed while data was being compressed' + ); + + callCallbacks(this, err, cb); + return; + } + + this._bufferedBytes -= options[kByteLength]; + this._state = DEFAULT; + options.readOnly = false; + this.sendFrame(Sender.frame(buf, options), cb); + this.dequeue(); + }); + } + + /** + * Executes queued send operations. + * + * @private + */ + dequeue() { + while (this._state === DEFAULT && this._queue.length) { + const params = this._queue.shift(); + + this._bufferedBytes -= params[3][kByteLength]; + Reflect.apply(params[0], this, params.slice(1)); + } + } + + /** + * Enqueues a send operation. + * + * @param {Array} params Send operation parameters. + * @private + */ + enqueue(params) { + this._bufferedBytes += params[3][kByteLength]; + this._queue.push(params); + } + + /** + * Sends a frame. + * + * @param {(Buffer | String)[]} list The frame to send + * @param {Function} [cb] Callback + * @private + */ + sendFrame(list, cb) { + if (list.length === 2) { + this._socket.cork(); + this._socket.write(list[0]); + this._socket.write(list[1], cb); + this._socket.uncork(); + } else { + this._socket.write(list[0], cb); + } + } +} + +module.exports = Sender; + +/** + * Calls queued callbacks with an error. + * + * @param {Sender} sender The `Sender` instance + * @param {Error} err The error to call the callbacks with + * @param {Function} [cb] The first callback + * @private + */ +function callCallbacks(sender, err, cb) { + if (typeof cb === 'function') cb(err); + + for (let i = 0; i < sender._queue.length; i++) { + const params = sender._queue[i]; + const callback = params[params.length - 1]; + + if (typeof callback === 'function') callback(err); + } +} + +/** + * Handles a `Sender` error. + * + * @param {Sender} sender The `Sender` instance + * @param {Error} err The error + * @param {Function} [cb] The first pending callback + * @private + */ +function onError(sender, err, cb) { + callCallbacks(sender, err, cb); + sender.onerror(err); +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/stream.js b/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/stream.js new file mode 100644 index 0000000000000000000000000000000000000000..4c58c911bc3da49c9b2610da77ff61b71f111810 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/stream.js @@ -0,0 +1,161 @@ +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^WebSocket$" }] */ +'use strict'; + +const WebSocket = require('./websocket'); +const { Duplex } = require('stream'); + +/** + * Emits the `'close'` event on a stream. + * + * @param {Duplex} stream The stream. + * @private + */ +function emitClose(stream) { + stream.emit('close'); +} + +/** + * The listener of the `'end'` event. + * + * @private + */ +function duplexOnEnd() { + if (!this.destroyed && this._writableState.finished) { + this.destroy(); + } +} + +/** + * The listener of the `'error'` event. + * + * @param {Error} err The error + * @private + */ +function duplexOnError(err) { + this.removeListener('error', duplexOnError); + this.destroy(); + if (this.listenerCount('error') === 0) { + // Do not suppress the throwing behavior. + this.emit('error', err); + } +} + +/** + * Wraps a `WebSocket` in a duplex stream. + * + * @param {WebSocket} ws The `WebSocket` to wrap + * @param {Object} [options] The options for the `Duplex` constructor + * @return {Duplex} The duplex stream + * @public + */ +function createWebSocketStream(ws, options) { + let terminateOnDestroy = true; + + const duplex = new Duplex({ + ...options, + autoDestroy: false, + emitClose: false, + objectMode: false, + writableObjectMode: false + }); + + ws.on('message', function message(msg, isBinary) { + const data = + !isBinary && duplex._readableState.objectMode ? msg.toString() : msg; + + if (!duplex.push(data)) ws.pause(); + }); + + ws.once('error', function error(err) { + if (duplex.destroyed) return; + + // Prevent `ws.terminate()` from being called by `duplex._destroy()`. + // + // - If the `'error'` event is emitted before the `'open'` event, then + // `ws.terminate()` is a noop as no socket is assigned. + // - Otherwise, the error is re-emitted by the listener of the `'error'` + // event of the `Receiver` object. The listener already closes the + // connection by calling `ws.close()`. This allows a close frame to be + // sent to the other peer. If `ws.terminate()` is called right after this, + // then the close frame might not be sent. + terminateOnDestroy = false; + duplex.destroy(err); + }); + + ws.once('close', function close() { + if (duplex.destroyed) return; + + duplex.push(null); + }); + + duplex._destroy = function (err, callback) { + if (ws.readyState === ws.CLOSED) { + callback(err); + process.nextTick(emitClose, duplex); + return; + } + + let called = false; + + ws.once('error', function error(err) { + called = true; + callback(err); + }); + + ws.once('close', function close() { + if (!called) callback(err); + process.nextTick(emitClose, duplex); + }); + + if (terminateOnDestroy) ws.terminate(); + }; + + duplex._final = function (callback) { + if (ws.readyState === ws.CONNECTING) { + ws.once('open', function open() { + duplex._final(callback); + }); + return; + } + + // If the value of the `_socket` property is `null` it means that `ws` is a + // client websocket and the handshake failed. In fact, when this happens, a + // socket is never assigned to the websocket. Wait for the `'error'` event + // that will be emitted by the websocket. + if (ws._socket === null) return; + + if (ws._socket._writableState.finished) { + callback(); + if (duplex._readableState.endEmitted) duplex.destroy(); + } else { + ws._socket.once('finish', function finish() { + // `duplex` is not destroyed here because the `'end'` event will be + // emitted on `duplex` after this `'finish'` event. The EOF signaling + // `null` chunk is, in fact, pushed when the websocket emits `'close'`. + callback(); + }); + ws.close(); + } + }; + + duplex._read = function () { + if (ws.isPaused) ws.resume(); + }; + + duplex._write = function (chunk, encoding, callback) { + if (ws.readyState === ws.CONNECTING) { + ws.once('open', function open() { + duplex._write(chunk, encoding, callback); + }); + return; + } + + ws.send(chunk, callback); + }; + + duplex.on('end', duplexOnEnd); + duplex.on('error', duplexOnError); + return duplex; +} + +module.exports = createWebSocketStream; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/subprotocol.js b/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/subprotocol.js new file mode 100644 index 0000000000000000000000000000000000000000..d4381e8864fd055e81dd75eeb4b852d9da864673 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/subprotocol.js @@ -0,0 +1,62 @@ +'use strict'; + +const { tokenChars } = require('./validation'); + +/** + * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names. + * + * @param {String} header The field value of the header + * @return {Set} The subprotocol names + * @public + */ +function parse(header) { + const protocols = new Set(); + let start = -1; + let end = -1; + let i = 0; + + for (i; i < header.length; i++) { + const code = header.charCodeAt(i); + + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if ( + i !== 0 && + (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */ + ) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x2c /* ',' */) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + + const protocol = header.slice(start, end); + + if (protocols.has(protocol)) { + throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); + } + + protocols.add(protocol); + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } + + if (start === -1 || end !== -1) { + throw new SyntaxError('Unexpected end of input'); + } + + const protocol = header.slice(start, i); + + if (protocols.has(protocol)) { + throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); + } + + protocols.add(protocol); + return protocols; +} + +module.exports = { parse }; diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/validation.js b/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/validation.js new file mode 100644 index 0000000000000000000000000000000000000000..4a2e68d5127279431a74b6961e8d35161d3276e2 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/validation.js @@ -0,0 +1,152 @@ +'use strict'; + +const { isUtf8 } = require('buffer'); + +const { hasBlob } = require('./constants'); + +// +// Allowed token characters: +// +// '!', '#', '$', '%', '&', ''', '*', '+', '-', +// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~' +// +// tokenChars[32] === 0 // ' ' +// tokenChars[33] === 1 // '!' +// tokenChars[34] === 0 // '"' +// ... +// +// prettier-ignore +const tokenChars = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31 + 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63 + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127 +]; + +/** + * Checks if a status code is allowed in a close frame. + * + * @param {Number} code The status code + * @return {Boolean} `true` if the status code is valid, else `false` + * @public + */ +function isValidStatusCode(code) { + return ( + (code >= 1000 && + code <= 1014 && + code !== 1004 && + code !== 1005 && + code !== 1006) || + (code >= 3000 && code <= 4999) + ); +} + +/** + * Checks if a given buffer contains only correct UTF-8. + * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by + * Markus Kuhn. + * + * @param {Buffer} buf The buffer to check + * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false` + * @public + */ +function _isValidUTF8(buf) { + const len = buf.length; + let i = 0; + + while (i < len) { + if ((buf[i] & 0x80) === 0) { + // 0xxxxxxx + i++; + } else if ((buf[i] & 0xe0) === 0xc0) { + // 110xxxxx 10xxxxxx + if ( + i + 1 === len || + (buf[i + 1] & 0xc0) !== 0x80 || + (buf[i] & 0xfe) === 0xc0 // Overlong + ) { + return false; + } + + i += 2; + } else if ((buf[i] & 0xf0) === 0xe0) { + // 1110xxxx 10xxxxxx 10xxxxxx + if ( + i + 2 >= len || + (buf[i + 1] & 0xc0) !== 0x80 || + (buf[i + 2] & 0xc0) !== 0x80 || + (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong + (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF) + ) { + return false; + } + + i += 3; + } else if ((buf[i] & 0xf8) === 0xf0) { + // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + if ( + i + 3 >= len || + (buf[i + 1] & 0xc0) !== 0x80 || + (buf[i + 2] & 0xc0) !== 0x80 || + (buf[i + 3] & 0xc0) !== 0x80 || + (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong + (buf[i] === 0xf4 && buf[i + 1] > 0x8f) || + buf[i] > 0xf4 // > U+10FFFF + ) { + return false; + } + + i += 4; + } else { + return false; + } + } + + return true; +} + +/** + * Determines whether a value is a `Blob`. + * + * @param {*} value The value to be tested + * @return {Boolean} `true` if `value` is a `Blob`, else `false` + * @private + */ +function isBlob(value) { + return ( + hasBlob && + typeof value === 'object' && + typeof value.arrayBuffer === 'function' && + typeof value.type === 'string' && + typeof value.stream === 'function' && + (value[Symbol.toStringTag] === 'Blob' || + value[Symbol.toStringTag] === 'File') + ); +} + +module.exports = { + isBlob, + isValidStatusCode, + isValidUTF8: _isValidUTF8, + tokenChars +}; + +if (isUtf8) { + module.exports.isValidUTF8 = function (buf) { + return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf); + }; +} /* istanbul ignore else */ else if (!process.env.WS_NO_UTF_8_VALIDATE) { + try { + const isValidUTF8 = require('utf-8-validate'); + + module.exports.isValidUTF8 = function (buf) { + return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf); + }; + } catch (e) { + // Continue regardless of the error. + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/websocket-server.js b/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/websocket-server.js new file mode 100644 index 0000000000000000000000000000000000000000..33e09858cbe0e34b4f137b49b570a543bc5371d4 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/websocket-server.js @@ -0,0 +1,550 @@ +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex$", "caughtErrors": "none" }] */ + +'use strict'; + +const EventEmitter = require('events'); +const http = require('http'); +const { Duplex } = require('stream'); +const { createHash } = require('crypto'); + +const extension = require('./extension'); +const PerMessageDeflate = require('./permessage-deflate'); +const subprotocol = require('./subprotocol'); +const WebSocket = require('./websocket'); +const { GUID, kWebSocket } = require('./constants'); + +const keyRegex = /^[+/0-9A-Za-z]{22}==$/; + +const RUNNING = 0; +const CLOSING = 1; +const CLOSED = 2; + +/** + * Class representing a WebSocket server. + * + * @extends EventEmitter + */ +class WebSocketServer extends EventEmitter { + /** + * Create a `WebSocketServer` instance. + * + * @param {Object} options Configuration options + * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether + * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted + * multiple times in the same tick + * @param {Boolean} [options.autoPong=true] Specifies whether or not to + * automatically send a pong in response to a ping + * @param {Number} [options.backlog=511] The maximum length of the queue of + * pending connections + * @param {Boolean} [options.clientTracking=true] Specifies whether or not to + * track clients + * @param {Function} [options.handleProtocols] A hook to handle protocols + * @param {String} [options.host] The hostname where to bind the server + * @param {Number} [options.maxPayload=104857600] The maximum allowed message + * size + * @param {Boolean} [options.noServer=false] Enable no server mode + * @param {String} [options.path] Accept only connections matching this path + * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable + * permessage-deflate + * @param {Number} [options.port] The port where to bind the server + * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S + * server to use + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @param {Function} [options.verifyClient] A hook to reject connections + * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket` + * class to use. It must be the `WebSocket` class or class that extends it + * @param {Function} [callback] A listener for the `listening` event + */ + constructor(options, callback) { + super(); + + options = { + allowSynchronousEvents: true, + autoPong: true, + maxPayload: 100 * 1024 * 1024, + skipUTF8Validation: false, + perMessageDeflate: false, + handleProtocols: null, + clientTracking: true, + verifyClient: null, + noServer: false, + backlog: null, // use default (511 as implemented in net.js) + server: null, + host: null, + path: null, + port: null, + WebSocket, + ...options + }; + + if ( + (options.port == null && !options.server && !options.noServer) || + (options.port != null && (options.server || options.noServer)) || + (options.server && options.noServer) + ) { + throw new TypeError( + 'One and only one of the "port", "server", or "noServer" options ' + + 'must be specified' + ); + } + + if (options.port != null) { + this._server = http.createServer((req, res) => { + const body = http.STATUS_CODES[426]; + + res.writeHead(426, { + 'Content-Length': body.length, + 'Content-Type': 'text/plain' + }); + res.end(body); + }); + this._server.listen( + options.port, + options.host, + options.backlog, + callback + ); + } else if (options.server) { + this._server = options.server; + } + + if (this._server) { + const emitConnection = this.emit.bind(this, 'connection'); + + this._removeListeners = addListeners(this._server, { + listening: this.emit.bind(this, 'listening'), + error: this.emit.bind(this, 'error'), + upgrade: (req, socket, head) => { + this.handleUpgrade(req, socket, head, emitConnection); + } + }); + } + + if (options.perMessageDeflate === true) options.perMessageDeflate = {}; + if (options.clientTracking) { + this.clients = new Set(); + this._shouldEmitClose = false; + } + + this.options = options; + this._state = RUNNING; + } + + /** + * Returns the bound address, the address family name, and port of the server + * as reported by the operating system if listening on an IP socket. + * If the server is listening on a pipe or UNIX domain socket, the name is + * returned as a string. + * + * @return {(Object|String|null)} The address of the server + * @public + */ + address() { + if (this.options.noServer) { + throw new Error('The server is operating in "noServer" mode'); + } + + if (!this._server) return null; + return this._server.address(); + } + + /** + * Stop the server from accepting new connections and emit the `'close'` event + * when all existing connections are closed. + * + * @param {Function} [cb] A one-time listener for the `'close'` event + * @public + */ + close(cb) { + if (this._state === CLOSED) { + if (cb) { + this.once('close', () => { + cb(new Error('The server is not running')); + }); + } + + process.nextTick(emitClose, this); + return; + } + + if (cb) this.once('close', cb); + + if (this._state === CLOSING) return; + this._state = CLOSING; + + if (this.options.noServer || this.options.server) { + if (this._server) { + this._removeListeners(); + this._removeListeners = this._server = null; + } + + if (this.clients) { + if (!this.clients.size) { + process.nextTick(emitClose, this); + } else { + this._shouldEmitClose = true; + } + } else { + process.nextTick(emitClose, this); + } + } else { + const server = this._server; + + this._removeListeners(); + this._removeListeners = this._server = null; + + // + // The HTTP/S server was created internally. Close it, and rely on its + // `'close'` event. + // + server.close(() => { + emitClose(this); + }); + } + } + + /** + * See if a given request should be handled by this server instance. + * + * @param {http.IncomingMessage} req Request object to inspect + * @return {Boolean} `true` if the request is valid, else `false` + * @public + */ + shouldHandle(req) { + if (this.options.path) { + const index = req.url.indexOf('?'); + const pathname = index !== -1 ? req.url.slice(0, index) : req.url; + + if (pathname !== this.options.path) return false; + } + + return true; + } + + /** + * Handle a HTTP Upgrade request. + * + * @param {http.IncomingMessage} req The request object + * @param {Duplex} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Function} cb Callback + * @public + */ + handleUpgrade(req, socket, head, cb) { + socket.on('error', socketOnError); + + const key = req.headers['sec-websocket-key']; + const upgrade = req.headers.upgrade; + const version = +req.headers['sec-websocket-version']; + + if (req.method !== 'GET') { + const message = 'Invalid HTTP method'; + abortHandshakeOrEmitwsClientError(this, req, socket, 405, message); + return; + } + + if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') { + const message = 'Invalid Upgrade header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + + if (key === undefined || !keyRegex.test(key)) { + const message = 'Missing or invalid Sec-WebSocket-Key header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + + if (version !== 13 && version !== 8) { + const message = 'Missing or invalid Sec-WebSocket-Version header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, { + 'Sec-WebSocket-Version': '13, 8' + }); + return; + } + + if (!this.shouldHandle(req)) { + abortHandshake(socket, 400); + return; + } + + const secWebSocketProtocol = req.headers['sec-websocket-protocol']; + let protocols = new Set(); + + if (secWebSocketProtocol !== undefined) { + try { + protocols = subprotocol.parse(secWebSocketProtocol); + } catch (err) { + const message = 'Invalid Sec-WebSocket-Protocol header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + } + + const secWebSocketExtensions = req.headers['sec-websocket-extensions']; + const extensions = {}; + + if ( + this.options.perMessageDeflate && + secWebSocketExtensions !== undefined + ) { + const perMessageDeflate = new PerMessageDeflate( + this.options.perMessageDeflate, + true, + this.options.maxPayload + ); + + try { + const offers = extension.parse(secWebSocketExtensions); + + if (offers[PerMessageDeflate.extensionName]) { + perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]); + extensions[PerMessageDeflate.extensionName] = perMessageDeflate; + } + } catch (err) { + const message = + 'Invalid or unacceptable Sec-WebSocket-Extensions header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + } + + // + // Optionally call external client verification handler. + // + if (this.options.verifyClient) { + const info = { + origin: + req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`], + secure: !!(req.socket.authorized || req.socket.encrypted), + req + }; + + if (this.options.verifyClient.length === 2) { + this.options.verifyClient(info, (verified, code, message, headers) => { + if (!verified) { + return abortHandshake(socket, code || 401, message, headers); + } + + this.completeUpgrade( + extensions, + key, + protocols, + req, + socket, + head, + cb + ); + }); + return; + } + + if (!this.options.verifyClient(info)) return abortHandshake(socket, 401); + } + + this.completeUpgrade(extensions, key, protocols, req, socket, head, cb); + } + + /** + * Upgrade the connection to WebSocket. + * + * @param {Object} extensions The accepted extensions + * @param {String} key The value of the `Sec-WebSocket-Key` header + * @param {Set} protocols The subprotocols + * @param {http.IncomingMessage} req The request object + * @param {Duplex} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Function} cb Callback + * @throws {Error} If called more than once with the same socket + * @private + */ + completeUpgrade(extensions, key, protocols, req, socket, head, cb) { + // + // Destroy the socket if the client has already sent a FIN packet. + // + if (!socket.readable || !socket.writable) return socket.destroy(); + + if (socket[kWebSocket]) { + throw new Error( + 'server.handleUpgrade() was called more than once with the same ' + + 'socket, possibly due to a misconfiguration' + ); + } + + if (this._state > RUNNING) return abortHandshake(socket, 503); + + const digest = createHash('sha1') + .update(key + GUID) + .digest('base64'); + + const headers = [ + 'HTTP/1.1 101 Switching Protocols', + 'Upgrade: websocket', + 'Connection: Upgrade', + `Sec-WebSocket-Accept: ${digest}` + ]; + + const ws = new this.options.WebSocket(null, undefined, this.options); + + if (protocols.size) { + // + // Optionally call external protocol selection handler. + // + const protocol = this.options.handleProtocols + ? this.options.handleProtocols(protocols, req) + : protocols.values().next().value; + + if (protocol) { + headers.push(`Sec-WebSocket-Protocol: ${protocol}`); + ws._protocol = protocol; + } + } + + if (extensions[PerMessageDeflate.extensionName]) { + const params = extensions[PerMessageDeflate.extensionName].params; + const value = extension.format({ + [PerMessageDeflate.extensionName]: [params] + }); + headers.push(`Sec-WebSocket-Extensions: ${value}`); + ws._extensions = extensions; + } + + // + // Allow external modification/inspection of handshake headers. + // + this.emit('headers', headers, req); + + socket.write(headers.concat('\r\n').join('\r\n')); + socket.removeListener('error', socketOnError); + + ws.setSocket(socket, head, { + allowSynchronousEvents: this.options.allowSynchronousEvents, + maxPayload: this.options.maxPayload, + skipUTF8Validation: this.options.skipUTF8Validation + }); + + if (this.clients) { + this.clients.add(ws); + ws.on('close', () => { + this.clients.delete(ws); + + if (this._shouldEmitClose && !this.clients.size) { + process.nextTick(emitClose, this); + } + }); + } + + cb(ws, req); + } +} + +module.exports = WebSocketServer; + +/** + * Add event listeners on an `EventEmitter` using a map of + * pairs. + * + * @param {EventEmitter} server The event emitter + * @param {Object.} map The listeners to add + * @return {Function} A function that will remove the added listeners when + * called + * @private + */ +function addListeners(server, map) { + for (const event of Object.keys(map)) server.on(event, map[event]); + + return function removeListeners() { + for (const event of Object.keys(map)) { + server.removeListener(event, map[event]); + } + }; +} + +/** + * Emit a `'close'` event on an `EventEmitter`. + * + * @param {EventEmitter} server The event emitter + * @private + */ +function emitClose(server) { + server._state = CLOSED; + server.emit('close'); +} + +/** + * Handle socket errors. + * + * @private + */ +function socketOnError() { + this.destroy(); +} + +/** + * Close the connection when preconditions are not fulfilled. + * + * @param {Duplex} socket The socket of the upgrade request + * @param {Number} code The HTTP response status code + * @param {String} [message] The HTTP response body + * @param {Object} [headers] Additional HTTP response headers + * @private + */ +function abortHandshake(socket, code, message, headers) { + // + // The socket is writable unless the user destroyed or ended it before calling + // `server.handleUpgrade()` or in the `verifyClient` function, which is a user + // error. Handling this does not make much sense as the worst that can happen + // is that some of the data written by the user might be discarded due to the + // call to `socket.end()` below, which triggers an `'error'` event that in + // turn causes the socket to be destroyed. + // + message = message || http.STATUS_CODES[code]; + headers = { + Connection: 'close', + 'Content-Type': 'text/html', + 'Content-Length': Buffer.byteLength(message), + ...headers + }; + + socket.once('finish', socket.destroy); + + socket.end( + `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` + + Object.keys(headers) + .map((h) => `${h}: ${headers[h]}`) + .join('\r\n') + + '\r\n\r\n' + + message + ); +} + +/** + * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least + * one listener for it, otherwise call `abortHandshake()`. + * + * @param {WebSocketServer} server The WebSocket server + * @param {http.IncomingMessage} req The request object + * @param {Duplex} socket The socket of the upgrade request + * @param {Number} code The HTTP response status code + * @param {String} message The HTTP response body + * @param {Object} [headers] The HTTP response headers + * @private + */ +function abortHandshakeOrEmitwsClientError( + server, + req, + socket, + code, + message, + headers +) { + if (server.listenerCount('wsClientError')) { + const err = new Error(message); + Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError); + + server.emit('wsClientError', err, socket, req); + } else { + abortHandshake(socket, code, message, headers); + } +} diff --git a/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/websocket.js b/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/websocket.js new file mode 100644 index 0000000000000000000000000000000000000000..ad8764a0273e9ec83f94d9d306f982d65cba2cd3 --- /dev/null +++ b/novas/novacore-zephyr/claude-code-router/node_modules/ws/lib/websocket.js @@ -0,0 +1,1388 @@ +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex|Readable$", "caughtErrors": "none" }] */ + +'use strict'; + +const EventEmitter = require('events'); +const https = require('https'); +const http = require('http'); +const net = require('net'); +const tls = require('tls'); +const { randomBytes, createHash } = require('crypto'); +const { Duplex, Readable } = require('stream'); +const { URL } = require('url'); + +const PerMessageDeflate = require('./permessage-deflate'); +const Receiver = require('./receiver'); +const Sender = require('./sender'); +const { isBlob } = require('./validation'); + +const { + BINARY_TYPES, + EMPTY_BUFFER, + GUID, + kForOnEventAttribute, + kListener, + kStatusCode, + kWebSocket, + NOOP +} = require('./constants'); +const { + EventTarget: { addEventListener, removeEventListener } +} = require('./event-target'); +const { format, parse } = require('./extension'); +const { toBuffer } = require('./buffer-util'); + +const closeTimeout = 30 * 1000; +const kAborted = Symbol('kAborted'); +const protocolVersions = [8, 13]; +const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED']; +const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/; + +/** + * Class representing a WebSocket. + * + * @extends EventEmitter + */ +class WebSocket extends EventEmitter { + /** + * Create a new `WebSocket`. + * + * @param {(String|URL)} address The URL to which to connect + * @param {(String|String[])} [protocols] The subprotocols + * @param {Object} [options] Connection options + */ + constructor(address, protocols, options) { + super(); + + this._binaryType = BINARY_TYPES[0]; + this._closeCode = 1006; + this._closeFrameReceived = false; + this._closeFrameSent = false; + this._closeMessage = EMPTY_BUFFER; + this._closeTimer = null; + this._errorEmitted = false; + this._extensions = {}; + this._paused = false; + this._protocol = ''; + this._readyState = WebSocket.CONNECTING; + this._receiver = null; + this._sender = null; + this._socket = null; + + if (address !== null) { + this._bufferedAmount = 0; + this._isServer = false; + this._redirects = 0; + + if (protocols === undefined) { + protocols = []; + } else if (!Array.isArray(protocols)) { + if (typeof protocols === 'object' && protocols !== null) { + options = protocols; + protocols = []; + } else { + protocols = [protocols]; + } + } + + initAsClient(this, address, protocols, options); + } else { + this._autoPong = options.autoPong; + this._isServer = true; + } + } + + /** + * For historical reasons, the custom "nodebuffer" type is used by the default + * instead of "blob". + * + * @type {String} + */ + get binaryType() { + return this._binaryType; + } + + set binaryType(type) { + if (!BINARY_TYPES.includes(type)) return; + + this._binaryType = type; + + // + // Allow to change `binaryType` on the fly. + // + if (this._receiver) this._receiver._binaryType = type; + } + + /** + * @type {Number} + */ + get bufferedAmount() { + if (!this._socket) return this._bufferedAmount; + + return this._socket._writableState.length + this._sender._bufferedBytes; + } + + /** + * @type {String} + */ + get extensions() { + return Object.keys(this._extensions).join(); + } + + /** + * @type {Boolean} + */ + get isPaused() { + return this._paused; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onclose() { + return null; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onerror() { + return null; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onopen() { + return null; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onmessage() { + return null; + } + + /** + * @type {String} + */ + get protocol() { + return this._protocol; + } + + /** + * @type {Number} + */ + get readyState() { + return this._readyState; + } + + /** + * @type {String} + */ + get url() { + return this._url; + } + + /** + * Set up the socket and the internal resources. + * + * @param {Duplex} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Object} options Options object + * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether + * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted + * multiple times in the same tick + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Number} [options.maxPayload=0] The maximum allowed message size + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @private + */ + setSocket(socket, head, options) { + const receiver = new Receiver({ + allowSynchronousEvents: options.allowSynchronousEvents, + binaryType: this.binaryType, + extensions: this._extensions, + isServer: this._isServer, + maxPayload: options.maxPayload, + skipUTF8Validation: options.skipUTF8Validation + }); + + const sender = new Sender(socket, this._extensions, options.generateMask); + + this._receiver = receiver; + this._sender = sender; + this._socket = socket; + + receiver[kWebSocket] = this; + sender[kWebSocket] = this; + socket[kWebSocket] = this; + + receiver.on('conclude', receiverOnConclude); + receiver.on('drain', receiverOnDrain); + receiver.on('error', receiverOnError); + receiver.on('message', receiverOnMessage); + receiver.on('ping', receiverOnPing); + receiver.on('pong', receiverOnPong); + + sender.onerror = senderOnError; + + // + // These methods may not be available if `socket` is just a `Duplex`. + // + if (socket.setTimeout) socket.setTimeout(0); + if (socket.setNoDelay) socket.setNoDelay(); + + if (head.length > 0) socket.unshift(head); + + socket.on('close', socketOnClose); + socket.on('data', socketOnData); + socket.on('end', socketOnEnd); + socket.on('error', socketOnError); + + this._readyState = WebSocket.OPEN; + this.emit('open'); + } + + /** + * Emit the `'close'` event. + * + * @private + */ + emitClose() { + if (!this._socket) { + this._readyState = WebSocket.CLOSED; + this.emit('close', this._closeCode, this._closeMessage); + return; + } + + if (this._extensions[PerMessageDeflate.extensionName]) { + this._extensions[PerMessageDeflate.extensionName].cleanup(); + } + + this._receiver.removeAllListeners(); + this._readyState = WebSocket.CLOSED; + this.emit('close', this._closeCode, this._closeMessage); + } + + /** + * Start a closing handshake. + * + * +----------+ +-----------+ +----------+ + * - - -|ws.close()|-->|close frame|-->|ws.close()|- - - + * | +----------+ +-----------+ +----------+ | + * +----------+ +-----------+ | + * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING + * +----------+ +-----------+ | + * | | | +---+ | + * +------------------------+-->|fin| - - - - + * | +---+ | +---+ + * - - - - -|fin|<---------------------+ + * +---+ + * + * @param {Number} [code] Status code explaining why the connection is closing + * @param {(String|Buffer)} [data] The reason why the connection is + * closing + * @public + */ + close(code, data) { + if (this.readyState === WebSocket.CLOSED) return; + if (this.readyState === WebSocket.CONNECTING) { + const msg = 'WebSocket was closed before the connection was established'; + abortHandshake(this, this._req, msg); + return; + } + + if (this.readyState === WebSocket.CLOSING) { + if ( + this._closeFrameSent && + (this._closeFrameReceived || this._receiver._writableState.errorEmitted) + ) { + this._socket.end(); + } + + return; + } + + this._readyState = WebSocket.CLOSING; + this._sender.close(code, data, !this._isServer, (err) => { + // + // This error is handled by the `'error'` listener on the socket. We only + // want to know if the close frame has been sent here. + // + if (err) return; + + this._closeFrameSent = true; + + if ( + this._closeFrameReceived || + this._receiver._writableState.errorEmitted + ) { + this._socket.end(); + } + }); + + setCloseTimer(this); + } + + /** + * Pause the socket. + * + * @public + */ + pause() { + if ( + this.readyState === WebSocket.CONNECTING || + this.readyState === WebSocket.CLOSED + ) { + return; + } + + this._paused = true; + this._socket.pause(); + } + + /** + * Send a ping. + * + * @param {*} [data] The data to send + * @param {Boolean} [mask] Indicates whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when the ping is sent + * @public + */ + ping(data, mask, cb) { + if (this.readyState === WebSocket.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof data === 'function') { + cb = data; + data = mask = undefined; + } else if (typeof mask === 'function') { + cb = mask; + mask = undefined; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + if (mask === undefined) mask = !this._isServer; + this._sender.ping(data || EMPTY_BUFFER, mask, cb); + } + + /** + * Send a pong. + * + * @param {*} [data] The data to send + * @param {Boolean} [mask] Indicates whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when the pong is sent + * @public + */ + pong(data, mask, cb) { + if (this.readyState === WebSocket.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof data === 'function') { + cb = data; + data = mask = undefined; + } else if (typeof mask === 'function') { + cb = mask; + mask = undefined; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + if (mask === undefined) mask = !this._isServer; + this._sender.pong(data || EMPTY_BUFFER, mask, cb); + } + + /** + * Resume the socket. + * + * @public + */ + resume() { + if ( + this.readyState === WebSocket.CONNECTING || + this.readyState === WebSocket.CLOSED + ) { + return; + } + + this._paused = false; + if (!this._receiver._writableState.needDrain) this._socket.resume(); + } + + /** + * Send a data message. + * + * @param {*} data The message to send + * @param {Object} [options] Options object + * @param {Boolean} [options.binary] Specifies whether `data` is binary or + * text + * @param {Boolean} [options.compress] Specifies whether or not to compress + * `data` + * @param {Boolean} [options.fin=true] Specifies whether the fragment is the + * last one + * @param {Boolean} [options.mask] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when data is written out + * @public + */ + send(data, options, cb) { + if (this.readyState === WebSocket.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof options === 'function') { + cb = options; + options = {}; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + const opts = { + binary: typeof data !== 'string', + mask: !this._isServer, + compress: true, + fin: true, + ...options + }; + + if (!this._extensions[PerMessageDeflate.extensionName]) { + opts.compress = false; + } + + this._sender.send(data || EMPTY_BUFFER, opts, cb); + } + + /** + * Forcibly close the connection. + * + * @public + */ + terminate() { + if (this.readyState === WebSocket.CLOSED) return; + if (this.readyState === WebSocket.CONNECTING) { + const msg = 'WebSocket was closed before the connection was established'; + abortHandshake(this, this._req, msg); + return; + } + + if (this._socket) { + this._readyState = WebSocket.CLOSING; + this._socket.destroy(); + } + } +} + +/** + * @constant {Number} CONNECTING + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'CONNECTING', { + enumerable: true, + value: readyStates.indexOf('CONNECTING') +}); + +/** + * @constant {Number} CONNECTING + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'CONNECTING', { + enumerable: true, + value: readyStates.indexOf('CONNECTING') +}); + +/** + * @constant {Number} OPEN + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'OPEN', { + enumerable: true, + value: readyStates.indexOf('OPEN') +}); + +/** + * @constant {Number} OPEN + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'OPEN', { + enumerable: true, + value: readyStates.indexOf('OPEN') +}); + +/** + * @constant {Number} CLOSING + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'CLOSING', { + enumerable: true, + value: readyStates.indexOf('CLOSING') +}); + +/** + * @constant {Number} CLOSING + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'CLOSING', { + enumerable: true, + value: readyStates.indexOf('CLOSING') +}); + +/** + * @constant {Number} CLOSED + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'CLOSED', { + enumerable: true, + value: readyStates.indexOf('CLOSED') +}); + +/** + * @constant {Number} CLOSED + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'CLOSED', { + enumerable: true, + value: readyStates.indexOf('CLOSED') +}); + +[ + 'binaryType', + 'bufferedAmount', + 'extensions', + 'isPaused', + 'protocol', + 'readyState', + 'url' +].forEach((property) => { + Object.defineProperty(WebSocket.prototype, property, { enumerable: true }); +}); + +// +// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes. +// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface +// +['open', 'error', 'close', 'message'].forEach((method) => { + Object.defineProperty(WebSocket.prototype, `on${method}`, { + enumerable: true, + get() { + for (const listener of this.listeners(method)) { + if (listener[kForOnEventAttribute]) return listener[kListener]; + } + + return null; + }, + set(handler) { + for (const listener of this.listeners(method)) { + if (listener[kForOnEventAttribute]) { + this.removeListener(method, listener); + break; + } + } + + if (typeof handler !== 'function') return; + + this.addEventListener(method, handler, { + [kForOnEventAttribute]: true + }); + } + }); +}); + +WebSocket.prototype.addEventListener = addEventListener; +WebSocket.prototype.removeEventListener = removeEventListener; + +module.exports = WebSocket; + +/** + * Initialize a WebSocket client. + * + * @param {WebSocket} websocket The client to initialize + * @param {(String|URL)} address The URL to which to connect + * @param {Array} protocols The subprotocols + * @param {Object} [options] Connection options + * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any + * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple + * times in the same tick + * @param {Boolean} [options.autoPong=true] Specifies whether or not to + * automatically send a pong in response to a ping + * @param {Function} [options.finishRequest] A function which can be used to + * customize the headers of each http request before it is sent + * @param {Boolean} [options.followRedirects=false] Whether or not to follow + * redirects + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the + * handshake request + * @param {Number} [options.maxPayload=104857600] The maximum allowed message + * size + * @param {Number} [options.maxRedirects=10] The maximum number of redirects + * allowed + * @param {String} [options.origin] Value of the `Origin` or + * `Sec-WebSocket-Origin` header + * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable + * permessage-deflate + * @param {Number} [options.protocolVersion=13] Value of the + * `Sec-WebSocket-Version` header + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @private + */ +function initAsClient(websocket, address, protocols, options) { + const opts = { + allowSynchronousEvents: true, + autoPong: true, + protocolVersion: protocolVersions[1], + maxPayload: 100 * 1024 * 1024, + skipUTF8Validation: false, + perMessageDeflate: true, + followRedirects: false, + maxRedirects: 10, + ...options, + socketPath: undefined, + hostname: undefined, + protocol: undefined, + timeout: undefined, + method: 'GET', + host: undefined, + path: undefined, + port: undefined + }; + + websocket._autoPong = opts.autoPong; + + if (!protocolVersions.includes(opts.protocolVersion)) { + throw new RangeError( + `Unsupported protocol version: ${opts.protocolVersion} ` + + `(supported versions: ${protocolVersions.join(', ')})` + ); + } + + let parsedUrl; + + if (address instanceof URL) { + parsedUrl = address; + } else { + try { + parsedUrl = new URL(address); + } catch (e) { + throw new SyntaxError(`Invalid URL: ${address}`); + } + } + + if (parsedUrl.protocol === 'http:') { + parsedUrl.protocol = 'ws:'; + } else if (parsedUrl.protocol === 'https:') { + parsedUrl.protocol = 'wss:'; + } + + websocket._url = parsedUrl.href; + + const isSecure = parsedUrl.protocol === 'wss:'; + const isIpcUrl = parsedUrl.protocol === 'ws+unix:'; + let invalidUrlMessage; + + if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) { + invalidUrlMessage = + 'The URL\'s protocol must be one of "ws:", "wss:", ' + + '"http:", "https:", or "ws+unix:"'; + } else if (isIpcUrl && !parsedUrl.pathname) { + invalidUrlMessage = "The URL's pathname is empty"; + } else if (parsedUrl.hash) { + invalidUrlMessage = 'The URL contains a fragment identifier'; + } + + if (invalidUrlMessage) { + const err = new SyntaxError(invalidUrlMessage); + + if (websocket._redirects === 0) { + throw err; + } else { + emitErrorAndClose(websocket, err); + return; + } + } + + const defaultPort = isSecure ? 443 : 80; + const key = randomBytes(16).toString('base64'); + const request = isSecure ? https.request : http.request; + const protocolSet = new Set(); + let perMessageDeflate; + + opts.createConnection = + opts.createConnection || (isSecure ? tlsConnect : netConnect); + opts.defaultPort = opts.defaultPort || defaultPort; + opts.port = parsedUrl.port || defaultPort; + opts.host = parsedUrl.hostname.startsWith('[') + ? parsedUrl.hostname.slice(1, -1) + : parsedUrl.hostname; + opts.headers = { + ...opts.headers, + 'Sec-WebSocket-Version': opts.protocolVersion, + 'Sec-WebSocket-Key': key, + Connection: 'Upgrade', + Upgrade: 'websocket' + }; + opts.path = parsedUrl.pathname + parsedUrl.search; + opts.timeout = opts.handshakeTimeout; + + if (opts.perMessageDeflate) { + perMessageDeflate = new PerMessageDeflate( + opts.perMessageDeflate !== true ? opts.perMessageDeflate : {}, + false, + opts.maxPayload + ); + opts.headers['Sec-WebSocket-Extensions'] = format({ + [PerMessageDeflate.extensionName]: perMessageDeflate.offer() + }); + } + if (protocols.length) { + for (const protocol of protocols) { + if ( + typeof protocol !== 'string' || + !subprotocolRegex.test(protocol) || + protocolSet.has(protocol) + ) { + throw new SyntaxError( + 'An invalid or duplicated subprotocol was specified' + ); + } + + protocolSet.add(protocol); + } + + opts.headers['Sec-WebSocket-Protocol'] = protocols.join(','); + } + if (opts.origin) { + if (opts.protocolVersion < 13) { + opts.headers['Sec-WebSocket-Origin'] = opts.origin; + } else { + opts.headers.Origin = opts.origin; + } + } + if (parsedUrl.username || parsedUrl.password) { + opts.auth = `${parsedUrl.username}:${parsedUrl.password}`; + } + + if (isIpcUrl) { + const parts = opts.path.split(':'); + + opts.socketPath = parts[0]; + opts.path = parts[1]; + } + + let req; + + if (opts.followRedirects) { + if (websocket._redirects === 0) { + websocket._originalIpc = isIpcUrl; + websocket._originalSecure = isSecure; + websocket._originalHostOrSocketPath = isIpcUrl + ? opts.socketPath + : parsedUrl.host; + + const headers = options && options.headers; + + // + // Shallow copy the user provided options so that headers can be changed + // without mutating the original object. + // + options = { ...options, headers: {} }; + + if (headers) { + for (const [key, value] of Object.entries(headers)) { + options.headers[key.toLowerCase()] = value; + } + } + } else if (websocket.listenerCount('redirect') === 0) { + const isSameHost = isIpcUrl + ? websocket._originalIpc + ? opts.socketPath === websocket._originalHostOrSocketPath + : false + : websocket._originalIpc + ? false + : parsedUrl.host === websocket._originalHostOrSocketPath; + + if (!isSameHost || (websocket._originalSecure && !isSecure)) { + // + // Match curl 7.77.0 behavior and drop the following headers. These + // headers are also dropped when following a redirect to a subdomain. + // + delete opts.headers.authorization; + delete opts.headers.cookie; + + if (!isSameHost) delete opts.headers.host; + + opts.auth = undefined; + } + } + + // + // Match curl 7.77.0 behavior and make the first `Authorization` header win. + // If the `Authorization` header is set, then there is nothing to do as it + // will take precedence. + // + if (opts.auth && !options.headers.authorization) { + options.headers.authorization = + 'Basic ' + Buffer.from(opts.auth).toString('base64'); + } + + req = websocket._req = request(opts); + + if (websocket._redirects) { + // + // Unlike what is done for the `'upgrade'` event, no early exit is + // triggered here if the user calls `websocket.close()` or + // `websocket.terminate()` from a listener of the `'redirect'` event. This + // is because the user can also call `request.destroy()` with an error + // before calling `websocket.close()` or `websocket.terminate()` and this + // would result in an error being emitted on the `request` object with no + // `'error'` event listeners attached. + // + websocket.emit('redirect', websocket.url, req); + } + } else { + req = websocket._req = request(opts); + } + + if (opts.timeout) { + req.on('timeout', () => { + abortHandshake(websocket, req, 'Opening handshake has timed out'); + }); + } + + req.on('error', (err) => { + if (req === null || req[kAborted]) return; + + req = websocket._req = null; + emitErrorAndClose(websocket, err); + }); + + req.on('response', (res) => { + const location = res.headers.location; + const statusCode = res.statusCode; + + if ( + location && + opts.followRedirects && + statusCode >= 300 && + statusCode < 400 + ) { + if (++websocket._redirects > opts.maxRedirects) { + abortHandshake(websocket, req, 'Maximum redirects exceeded'); + return; + } + + req.abort(); + + let addr; + + try { + addr = new URL(location, address); + } catch (e) { + const err = new SyntaxError(`Invalid URL: ${location}`); + emitErrorAndClose(websocket, err); + return; + } + + initAsClient(websocket, addr, protocols, options); + } else if (!websocket.emit('unexpected-response', req, res)) { + abortHandshake( + websocket, + req, + `Unexpected server response: ${res.statusCode}` + ); + } + }); + + req.on('upgrade', (res, socket, head) => { + websocket.emit('upgrade', res); + + // + // The user may have closed the connection from a listener of the + // `'upgrade'` event. + // + if (websocket.readyState !== WebSocket.CONNECTING) return; + + req = websocket._req = null; + + const upgrade = res.headers.upgrade; + + if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') { + abortHandshake(websocket, socket, 'Invalid Upgrade header'); + return; + } + + const digest = createHash('sha1') + .update(key + GUID) + .digest('base64'); + + if (res.headers['sec-websocket-accept'] !== digest) { + abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header'); + return; + } + + const serverProt = res.headers['sec-websocket-protocol']; + let protError; + + if (serverProt !== undefined) { + if (!protocolSet.size) { + protError = 'Server sent a subprotocol but none was requested'; + } else if (!protocolSet.has(serverProt)) { + protError = 'Server sent an invalid subprotocol'; + } + } else if (protocolSet.size) { + protError = 'Server sent no subprotocol'; + } + + if (protError) { + abortHandshake(websocket, socket, protError); + return; + } + + if (serverProt) websocket._protocol = serverProt; + + const secWebSocketExtensions = res.headers['sec-websocket-extensions']; + + if (secWebSocketExtensions !== undefined) { + if (!perMessageDeflate) { + const message = + 'Server sent a Sec-WebSocket-Extensions header but no extension ' + + 'was requested'; + abortHandshake(websocket, socket, message); + return; + } + + let extensions; + + try { + extensions = parse(secWebSocketExtensions); + } catch (err) { + const message = 'Invalid Sec-WebSocket-Extensions header'; + abortHandshake(websocket, socket, message); + return; + } + + const extensionNames = Object.keys(extensions); + + if ( + extensionNames.length !== 1 || + extensionNames[0] !== PerMessageDeflate.extensionName + ) { + const message = 'Server indicated an extension that was not requested'; + abortHandshake(websocket, socket, message); + return; + } + + try { + perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]); + } catch (err) { + const message = 'Invalid Sec-WebSocket-Extensions header'; + abortHandshake(websocket, socket, message); + return; + } + + websocket._extensions[PerMessageDeflate.extensionName] = + perMessageDeflate; + } + + websocket.setSocket(socket, head, { + allowSynchronousEvents: opts.allowSynchronousEvents, + generateMask: opts.generateMask, + maxPayload: opts.maxPayload, + skipUTF8Validation: opts.skipUTF8Validation + }); + }); + + if (opts.finishRequest) { + opts.finishRequest(req, websocket); + } else { + req.end(); + } +} + +/** + * Emit the `'error'` and `'close'` events. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {Error} The error to emit + * @private + */ +function emitErrorAndClose(websocket, err) { + websocket._readyState = WebSocket.CLOSING; + // + // The following assignment is practically useless and is done only for + // consistency. + // + websocket._errorEmitted = true; + websocket.emit('error', err); + websocket.emitClose(); +} + +/** + * Create a `net.Socket` and initiate a connection. + * + * @param {Object} options Connection options + * @return {net.Socket} The newly created socket used to start the connection + * @private + */ +function netConnect(options) { + options.path = options.socketPath; + return net.connect(options); +} + +/** + * Create a `tls.TLSSocket` and initiate a connection. + * + * @param {Object} options Connection options + * @return {tls.TLSSocket} The newly created socket used to start the connection + * @private + */ +function tlsConnect(options) { + options.path = undefined; + + if (!options.servername && options.servername !== '') { + options.servername = net.isIP(options.host) ? '' : options.host; + } + + return tls.connect(options); +} + +/** + * Abort the handshake and emit an error. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to + * abort or the socket to destroy + * @param {String} message The error message + * @private + */ +function abortHandshake(websocket, stream, message) { + websocket._readyState = WebSocket.CLOSING; + + const err = new Error(message); + Error.captureStackTrace(err, abortHandshake); + + if (stream.setHeader) { + stream[kAborted] = true; + stream.abort(); + + if (stream.socket && !stream.socket.destroyed) { + // + // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if + // called after the request completed. See + // https://github.com/websockets/ws/issues/1869. + // + stream.socket.destroy(); + } + + process.nextTick(emitErrorAndClose, websocket, err); + } else { + stream.destroy(err); + stream.once('error', websocket.emit.bind(websocket, 'error')); + stream.once('close', websocket.emitClose.bind(websocket)); + } +} + +/** + * Handle cases where the `ping()`, `pong()`, or `send()` methods are called + * when the `readyState` attribute is `CLOSING` or `CLOSED`. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {*} [data] The data to send + * @param {Function} [cb] Callback + * @private + */ +function sendAfterClose(websocket, data, cb) { + if (data) { + const length = isBlob(data) ? data.size : toBuffer(data).length; + + // + // The `_bufferedAmount` property is used only when the peer is a client and + // the opening handshake fails. Under these circumstances, in fact, the + // `setSocket()` method is not called, so the `_socket` and `_sender` + // properties are set to `null`. + // + if (websocket._socket) websocket._sender._bufferedBytes += length; + else websocket._bufferedAmount += length; + } + + if (cb) { + const err = new Error( + `WebSocket is not open: readyState ${websocket.readyState} ` + + `(${readyStates[websocket.readyState]})` + ); + process.nextTick(cb, err); + } +} + +/** + * The listener of the `Receiver` `'conclude'` event. + * + * @param {Number} code The status code + * @param {Buffer} reason The reason for closing + * @private + */ +function receiverOnConclude(code, reason) { + const websocket = this[kWebSocket]; + + websocket._closeFrameReceived = true; + websocket._closeMessage = reason; + websocket._closeCode = code; + + if (websocket._socket[kWebSocket] === undefined) return; + + websocket._socket.removeListener('data', socketOnData); + process.nextTick(resume, websocket._socket); + + if (code === 1005) websocket.close(); + else websocket.close(code, reason); +} + +/** + * The listener of the `Receiver` `'drain'` event. + * + * @private + */ +function receiverOnDrain() { + const websocket = this[kWebSocket]; + + if (!websocket.isPaused) websocket._socket.resume(); +} + +/** + * The listener of the `Receiver` `'error'` event. + * + * @param {(RangeError|Error)} err The emitted error + * @private + */ +function receiverOnError(err) { + const websocket = this[kWebSocket]; + + if (websocket._socket[kWebSocket] !== undefined) { + websocket._socket.removeListener('data', socketOnData); + + // + // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See + // https://github.com/websockets/ws/issues/1940. + // + process.nextTick(resume, websocket._socket); + + websocket.close(err[kStatusCode]); + } + + if (!websocket._errorEmitted) { + websocket._errorEmitted = true; + websocket.emit('error', err); + } +} + +/** + * The listener of the `Receiver` `'finish'` event. + * + * @private + */ +function receiverOnFinish() { + this[kWebSocket].emitClose(); +} + +/** + * The listener of the `Receiver` `'message'` event. + * + * @param {Buffer|ArrayBuffer|Buffer[])} data The message + * @param {Boolean} isBinary Specifies whether the message is binary or not + * @private + */ +function receiverOnMessage(data, isBinary) { + this[kWebSocket].emit('message', data, isBinary); +} + +/** + * The listener of the `Receiver` `'ping'` event. + * + * @param {Buffer} data The data included in the ping frame + * @private + */ +function receiverOnPing(data) { + const websocket = this[kWebSocket]; + + if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP); + websocket.emit('ping', data); +} + +/** + * The listener of the `Receiver` `'pong'` event. + * + * @param {Buffer} data The data included in the pong frame + * @private + */ +function receiverOnPong(data) { + this[kWebSocket].emit('pong', data); +} + +/** + * Resume a readable stream + * + * @param {Readable} stream The readable stream + * @private + */ +function resume(stream) { + stream.resume(); +} + +/** + * The `Sender` error event handler. + * + * @param {Error} The error + * @private + */ +function senderOnError(err) { + const websocket = this[kWebSocket]; + + if (websocket.readyState === WebSocket.CLOSED) return; + if (websocket.readyState === WebSocket.OPEN) { + websocket._readyState = WebSocket.CLOSING; + setCloseTimer(websocket); + } + + // + // `socket.end()` is used instead of `socket.destroy()` to allow the other + // peer to finish sending queued data. There is no need to set a timer here + // because `CLOSING` means that it is already set or not needed. + // + this._socket.end(); + + if (!websocket._errorEmitted) { + websocket._errorEmitted = true; + websocket.emit('error', err); + } +} + +/** + * Set a timer to destroy the underlying raw socket of a WebSocket. + * + * @param {WebSocket} websocket The WebSocket instance + * @private + */ +function setCloseTimer(websocket) { + websocket._closeTimer = setTimeout( + websocket._socket.destroy.bind(websocket._socket), + closeTimeout + ); +} + +/** + * The listener of the socket `'close'` event. + * + * @private + */ +function socketOnClose() { + const websocket = this[kWebSocket]; + + this.removeListener('close', socketOnClose); + this.removeListener('data', socketOnData); + this.removeListener('end', socketOnEnd); + + websocket._readyState = WebSocket.CLOSING; + + let chunk; + + // + // The close frame might not have been received or the `'end'` event emitted, + // for example, if the socket was destroyed due to an error. Ensure that the + // `receiver` stream is closed after writing any remaining buffered data to + // it. If the readable side of the socket is in flowing mode then there is no + // buffered data as everything has been already written and `readable.read()` + // will return `null`. If instead, the socket is paused, any possible buffered + // data will be read as a single chunk. + // + if ( + !this._readableState.endEmitted && + !websocket._closeFrameReceived && + !websocket._receiver._writableState.errorEmitted && + (chunk = websocket._socket.read()) !== null + ) { + websocket._receiver.write(chunk); + } + + websocket._receiver.end(); + + this[kWebSocket] = undefined; + + clearTimeout(websocket._closeTimer); + + if ( + websocket._receiver._writableState.finished || + websocket._receiver._writableState.errorEmitted + ) { + websocket.emitClose(); + } else { + websocket._receiver.on('error', receiverOnFinish); + websocket._receiver.on('finish', receiverOnFinish); + } +} + +/** + * The listener of the socket `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function socketOnData(chunk) { + if (!this[kWebSocket]._receiver.write(chunk)) { + this.pause(); + } +} + +/** + * The listener of the socket `'end'` event. + * + * @private + */ +function socketOnEnd() { + const websocket = this[kWebSocket]; + + websocket._readyState = WebSocket.CLOSING; + websocket._receiver.end(); + this.end(); +} + +/** + * The listener of the socket `'error'` event. + * + * @private + */ +function socketOnError() { + const websocket = this[kWebSocket]; + + this.removeListener('error', socketOnError); + this.on('error', NOOP); + + if (websocket) { + websocket._readyState = WebSocket.CLOSING; + this.destroy(); + } +}