@langchain/core 1.1.5-dev-1765432861398 → 1.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/agents.cjs +1 -0
- package/agents.d.cts +1 -0
- package/agents.d.ts +1 -0
- package/agents.js +1 -0
- package/caches.cjs +1 -0
- package/caches.d.cts +1 -0
- package/caches.d.ts +1 -0
- package/caches.js +1 -0
- package/callbacks/base.cjs +1 -0
- package/callbacks/base.d.cts +1 -0
- package/callbacks/base.d.ts +1 -0
- package/callbacks/base.js +1 -0
- package/callbacks/dispatch/web.cjs +1 -0
- package/callbacks/dispatch/web.d.cts +1 -0
- package/callbacks/dispatch/web.d.ts +1 -0
- package/callbacks/dispatch/web.js +1 -0
- package/callbacks/dispatch.cjs +1 -0
- package/callbacks/dispatch.d.cts +1 -0
- package/callbacks/dispatch.d.ts +1 -0
- package/callbacks/dispatch.js +1 -0
- package/callbacks/manager.cjs +1 -0
- package/callbacks/manager.d.cts +1 -0
- package/callbacks/manager.d.ts +1 -0
- package/callbacks/manager.js +1 -0
- package/callbacks/promises.cjs +1 -0
- package/callbacks/promises.d.cts +1 -0
- package/callbacks/promises.d.ts +1 -0
- package/callbacks/promises.js +1 -0
- package/chat_history.cjs +1 -0
- package/chat_history.d.cts +1 -0
- package/chat_history.d.ts +1 -0
- package/chat_history.js +1 -0
- package/context.cjs +1 -0
- package/context.d.cts +1 -0
- package/context.d.ts +1 -0
- package/context.js +1 -0
- package/dist/load/index.d.cts.map +1 -1
- package/dist/messages/format.cjs +1 -1
- package/dist/messages/format.cjs.map +1 -1
- package/dist/messages/format.js +1 -1
- package/dist/messages/format.js.map +1 -1
- package/dist/runnables/graph_mermaid.cjs +9 -3
- package/dist/runnables/graph_mermaid.cjs.map +1 -1
- package/dist/runnables/graph_mermaid.js +9 -3
- package/dist/runnables/graph_mermaid.js.map +1 -1
- package/dist/tracers/base.cjs +9 -10
- package/dist/tracers/base.cjs.map +1 -1
- package/dist/tracers/base.js +9 -10
- package/dist/tracers/base.js.map +1 -1
- package/dist/utils/fast-json-patch/src/core.cjs +10 -0
- package/dist/utils/fast-json-patch/src/core.cjs.map +1 -1
- package/dist/utils/fast-json-patch/src/core.js +10 -0
- package/dist/utils/fast-json-patch/src/core.js.map +1 -1
- package/dist/utils/json_schema.cjs +4 -3
- package/dist/utils/json_schema.cjs.map +1 -1
- package/dist/utils/json_schema.d.cts +5 -2
- package/dist/utils/json_schema.d.cts.map +1 -1
- package/dist/utils/json_schema.d.ts +5 -2
- package/dist/utils/json_schema.d.ts.map +1 -1
- package/dist/utils/json_schema.js +4 -3
- package/dist/utils/json_schema.js.map +1 -1
- package/dist/utils/testing/chat_models.cjs +45 -1
- package/dist/utils/testing/chat_models.cjs.map +1 -1
- package/dist/utils/testing/chat_models.d.cts +3 -0
- package/dist/utils/testing/chat_models.d.cts.map +1 -1
- package/dist/utils/testing/chat_models.d.ts +3 -0
- package/dist/utils/testing/chat_models.d.ts.map +1 -1
- package/dist/utils/testing/chat_models.js +45 -1
- package/dist/utils/testing/chat_models.js.map +1 -1
- package/dist/utils/types/zod.cjs +1 -1
- package/dist/utils/types/zod.cjs.map +1 -1
- package/dist/utils/types/zod.js +1 -1
- package/dist/utils/types/zod.js.map +1 -1
- package/dist/vectorstores.d.cts.map +1 -1
- package/document_loaders/base.cjs +1 -0
- package/document_loaders/base.d.cts +1 -0
- package/document_loaders/base.d.ts +1 -0
- package/document_loaders/base.js +1 -0
- package/document_loaders/langsmith.cjs +1 -0
- package/document_loaders/langsmith.d.cts +1 -0
- package/document_loaders/langsmith.d.ts +1 -0
- package/document_loaders/langsmith.js +1 -0
- package/documents.cjs +1 -0
- package/documents.d.cts +1 -0
- package/documents.d.ts +1 -0
- package/documents.js +1 -0
- package/embeddings.cjs +1 -0
- package/embeddings.d.cts +1 -0
- package/embeddings.d.ts +1 -0
- package/embeddings.js +1 -0
- package/example_selectors.cjs +1 -0
- package/example_selectors.d.cts +1 -0
- package/example_selectors.d.ts +1 -0
- package/example_selectors.js +1 -0
- package/indexing.cjs +1 -0
- package/indexing.d.cts +1 -0
- package/indexing.d.ts +1 -0
- package/indexing.js +1 -0
- package/language_models/base.cjs +1 -0
- package/language_models/base.d.cts +1 -0
- package/language_models/base.d.ts +1 -0
- package/language_models/base.js +1 -0
- package/language_models/chat_models.cjs +1 -0
- package/language_models/chat_models.d.cts +1 -0
- package/language_models/chat_models.d.ts +1 -0
- package/language_models/chat_models.js +1 -0
- package/language_models/llms.cjs +1 -0
- package/language_models/llms.d.cts +1 -0
- package/language_models/llms.d.ts +1 -0
- package/language_models/llms.js +1 -0
- package/language_models/profile.cjs +1 -0
- package/language_models/profile.d.cts +1 -0
- package/language_models/profile.d.ts +1 -0
- package/language_models/profile.js +1 -0
- package/load/serializable.cjs +1 -0
- package/load/serializable.d.cts +1 -0
- package/load/serializable.d.ts +1 -0
- package/load/serializable.js +1 -0
- package/load.cjs +1 -0
- package/load.d.cts +1 -0
- package/load.d.ts +1 -0
- package/load.js +1 -0
- package/memory.cjs +1 -0
- package/memory.d.cts +1 -0
- package/memory.d.ts +1 -0
- package/memory.js +1 -0
- package/messages/tool.cjs +1 -0
- package/messages/tool.d.cts +1 -0
- package/messages/tool.d.ts +1 -0
- package/messages/tool.js +1 -0
- package/messages.cjs +1 -0
- package/messages.d.cts +1 -0
- package/messages.d.ts +1 -0
- package/messages.js +1 -0
- package/output_parsers/openai_functions.cjs +1 -0
- package/output_parsers/openai_functions.d.cts +1 -0
- package/output_parsers/openai_functions.d.ts +1 -0
- package/output_parsers/openai_functions.js +1 -0
- package/output_parsers/openai_tools.cjs +1 -0
- package/output_parsers/openai_tools.d.cts +1 -0
- package/output_parsers/openai_tools.d.ts +1 -0
- package/output_parsers/openai_tools.js +1 -0
- package/output_parsers.cjs +1 -0
- package/output_parsers.d.cts +1 -0
- package/output_parsers.d.ts +1 -0
- package/output_parsers.js +1 -0
- package/outputs.cjs +1 -0
- package/outputs.d.cts +1 -0
- package/outputs.d.ts +1 -0
- package/outputs.js +1 -0
- package/package.json +1 -1
- package/prompt_values.cjs +1 -0
- package/prompt_values.d.cts +1 -0
- package/prompt_values.d.ts +1 -0
- package/prompt_values.js +1 -0
- package/prompts.cjs +1 -0
- package/prompts.d.cts +1 -0
- package/prompts.d.ts +1 -0
- package/prompts.js +1 -0
- package/retrievers/document_compressors.cjs +1 -0
- package/retrievers/document_compressors.d.cts +1 -0
- package/retrievers/document_compressors.d.ts +1 -0
- package/retrievers/document_compressors.js +1 -0
- package/retrievers.cjs +1 -0
- package/retrievers.d.cts +1 -0
- package/retrievers.d.ts +1 -0
- package/retrievers.js +1 -0
- package/runnables/graph.cjs +1 -0
- package/runnables/graph.d.cts +1 -0
- package/runnables/graph.d.ts +1 -0
- package/runnables/graph.js +1 -0
- package/runnables.cjs +1 -0
- package/runnables.d.cts +1 -0
- package/runnables.d.ts +1 -0
- package/runnables.js +1 -0
- package/singletons.cjs +1 -0
- package/singletons.d.cts +1 -0
- package/singletons.d.ts +1 -0
- package/singletons.js +1 -0
- package/stores.cjs +1 -0
- package/stores.d.cts +1 -0
- package/stores.d.ts +1 -0
- package/stores.js +1 -0
- package/structured_query.cjs +1 -0
- package/structured_query.d.cts +1 -0
- package/structured_query.d.ts +1 -0
- package/structured_query.js +1 -0
- package/tools.cjs +1 -0
- package/tools.d.cts +1 -0
- package/tools.d.ts +1 -0
- package/tools.js +1 -0
- package/tracers/base.cjs +1 -0
- package/tracers/base.d.cts +1 -0
- package/tracers/base.d.ts +1 -0
- package/tracers/base.js +1 -0
- package/tracers/console.cjs +1 -0
- package/tracers/console.d.cts +1 -0
- package/tracers/console.d.ts +1 -0
- package/tracers/console.js +1 -0
- package/tracers/log_stream.cjs +1 -0
- package/tracers/log_stream.d.cts +1 -0
- package/tracers/log_stream.d.ts +1 -0
- package/tracers/log_stream.js +1 -0
- package/tracers/run_collector.cjs +1 -0
- package/tracers/run_collector.d.cts +1 -0
- package/tracers/run_collector.d.ts +1 -0
- package/tracers/run_collector.js +1 -0
- package/tracers/tracer_langchain.cjs +1 -0
- package/tracers/tracer_langchain.d.cts +1 -0
- package/tracers/tracer_langchain.d.ts +1 -0
- package/tracers/tracer_langchain.js +1 -0
- package/types/stream.cjs +1 -0
- package/types/stream.d.cts +1 -0
- package/types/stream.d.ts +1 -0
- package/types/stream.js +1 -0
- package/utils/async_caller.cjs +1 -0
- package/utils/async_caller.d.cts +1 -0
- package/utils/async_caller.d.ts +1 -0
- package/utils/async_caller.js +1 -0
- package/utils/chunk_array.cjs +1 -0
- package/utils/chunk_array.d.cts +1 -0
- package/utils/chunk_array.d.ts +1 -0
- package/utils/chunk_array.js +1 -0
- package/utils/env.cjs +1 -0
- package/utils/env.d.cts +1 -0
- package/utils/env.d.ts +1 -0
- package/utils/env.js +1 -0
- package/utils/event_source_parse.cjs +1 -0
- package/utils/event_source_parse.d.cts +1 -0
- package/utils/event_source_parse.d.ts +1 -0
- package/utils/event_source_parse.js +1 -0
- package/utils/format.cjs +1 -0
- package/utils/format.d.cts +1 -0
- package/utils/format.d.ts +1 -0
- package/utils/format.js +1 -0
- package/utils/function_calling.cjs +1 -0
- package/utils/function_calling.d.cts +1 -0
- package/utils/function_calling.d.ts +1 -0
- package/utils/function_calling.js +1 -0
- package/utils/hash.cjs +1 -0
- package/utils/hash.d.cts +1 -0
- package/utils/hash.d.ts +1 -0
- package/utils/hash.js +1 -0
- package/utils/json_patch.cjs +1 -0
- package/utils/json_patch.d.cts +1 -0
- package/utils/json_patch.d.ts +1 -0
- package/utils/json_patch.js +1 -0
- package/utils/json_schema.cjs +1 -0
- package/utils/json_schema.d.cts +1 -0
- package/utils/json_schema.d.ts +1 -0
- package/utils/json_schema.js +1 -0
- package/utils/math.cjs +1 -0
- package/utils/math.d.cts +1 -0
- package/utils/math.d.ts +1 -0
- package/utils/math.js +1 -0
- package/utils/stream.cjs +1 -0
- package/utils/stream.d.cts +1 -0
- package/utils/stream.d.ts +1 -0
- package/utils/stream.js +1 -0
- package/utils/testing.cjs +1 -0
- package/utils/testing.d.cts +1 -0
- package/utils/testing.d.ts +1 -0
- package/utils/testing.js +1 -0
- package/utils/tiktoken.cjs +1 -0
- package/utils/tiktoken.d.cts +1 -0
- package/utils/tiktoken.d.ts +1 -0
- package/utils/tiktoken.js +1 -0
- package/utils/types.cjs +1 -0
- package/utils/types.d.cts +1 -0
- package/utils/types.d.ts +1 -0
- package/utils/types.js +1 -0
- package/vectorstores.cjs +1 -0
- package/vectorstores.d.cts +1 -0
- package/vectorstores.d.ts +1 -0
- package/vectorstores.js +1 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core.js","names":["document: any","pointer: string","document: T","operation: Operation","validateOperation: boolean | Validator<T>","mutateDocument: boolean","banPrototypeModifications: boolean","index: number","returnValue: OperationResult<T>","key: string | number","patch: ReadonlyArray<Operation>","validateOperation?: boolean | Validator<T>","operationResult: OperationResult<T>","document?: any","existingPathFragment?: string","existingValue: any","sequence: ReadonlyArray<Operation>","document?: T","externalValidator?: Validator<T>","a: any","b: any"],"sources":["../../../../src/utils/fast-json-patch/src/core.ts"],"sourcesContent":["// @ts-nocheck\n\n// Inlined because of ESM import issues\n\n/*!\n * https://github.com/Starcounter-Jack/JSON-Patch\n * (c) 2013-2021 Joachim Wester\n * MIT license\n */\ndeclare var require: any;\n\nimport {\n PatchError,\n _deepClone,\n isInteger,\n unescapePathComponent,\n hasUndefined,\n} from \"./helpers.js\";\n\nexport const JsonPatchError = PatchError;\nexport const deepClone = _deepClone;\n\nexport type Operation =\n | AddOperation<any>\n | RemoveOperation\n | ReplaceOperation<any>\n | MoveOperation\n | CopyOperation\n | TestOperation<any>\n | GetOperation<any>;\n\nexport interface Validator<T> {\n (\n operation: Operation,\n index: number,\n document: T,\n existingPathFragment: string\n ): void;\n}\n\nexport interface OperationResult<T> {\n removed?: any;\n test?: boolean;\n newDocument: T;\n}\n\nexport interface BaseOperation {\n path: string;\n}\n\nexport interface AddOperation<T> extends BaseOperation {\n op: \"add\";\n value: T;\n}\n\nexport interface RemoveOperation extends BaseOperation {\n op: \"remove\";\n}\n\nexport interface ReplaceOperation<T> extends BaseOperation {\n op: \"replace\";\n value: T;\n}\n\nexport interface MoveOperation extends BaseOperation {\n op: \"move\";\n from: string;\n}\n\nexport interface CopyOperation extends BaseOperation {\n op: \"copy\";\n from: string;\n}\n\nexport interface TestOperation<T> extends BaseOperation {\n op: \"test\";\n value: T;\n}\n\nexport interface GetOperation<T> extends BaseOperation {\n op: \"_get\";\n value: T;\n}\nexport interface PatchResult<T> extends Array<OperationResult<T>> {\n newDocument: T;\n}\n\n/* We use a Javascript hash to store each\n function. Each hash entry (property) uses\n the operation identifiers specified in rfc6902.\n In this way, we can map each patch operation\n to its dedicated function in efficient way.\n */\n\n/* The operations applicable to an object */\nconst objOps = {\n add: function (obj, key, document) {\n obj[key] = this.value;\n return { newDocument: document };\n },\n remove: function (obj, key, document) {\n var removed = obj[key];\n delete obj[key];\n return { newDocument: document, removed };\n },\n replace: function (obj, key, document) {\n var removed = obj[key];\n obj[key] = this.value;\n return { newDocument: document, removed };\n },\n move: function (obj, key, document) {\n /* in case move target overwrites an existing value,\n return the removed value, this can be taxing performance-wise,\n and is potentially unneeded */\n let removed = getValueByPointer(document, this.path);\n\n if (removed) {\n removed = _deepClone(removed);\n }\n\n const originalValue = applyOperation(document, {\n op: \"remove\",\n path: this.from,\n }).removed;\n\n applyOperation(document, {\n op: \"add\",\n path: this.path,\n value: originalValue,\n });\n\n return { newDocument: document, removed };\n },\n copy: function (obj, key, document) {\n const valueToCopy = getValueByPointer(document, this.from);\n // enforce copy by value so further operations don't affect source (see issue #177)\n applyOperation(document, {\n op: \"add\",\n path: this.path,\n value: _deepClone(valueToCopy),\n });\n return { newDocument: document };\n },\n test: function (obj, key, document) {\n return { newDocument: document, test: _areEquals(obj[key], this.value) };\n },\n _get: function (obj, key, document) {\n this.value = obj[key];\n return { newDocument: document };\n },\n};\n\n/* The operations applicable to an array. Many are the same as for the object */\nvar arrOps = {\n add: function (arr, i, document) {\n if (isInteger(i)) {\n arr.splice(i, 0, this.value);\n } else {\n // array props\n arr[i] = this.value;\n }\n // this may be needed when using '-' in an array\n return { newDocument: document, index: i };\n },\n remove: function (arr, i, document) {\n var removedList = arr.splice(i, 1);\n return { newDocument: document, removed: removedList[0] };\n },\n replace: function (arr, i, document) {\n var removed = arr[i];\n arr[i] = this.value;\n return { newDocument: document, removed };\n },\n move: objOps.move,\n copy: objOps.copy,\n test: objOps.test,\n _get: objOps._get,\n};\n\n/**\n * Retrieves a value from a JSON document by a JSON pointer.\n * Returns the value.\n *\n * @param document The document to get the value from\n * @param pointer an escaped JSON pointer\n * @return The retrieved value\n */\nexport function getValueByPointer(document: any, pointer: string): any {\n if (pointer == \"\") {\n return document;\n }\n var getOriginalDestination = <GetOperation<any>>{ op: \"_get\", path: pointer };\n applyOperation(document, getOriginalDestination);\n return getOriginalDestination.value;\n}\n/**\n * Apply a single JSON Patch Operation on a JSON document.\n * Returns the {newDocument, result} of the operation.\n * It modifies the `document` and `operation` objects - it gets the values by reference.\n * If you would like to avoid touching your values, clone them:\n * `jsonpatch.applyOperation(document, jsonpatch._deepClone(operation))`.\n *\n * @param document The document to patch\n * @param operation The operation to apply\n * @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation.\n * @param mutateDocument Whether to mutate the original document or clone it before applying\n * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`.\n * @return `{newDocument, result}` after the operation\n */\nexport function applyOperation<T>(\n document: T,\n operation: Operation,\n validateOperation: boolean | Validator<T> = false,\n mutateDocument: boolean = true,\n banPrototypeModifications: boolean = true,\n index: number = 0\n): OperationResult<T> {\n if (validateOperation) {\n if (typeof validateOperation == \"function\") {\n validateOperation(operation, 0, document, operation.path);\n } else {\n validator(operation, 0);\n }\n }\n /* ROOT OPERATIONS */\n if (operation.path === \"\") {\n let returnValue: OperationResult<T> = { newDocument: document };\n if (operation.op === \"add\") {\n returnValue.newDocument = operation.value;\n return returnValue;\n } else if (operation.op === \"replace\") {\n returnValue.newDocument = operation.value;\n returnValue.removed = document; //document we removed\n return returnValue;\n } else if (operation.op === \"move\" || operation.op === \"copy\") {\n // it's a move or copy to root\n returnValue.newDocument = getValueByPointer(document, operation.from); // get the value by json-pointer in `from` field\n if (operation.op === \"move\") {\n // report removed item\n returnValue.removed = document;\n }\n return returnValue;\n } else if (operation.op === \"test\") {\n returnValue.test = _areEquals(document, operation.value);\n if (returnValue.test === false) {\n throw new JsonPatchError(\n \"Test operation failed\",\n \"TEST_OPERATION_FAILED\",\n index,\n operation,\n document\n );\n }\n returnValue.newDocument = document;\n return returnValue;\n } else if (operation.op === \"remove\") {\n // a remove on root\n returnValue.removed = document;\n returnValue.newDocument = null;\n return returnValue;\n } else if (operation.op === \"_get\") {\n operation.value = document;\n return returnValue;\n } else {\n /* bad operation */\n if (validateOperation) {\n throw new JsonPatchError(\n \"Operation `op` property is not one of operations defined in RFC-6902\",\n \"OPERATION_OP_INVALID\",\n index,\n operation,\n document\n );\n } else {\n return returnValue;\n }\n }\n } /* END ROOT OPERATIONS */ else {\n if (!mutateDocument) {\n document = _deepClone(document);\n }\n const path = operation.path || \"\";\n const keys = path.split(\"/\");\n let obj = document;\n let t = 1; //skip empty element - http://jsperf.com/to-shift-or-not-to-shift\n let len = keys.length;\n let existingPathFragment = undefined;\n let key: string | number;\n let validateFunction;\n if (typeof validateOperation == \"function\") {\n validateFunction = validateOperation;\n } else {\n validateFunction = validator;\n }\n while (true) {\n key = keys[t];\n if (key && key.indexOf(\"~\") != -1) {\n key = unescapePathComponent(key);\n }\n\n if (\n banPrototypeModifications &&\n (key == \"__proto__\" ||\n (key == \"prototype\" && t > 0 && keys[t - 1] == \"constructor\"))\n ) {\n throw new TypeError(\n \"JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README\"\n );\n }\n\n if (validateOperation) {\n if (existingPathFragment === undefined) {\n if (obj[key] === undefined) {\n existingPathFragment = keys.slice(0, t).join(\"/\");\n } else if (t == len - 1) {\n existingPathFragment = operation.path;\n }\n if (existingPathFragment !== undefined) {\n validateFunction(operation, 0, document, existingPathFragment);\n }\n }\n }\n t++;\n if (Array.isArray(obj)) {\n if (key === \"-\") {\n key = obj.length;\n } else {\n if (validateOperation && !isInteger(key)) {\n throw new JsonPatchError(\n \"Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index\",\n \"OPERATION_PATH_ILLEGAL_ARRAY_INDEX\",\n index,\n operation,\n document\n );\n } // only parse key when it's an integer for `arr.prop` to work\n else if (isInteger(key)) {\n key = ~~key;\n }\n }\n if (t >= len) {\n if (validateOperation && operation.op === \"add\" && key > obj.length) {\n throw new JsonPatchError(\n \"The specified index MUST NOT be greater than the number of elements in the array\",\n \"OPERATION_VALUE_OUT_OF_BOUNDS\",\n index,\n operation,\n document\n );\n }\n const returnValue = arrOps[operation.op].call(\n operation,\n obj,\n key,\n document\n ); // Apply patch\n if (returnValue.test === false) {\n throw new JsonPatchError(\n \"Test operation failed\",\n \"TEST_OPERATION_FAILED\",\n index,\n operation,\n document\n );\n }\n return returnValue;\n }\n } else {\n if (t >= len) {\n const returnValue = objOps[operation.op].call(\n operation,\n obj,\n key,\n document\n ); // Apply patch\n if (returnValue.test === false) {\n throw new JsonPatchError(\n \"Test operation failed\",\n \"TEST_OPERATION_FAILED\",\n index,\n operation,\n document\n );\n }\n return returnValue;\n }\n }\n obj = obj[key];\n // If we have more keys in the path, but the next value isn't a non-null object,\n // throw an OPERATION_PATH_UNRESOLVABLE error instead of iterating again.\n if (validateOperation && t < len && (!obj || typeof obj !== \"object\")) {\n throw new JsonPatchError(\n \"Cannot perform operation at the desired path\",\n \"OPERATION_PATH_UNRESOLVABLE\",\n index,\n operation,\n document\n );\n }\n }\n }\n}\n\n/**\n * Apply a full JSON Patch array on a JSON document.\n * Returns the {newDocument, result} of the patch.\n * It modifies the `document` object and `patch` - it gets the values by reference.\n * If you would like to avoid touching your values, clone them:\n * `jsonpatch.applyPatch(document, jsonpatch._deepClone(patch))`.\n *\n * @param document The document to patch\n * @param patch The patch to apply\n * @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation.\n * @param mutateDocument Whether to mutate the original document or clone it before applying\n * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`.\n * @return An array of `{newDocument, result}` after the patch\n */\nexport function applyPatch<T>(\n document: T,\n patch: ReadonlyArray<Operation>,\n validateOperation?: boolean | Validator<T>,\n mutateDocument: boolean = true,\n banPrototypeModifications: boolean = true\n): PatchResult<T> {\n if (validateOperation) {\n if (!Array.isArray(patch)) {\n throw new JsonPatchError(\n \"Patch sequence must be an array\",\n \"SEQUENCE_NOT_AN_ARRAY\"\n );\n }\n }\n if (!mutateDocument) {\n document = _deepClone(document);\n }\n const results = new Array(patch.length) as PatchResult<T>;\n\n for (let i = 0, length = patch.length; i < length; i++) {\n // we don't need to pass mutateDocument argument because if it was true, we already deep cloned the object, we'll just pass `true`\n results[i] = applyOperation(\n document,\n patch[i],\n validateOperation,\n true,\n banPrototypeModifications,\n i\n );\n document = results[i].newDocument; // in case root was replaced\n }\n results.newDocument = document;\n return results;\n}\n\n/**\n * Apply a single JSON Patch Operation on a JSON document.\n * Returns the updated document.\n * Suitable as a reducer.\n *\n * @param document The document to patch\n * @param operation The operation to apply\n * @return The updated document\n */\nexport function applyReducer<T>(\n document: T,\n operation: Operation,\n index: number\n): T {\n const operationResult: OperationResult<T> = applyOperation(\n document,\n operation\n );\n if (operationResult.test === false) {\n // failed test\n throw new JsonPatchError(\n \"Test operation failed\",\n \"TEST_OPERATION_FAILED\",\n index,\n operation,\n document\n );\n }\n return operationResult.newDocument;\n}\n\n/**\n * Validates a single operation. Called from `jsonpatch.validate`. Throws `JsonPatchError` in case of an error.\n * @param {object} operation - operation object (patch)\n * @param {number} index - index of operation in the sequence\n * @param {object} [document] - object where the operation is supposed to be applied\n * @param {string} [existingPathFragment] - comes along with `document`\n */\nexport function validator(\n operation: Operation,\n index: number,\n document?: any,\n existingPathFragment?: string\n): void {\n if (\n typeof operation !== \"object\" ||\n operation === null ||\n Array.isArray(operation)\n ) {\n throw new JsonPatchError(\n \"Operation is not an object\",\n \"OPERATION_NOT_AN_OBJECT\",\n index,\n operation,\n document\n );\n } else if (!objOps[operation.op]) {\n throw new JsonPatchError(\n \"Operation `op` property is not one of operations defined in RFC-6902\",\n \"OPERATION_OP_INVALID\",\n index,\n operation,\n document\n );\n } else if (typeof operation.path !== \"string\") {\n throw new JsonPatchError(\n \"Operation `path` property is not a string\",\n \"OPERATION_PATH_INVALID\",\n index,\n operation,\n document\n );\n } else if (operation.path.indexOf(\"/\") !== 0 && operation.path.length > 0) {\n // paths that aren't empty string should start with \"/\"\n throw new JsonPatchError(\n 'Operation `path` property must start with \"/\"',\n \"OPERATION_PATH_INVALID\",\n index,\n operation,\n document\n );\n } else if (\n (operation.op === \"move\" || operation.op === \"copy\") &&\n typeof operation.from !== \"string\"\n ) {\n throw new JsonPatchError(\n \"Operation `from` property is not present (applicable in `move` and `copy` operations)\",\n \"OPERATION_FROM_REQUIRED\",\n index,\n operation,\n document\n );\n } else if (\n (operation.op === \"add\" ||\n operation.op === \"replace\" ||\n operation.op === \"test\") &&\n operation.value === undefined\n ) {\n throw new JsonPatchError(\n \"Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)\",\n \"OPERATION_VALUE_REQUIRED\",\n index,\n operation,\n document\n );\n } else if (\n (operation.op === \"add\" ||\n operation.op === \"replace\" ||\n operation.op === \"test\") &&\n hasUndefined(operation.value)\n ) {\n throw new JsonPatchError(\n \"Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)\",\n \"OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED\",\n index,\n operation,\n document\n );\n } else if (document) {\n if (operation.op == \"add\") {\n var pathLen = operation.path.split(\"/\").length;\n var existingPathLen = existingPathFragment.split(\"/\").length;\n if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) {\n throw new JsonPatchError(\n \"Cannot perform an `add` operation at the desired path\",\n \"OPERATION_PATH_CANNOT_ADD\",\n index,\n operation,\n document\n );\n }\n } else if (\n operation.op === \"replace\" ||\n operation.op === \"remove\" ||\n <any>operation.op === \"_get\"\n ) {\n if (operation.path !== existingPathFragment) {\n throw new JsonPatchError(\n \"Cannot perform the operation at a path that does not exist\",\n \"OPERATION_PATH_UNRESOLVABLE\",\n index,\n operation,\n document\n );\n }\n } else if (operation.op === \"move\" || operation.op === \"copy\") {\n var existingValue: any = {\n op: \"_get\",\n path: operation.from,\n value: undefined,\n };\n var error = validate([existingValue], document);\n if (error && error.name === \"OPERATION_PATH_UNRESOLVABLE\") {\n throw new JsonPatchError(\n \"Cannot perform the operation from a path that does not exist\",\n \"OPERATION_FROM_UNRESOLVABLE\",\n index,\n operation,\n document\n );\n }\n }\n }\n}\n\n/**\n * Validates a sequence of operations. If `document` parameter is provided, the sequence is additionally validated against the object document.\n * If error is encountered, returns a JsonPatchError object\n * @param sequence\n * @param document\n * @returns {JsonPatchError|undefined}\n */\nexport function validate<T>(\n sequence: ReadonlyArray<Operation>,\n document?: T,\n externalValidator?: Validator<T>\n): PatchError {\n try {\n if (!Array.isArray(sequence)) {\n throw new JsonPatchError(\n \"Patch sequence must be an array\",\n \"SEQUENCE_NOT_AN_ARRAY\"\n );\n }\n if (document) {\n //clone document and sequence so that we can safely try applying operations\n applyPatch(\n _deepClone(document),\n _deepClone(sequence),\n externalValidator || true\n );\n } else {\n externalValidator = externalValidator || validator;\n for (var i = 0; i < sequence.length; i++) {\n externalValidator(sequence[i], i, document, undefined);\n }\n }\n } catch (e) {\n if (e instanceof JsonPatchError) {\n return e;\n } else {\n throw e;\n }\n }\n}\n\n// based on https://github.com/epoberezkin/fast-deep-equal\n// MIT License\n\n// Copyright (c) 2017 Evgeny Poberezkin\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\nexport function _areEquals(a: any, b: any): boolean {\n if (a === b) return true;\n\n if (a && b && typeof a == \"object\" && typeof b == \"object\") {\n var arrA = Array.isArray(a),\n arrB = Array.isArray(b),\n i,\n length,\n key;\n\n if (arrA && arrB) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0; ) if (!_areEquals(a[i], b[i])) return false;\n return true;\n }\n\n if (arrA != arrB) return false;\n\n var keys = Object.keys(a);\n length = keys.length;\n\n if (length !== Object.keys(b).length) return false;\n\n for (i = length; i-- !== 0; ) if (!b.hasOwnProperty(keys[i])) return false;\n\n for (i = length; i-- !== 0; ) {\n key = keys[i];\n if (!_areEquals(a[key], b[key])) return false;\n }\n\n return true;\n }\n\n return a !== a && b !== b;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAmBA,MAAa,iBAAiB;AAC9B,MAAa,YAAY;AA2EzB,MAAM,SAAS;CACb,KAAK,SAAU,KAAK,KAAK,UAAU;EACjC,IAAI,OAAO,KAAK;AA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","names":["key: string | number","document: any","pointer: string","document: T","operation: Operation","validateOperation: boolean | Validator<T>","mutateDocument: boolean","banPrototypeModifications: boolean","index: number","returnValue: OperationResult<T>","patch: ReadonlyArray<Operation>","validateOperation?: boolean | Validator<T>","operationResult: OperationResult<T>","document?: any","existingPathFragment?: string","existingValue: any","sequence: ReadonlyArray<Operation>","document?: T","externalValidator?: Validator<T>","a: any","b: any"],"sources":["../../../../src/utils/fast-json-patch/src/core.ts"],"sourcesContent":["// @ts-nocheck\n\n// Inlined because of ESM import issues\n\n/*!\n * https://github.com/Starcounter-Jack/JSON-Patch\n * (c) 2013-2021 Joachim Wester\n * MIT license\n */\ndeclare var require: any;\n\nimport {\n PatchError,\n _deepClone,\n isInteger,\n unescapePathComponent,\n hasUndefined,\n} from \"./helpers.js\";\n\nexport const JsonPatchError = PatchError;\nexport const deepClone = _deepClone;\n\nexport type Operation =\n | AddOperation<any>\n | RemoveOperation\n | ReplaceOperation<any>\n | MoveOperation\n | CopyOperation\n | TestOperation<any>\n | GetOperation<any>;\n\nexport interface Validator<T> {\n (\n operation: Operation,\n index: number,\n document: T,\n existingPathFragment: string\n ): void;\n}\n\nexport interface OperationResult<T> {\n removed?: any;\n test?: boolean;\n newDocument: T;\n}\n\nexport interface BaseOperation {\n path: string;\n}\n\nexport interface AddOperation<T> extends BaseOperation {\n op: \"add\";\n value: T;\n}\n\nexport interface RemoveOperation extends BaseOperation {\n op: \"remove\";\n}\n\nexport interface ReplaceOperation<T> extends BaseOperation {\n op: \"replace\";\n value: T;\n}\n\nexport interface MoveOperation extends BaseOperation {\n op: \"move\";\n from: string;\n}\n\nexport interface CopyOperation extends BaseOperation {\n op: \"copy\";\n from: string;\n}\n\nexport interface TestOperation<T> extends BaseOperation {\n op: \"test\";\n value: T;\n}\n\nexport interface GetOperation<T> extends BaseOperation {\n op: \"_get\";\n value: T;\n}\nexport interface PatchResult<T> extends Array<OperationResult<T>> {\n newDocument: T;\n}\n\n/* We use a Javascript hash to store each\n function. Each hash entry (property) uses\n the operation identifiers specified in rfc6902.\n In this way, we can map each patch operation\n to its dedicated function in efficient way.\n */\n\n/**\n * Check if a key is a dangerous prototype property that could lead to prototype pollution.\n * This provides defense-in-depth alongside the check in applyOperation.\n */\nfunction isDangerousKey(key: string | number): boolean {\n return Object.getOwnPropertyNames(Object.prototype).includes(key);\n}\n\n/* The operations applicable to an object */\nconst objOps = {\n add: function (obj, key, document) {\n if (isDangerousKey(key)) {\n throw new TypeError(\n \"JSON-Patch: modifying `__proto__`, `constructor`, or `prototype` prop is banned for security reasons\"\n );\n }\n obj[key] = this.value;\n return { newDocument: document };\n },\n remove: function (obj, key, document) {\n if (isDangerousKey(key)) {\n throw new TypeError(\n \"JSON-Patch: modifying `__proto__`, `constructor`, or `prototype` prop is banned for security reasons\"\n );\n }\n var removed = obj[key];\n delete obj[key];\n return { newDocument: document, removed };\n },\n replace: function (obj, key, document) {\n if (isDangerousKey(key)) {\n throw new TypeError(\n \"JSON-Patch: modifying `__proto__`, `constructor`, or `prototype` prop is banned for security reasons\"\n );\n }\n var removed = obj[key];\n obj[key] = this.value;\n return { newDocument: document, removed };\n },\n move: function (obj, key, document) {\n /* in case move target overwrites an existing value,\n return the removed value, this can be taxing performance-wise,\n and is potentially unneeded */\n let removed = getValueByPointer(document, this.path);\n\n if (removed) {\n removed = _deepClone(removed);\n }\n\n const originalValue = applyOperation(document, {\n op: \"remove\",\n path: this.from,\n }).removed;\n\n applyOperation(document, {\n op: \"add\",\n path: this.path,\n value: originalValue,\n });\n\n return { newDocument: document, removed };\n },\n copy: function (obj, key, document) {\n const valueToCopy = getValueByPointer(document, this.from);\n // enforce copy by value so further operations don't affect source (see issue #177)\n applyOperation(document, {\n op: \"add\",\n path: this.path,\n value: _deepClone(valueToCopy),\n });\n return { newDocument: document };\n },\n test: function (obj, key, document) {\n return { newDocument: document, test: _areEquals(obj[key], this.value) };\n },\n _get: function (obj, key, document) {\n this.value = obj[key];\n return { newDocument: document };\n },\n};\n\n/* The operations applicable to an array. Many are the same as for the object */\nvar arrOps = {\n add: function (arr, i, document) {\n if (isInteger(i)) {\n arr.splice(i, 0, this.value);\n } else {\n // array props\n arr[i] = this.value;\n }\n // this may be needed when using '-' in an array\n return { newDocument: document, index: i };\n },\n remove: function (arr, i, document) {\n var removedList = arr.splice(i, 1);\n return { newDocument: document, removed: removedList[0] };\n },\n replace: function (arr, i, document) {\n var removed = arr[i];\n arr[i] = this.value;\n return { newDocument: document, removed };\n },\n move: objOps.move,\n copy: objOps.copy,\n test: objOps.test,\n _get: objOps._get,\n};\n\n/**\n * Retrieves a value from a JSON document by a JSON pointer.\n * Returns the value.\n *\n * @param document The document to get the value from\n * @param pointer an escaped JSON pointer\n * @return The retrieved value\n */\nexport function getValueByPointer(document: any, pointer: string): any {\n if (pointer == \"\") {\n return document;\n }\n var getOriginalDestination = <GetOperation<any>>{ op: \"_get\", path: pointer };\n applyOperation(document, getOriginalDestination);\n return getOriginalDestination.value;\n}\n/**\n * Apply a single JSON Patch Operation on a JSON document.\n * Returns the {newDocument, result} of the operation.\n * It modifies the `document` and `operation` objects - it gets the values by reference.\n * If you would like to avoid touching your values, clone them:\n * `jsonpatch.applyOperation(document, jsonpatch._deepClone(operation))`.\n *\n * @param document The document to patch\n * @param operation The operation to apply\n * @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation.\n * @param mutateDocument Whether to mutate the original document or clone it before applying\n * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`.\n * @return `{newDocument, result}` after the operation\n */\nexport function applyOperation<T>(\n document: T,\n operation: Operation,\n validateOperation: boolean | Validator<T> = false,\n mutateDocument: boolean = true,\n banPrototypeModifications: boolean = true,\n index: number = 0\n): OperationResult<T> {\n if (validateOperation) {\n if (typeof validateOperation == \"function\") {\n validateOperation(operation, 0, document, operation.path);\n } else {\n validator(operation, 0);\n }\n }\n /* ROOT OPERATIONS */\n if (operation.path === \"\") {\n let returnValue: OperationResult<T> = { newDocument: document };\n if (operation.op === \"add\") {\n returnValue.newDocument = operation.value;\n return returnValue;\n } else if (operation.op === \"replace\") {\n returnValue.newDocument = operation.value;\n returnValue.removed = document; //document we removed\n return returnValue;\n } else if (operation.op === \"move\" || operation.op === \"copy\") {\n // it's a move or copy to root\n returnValue.newDocument = getValueByPointer(document, operation.from); // get the value by json-pointer in `from` field\n if (operation.op === \"move\") {\n // report removed item\n returnValue.removed = document;\n }\n return returnValue;\n } else if (operation.op === \"test\") {\n returnValue.test = _areEquals(document, operation.value);\n if (returnValue.test === false) {\n throw new JsonPatchError(\n \"Test operation failed\",\n \"TEST_OPERATION_FAILED\",\n index,\n operation,\n document\n );\n }\n returnValue.newDocument = document;\n return returnValue;\n } else if (operation.op === \"remove\") {\n // a remove on root\n returnValue.removed = document;\n returnValue.newDocument = null;\n return returnValue;\n } else if (operation.op === \"_get\") {\n operation.value = document;\n return returnValue;\n } else {\n /* bad operation */\n if (validateOperation) {\n throw new JsonPatchError(\n \"Operation `op` property is not one of operations defined in RFC-6902\",\n \"OPERATION_OP_INVALID\",\n index,\n operation,\n document\n );\n } else {\n return returnValue;\n }\n }\n } /* END ROOT OPERATIONS */ else {\n if (!mutateDocument) {\n document = _deepClone(document);\n }\n const path = operation.path || \"\";\n const keys = path.split(\"/\");\n let obj = document;\n let t = 1; //skip empty element - http://jsperf.com/to-shift-or-not-to-shift\n let len = keys.length;\n let existingPathFragment = undefined;\n let key: string | number;\n let validateFunction;\n if (typeof validateOperation == \"function\") {\n validateFunction = validateOperation;\n } else {\n validateFunction = validator;\n }\n while (true) {\n key = keys[t];\n if (key && key.indexOf(\"~\") != -1) {\n key = unescapePathComponent(key);\n }\n\n if (\n banPrototypeModifications &&\n (key == \"__proto__\" ||\n (key == \"prototype\" && t > 0 && keys[t - 1] == \"constructor\"))\n ) {\n throw new TypeError(\n \"JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README\"\n );\n }\n\n if (validateOperation) {\n if (existingPathFragment === undefined) {\n if (obj[key] === undefined) {\n existingPathFragment = keys.slice(0, t).join(\"/\");\n } else if (t == len - 1) {\n existingPathFragment = operation.path;\n }\n if (existingPathFragment !== undefined) {\n validateFunction(operation, 0, document, existingPathFragment);\n }\n }\n }\n t++;\n if (Array.isArray(obj)) {\n if (key === \"-\") {\n key = obj.length;\n } else {\n if (validateOperation && !isInteger(key)) {\n throw new JsonPatchError(\n \"Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index\",\n \"OPERATION_PATH_ILLEGAL_ARRAY_INDEX\",\n index,\n operation,\n document\n );\n } // only parse key when it's an integer for `arr.prop` to work\n else if (isInteger(key)) {\n key = ~~key;\n }\n }\n if (t >= len) {\n if (validateOperation && operation.op === \"add\" && key > obj.length) {\n throw new JsonPatchError(\n \"The specified index MUST NOT be greater than the number of elements in the array\",\n \"OPERATION_VALUE_OUT_OF_BOUNDS\",\n index,\n operation,\n document\n );\n }\n const returnValue = arrOps[operation.op].call(\n operation,\n obj,\n key,\n document\n ); // Apply patch\n if (returnValue.test === false) {\n throw new JsonPatchError(\n \"Test operation failed\",\n \"TEST_OPERATION_FAILED\",\n index,\n operation,\n document\n );\n }\n return returnValue;\n }\n } else {\n if (t >= len) {\n const returnValue = objOps[operation.op].call(\n operation,\n obj,\n key,\n document\n ); // Apply patch\n if (returnValue.test === false) {\n throw new JsonPatchError(\n \"Test operation failed\",\n \"TEST_OPERATION_FAILED\",\n index,\n operation,\n document\n );\n }\n return returnValue;\n }\n }\n obj = obj[key];\n // If we have more keys in the path, but the next value isn't a non-null object,\n // throw an OPERATION_PATH_UNRESOLVABLE error instead of iterating again.\n if (validateOperation && t < len && (!obj || typeof obj !== \"object\")) {\n throw new JsonPatchError(\n \"Cannot perform operation at the desired path\",\n \"OPERATION_PATH_UNRESOLVABLE\",\n index,\n operation,\n document\n );\n }\n }\n }\n}\n\n/**\n * Apply a full JSON Patch array on a JSON document.\n * Returns the {newDocument, result} of the patch.\n * It modifies the `document` object and `patch` - it gets the values by reference.\n * If you would like to avoid touching your values, clone them:\n * `jsonpatch.applyPatch(document, jsonpatch._deepClone(patch))`.\n *\n * @param document The document to patch\n * @param patch The patch to apply\n * @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation.\n * @param mutateDocument Whether to mutate the original document or clone it before applying\n * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`.\n * @return An array of `{newDocument, result}` after the patch\n */\nexport function applyPatch<T>(\n document: T,\n patch: ReadonlyArray<Operation>,\n validateOperation?: boolean | Validator<T>,\n mutateDocument: boolean = true,\n banPrototypeModifications: boolean = true\n): PatchResult<T> {\n if (validateOperation) {\n if (!Array.isArray(patch)) {\n throw new JsonPatchError(\n \"Patch sequence must be an array\",\n \"SEQUENCE_NOT_AN_ARRAY\"\n );\n }\n }\n if (!mutateDocument) {\n document = _deepClone(document);\n }\n const results = new Array(patch.length) as PatchResult<T>;\n\n for (let i = 0, length = patch.length; i < length; i++) {\n // we don't need to pass mutateDocument argument because if it was true, we already deep cloned the object, we'll just pass `true`\n results[i] = applyOperation(\n document,\n patch[i],\n validateOperation,\n true,\n banPrototypeModifications,\n i\n );\n document = results[i].newDocument; // in case root was replaced\n }\n results.newDocument = document;\n return results;\n}\n\n/**\n * Apply a single JSON Patch Operation on a JSON document.\n * Returns the updated document.\n * Suitable as a reducer.\n *\n * @param document The document to patch\n * @param operation The operation to apply\n * @return The updated document\n */\nexport function applyReducer<T>(\n document: T,\n operation: Operation,\n index: number\n): T {\n const operationResult: OperationResult<T> = applyOperation(\n document,\n operation\n );\n if (operationResult.test === false) {\n // failed test\n throw new JsonPatchError(\n \"Test operation failed\",\n \"TEST_OPERATION_FAILED\",\n index,\n operation,\n document\n );\n }\n return operationResult.newDocument;\n}\n\n/**\n * Validates a single operation. Called from `jsonpatch.validate`. Throws `JsonPatchError` in case of an error.\n * @param {object} operation - operation object (patch)\n * @param {number} index - index of operation in the sequence\n * @param {object} [document] - object where the operation is supposed to be applied\n * @param {string} [existingPathFragment] - comes along with `document`\n */\nexport function validator(\n operation: Operation,\n index: number,\n document?: any,\n existingPathFragment?: string\n): void {\n if (\n typeof operation !== \"object\" ||\n operation === null ||\n Array.isArray(operation)\n ) {\n throw new JsonPatchError(\n \"Operation is not an object\",\n \"OPERATION_NOT_AN_OBJECT\",\n index,\n operation,\n document\n );\n } else if (!objOps[operation.op]) {\n throw new JsonPatchError(\n \"Operation `op` property is not one of operations defined in RFC-6902\",\n \"OPERATION_OP_INVALID\",\n index,\n operation,\n document\n );\n } else if (typeof operation.path !== \"string\") {\n throw new JsonPatchError(\n \"Operation `path` property is not a string\",\n \"OPERATION_PATH_INVALID\",\n index,\n operation,\n document\n );\n } else if (operation.path.indexOf(\"/\") !== 0 && operation.path.length > 0) {\n // paths that aren't empty string should start with \"/\"\n throw new JsonPatchError(\n 'Operation `path` property must start with \"/\"',\n \"OPERATION_PATH_INVALID\",\n index,\n operation,\n document\n );\n } else if (\n (operation.op === \"move\" || operation.op === \"copy\") &&\n typeof operation.from !== \"string\"\n ) {\n throw new JsonPatchError(\n \"Operation `from` property is not present (applicable in `move` and `copy` operations)\",\n \"OPERATION_FROM_REQUIRED\",\n index,\n operation,\n document\n );\n } else if (\n (operation.op === \"add\" ||\n operation.op === \"replace\" ||\n operation.op === \"test\") &&\n operation.value === undefined\n ) {\n throw new JsonPatchError(\n \"Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)\",\n \"OPERATION_VALUE_REQUIRED\",\n index,\n operation,\n document\n );\n } else if (\n (operation.op === \"add\" ||\n operation.op === \"replace\" ||\n operation.op === \"test\") &&\n hasUndefined(operation.value)\n ) {\n throw new JsonPatchError(\n \"Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)\",\n \"OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED\",\n index,\n operation,\n document\n );\n } else if (document) {\n if (operation.op == \"add\") {\n var pathLen = operation.path.split(\"/\").length;\n var existingPathLen = existingPathFragment.split(\"/\").length;\n if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) {\n throw new JsonPatchError(\n \"Cannot perform an `add` operation at the desired path\",\n \"OPERATION_PATH_CANNOT_ADD\",\n index,\n operation,\n document\n );\n }\n } else if (\n operation.op === \"replace\" ||\n operation.op === \"remove\" ||\n <any>operation.op === \"_get\"\n ) {\n if (operation.path !== existingPathFragment) {\n throw new JsonPatchError(\n \"Cannot perform the operation at a path that does not exist\",\n \"OPERATION_PATH_UNRESOLVABLE\",\n index,\n operation,\n document\n );\n }\n } else if (operation.op === \"move\" || operation.op === \"copy\") {\n var existingValue: any = {\n op: \"_get\",\n path: operation.from,\n value: undefined,\n };\n var error = validate([existingValue], document);\n if (error && error.name === \"OPERATION_PATH_UNRESOLVABLE\") {\n throw new JsonPatchError(\n \"Cannot perform the operation from a path that does not exist\",\n \"OPERATION_FROM_UNRESOLVABLE\",\n index,\n operation,\n document\n );\n }\n }\n }\n}\n\n/**\n * Validates a sequence of operations. If `document` parameter is provided, the sequence is additionally validated against the object document.\n * If error is encountered, returns a JsonPatchError object\n * @param sequence\n * @param document\n * @returns {JsonPatchError|undefined}\n */\nexport function validate<T>(\n sequence: ReadonlyArray<Operation>,\n document?: T,\n externalValidator?: Validator<T>\n): PatchError {\n try {\n if (!Array.isArray(sequence)) {\n throw new JsonPatchError(\n \"Patch sequence must be an array\",\n \"SEQUENCE_NOT_AN_ARRAY\"\n );\n }\n if (document) {\n //clone document and sequence so that we can safely try applying operations\n applyPatch(\n _deepClone(document),\n _deepClone(sequence),\n externalValidator || true\n );\n } else {\n externalValidator = externalValidator || validator;\n for (var i = 0; i < sequence.length; i++) {\n externalValidator(sequence[i], i, document, undefined);\n }\n }\n } catch (e) {\n if (e instanceof JsonPatchError) {\n return e;\n } else {\n throw e;\n }\n }\n}\n\n// based on https://github.com/epoberezkin/fast-deep-equal\n// MIT License\n\n// Copyright (c) 2017 Evgeny Poberezkin\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\nexport function _areEquals(a: any, b: any): boolean {\n if (a === b) return true;\n\n if (a && b && typeof a == \"object\" && typeof b == \"object\") {\n var arrA = Array.isArray(a),\n arrB = Array.isArray(b),\n i,\n length,\n key;\n\n if (arrA && arrB) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0; ) if (!_areEquals(a[i], b[i])) return false;\n return true;\n }\n\n if (arrA != arrB) return false;\n\n var keys = Object.keys(a);\n length = keys.length;\n\n if (length !== Object.keys(b).length) return false;\n\n for (i = length; i-- !== 0; ) if (!b.hasOwnProperty(keys[i])) return false;\n\n for (i = length; i-- !== 0; ) {\n key = keys[i];\n if (!_areEquals(a[key], b[key])) return false;\n }\n\n return true;\n }\n\n return a !== a && b !== b;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAmBA,MAAa,iBAAiB;AAC9B,MAAa,YAAY;;;;;AA8EzB,SAAS,eAAeA,KAA+B;AACrD,QAAO,OAAO,oBAAoB,OAAO,UA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AAI,CAAC,EAAE,eAAe,KAAK,GAAG,CAAE,QAAO;AAErE,OAAK,IAAI,QAAQ,QAAQ,IAAK;GAC5B,MAAM,KAAK;AACX,OAAI,CAAC,WAAW,EAAE,MAAM,EAAE,KAAK,CAAE,QAAO;EACzC;AAED,SAAO;CACR;AAED,QAAO,MAAM,KAAK,MAAM;AACzB"}
|
|
@@ -16,15 +16,16 @@ require_rolldown_runtime.__export(json_schema_exports, {
|
|
|
16
16
|
/**
|
|
17
17
|
* Converts a Zod schema or JSON schema to a JSON schema.
|
|
18
18
|
* @param schema - The schema to convert.
|
|
19
|
+
* @param params - The parameters to pass to the toJSONSchema function.
|
|
19
20
|
* @returns The converted schema.
|
|
20
21
|
*/
|
|
21
|
-
function toJsonSchema(schema) {
|
|
22
|
+
function toJsonSchema(schema, params) {
|
|
22
23
|
if (require_zod.isZodSchemaV4(schema)) {
|
|
23
24
|
const inputSchema = require_zod.interopZodTransformInputSchema(schema, true);
|
|
24
25
|
if (require_zod.isZodObjectV4(inputSchema)) {
|
|
25
26
|
const strictSchema = require_zod.interopZodObjectStrict(inputSchema, true);
|
|
26
|
-
return (0, zod_v4_core.toJSONSchema)(strictSchema);
|
|
27
|
-
} else return (0, zod_v4_core.toJSONSchema)(schema);
|
|
27
|
+
return (0, zod_v4_core.toJSONSchema)(strictSchema, params);
|
|
28
|
+
} else return (0, zod_v4_core.toJSONSchema)(schema, params);
|
|
28
29
|
}
|
|
29
30
|
if (require_zod.isZodSchemaV3(schema)) return require_zodToJsonSchema.zodToJsonSchema(schema);
|
|
30
31
|
return schema;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json_schema.cjs","names":["schema: InteropZodType | JSONSchema","isZodSchemaV4","interopZodTransformInputSchema","isZodObjectV4","interopZodObjectStrict","isZodSchemaV3","zodToJsonSchema","schema: unknown"],"sources":["../../src/utils/json_schema.ts"],"sourcesContent":["import { toJSONSchema } from \"zod/v4/core\";\nimport { dereference, type Schema } from \"@cfworker/json-schema\";\nimport {\n isZodSchemaV3,\n isZodSchemaV4,\n InteropZodType,\n interopZodObjectStrict,\n isZodObjectV4,\n ZodObjectV4,\n interopZodTransformInputSchema,\n} from \"./types/zod.js\";\nimport {\n type JsonSchema7Type as JSONSchema,\n zodToJsonSchema,\n} from \"./zod-to-json-schema/index.js\";\n\nexport { deepCompareStrict, Validator } from \"@cfworker/json-schema\";\n\n/**\n * Converts a Zod schema or JSON schema to a JSON schema.\n * @param schema - The schema to convert.\n * @returns The converted schema.\n */\nexport function toJsonSchema(schema: InteropZodType | JSONSchema): JSONSchema {\n if (isZodSchemaV4(schema)) {\n const inputSchema = interopZodTransformInputSchema(schema, true);\n if (isZodObjectV4(inputSchema)) {\n const strictSchema = interopZodObjectStrict(\n inputSchema,\n true\n ) as ZodObjectV4;\n return toJSONSchema(strictSchema);\n } else {\n return toJSONSchema(schema);\n }\n }\n if (isZodSchemaV3(schema)) {\n return zodToJsonSchema(schema);\n }\n return schema as JSONSchema;\n}\n\n/**\n * Validates if a JSON schema validates only strings. May return false negatives in some edge cases\n * (like recursive or unresolvable refs).\n *\n * @param schema - The schema to validate.\n * @returns `true` if the schema validates only strings, `false` otherwise.\n */\nexport function validatesOnlyStrings(schema: unknown): boolean {\n // Null, undefined, or empty schema\n if (\n !schema ||\n typeof schema !== \"object\" ||\n Object.keys(schema).length === 0 ||\n Array.isArray(schema)\n ) {\n return false; // Validates anything, not just strings\n }\n\n // Explicit type constraint\n if (\"type\" in schema) {\n if (typeof schema.type === \"string\") {\n return schema.type === \"string\";\n }\n\n if (Array.isArray(schema.type)) {\n // not sure why someone would do `\"type\": [\"string\"]` or especially `\"type\": [\"string\",\n // \"string\", \"string\", ...]` but we're not here to judge\n return schema.type.every((t) => t === \"string\");\n }\n return false; // Invalid or non-string type\n }\n\n // Enum with only string values\n if (\"enum\" in schema) {\n return (\n Array.isArray(schema.enum) &&\n schema.enum.length > 0 &&\n schema.enum.every((val) => typeof val === \"string\")\n );\n }\n\n // String constant\n if (\"const\" in schema) {\n return typeof schema.const === \"string\";\n }\n\n // Schema combinations\n if (\"allOf\" in schema && Array.isArray(schema.allOf)) {\n // If any subschema validates only strings, then the overall schema validates only strings\n return schema.allOf.some((subschema) => validatesOnlyStrings(subschema));\n }\n\n if (\n (\"anyOf\" in schema && Array.isArray(schema.anyOf)) ||\n (\"oneOf\" in schema && Array.isArray(schema.oneOf))\n ) {\n const subschemas = (\n \"anyOf\" in schema ? schema.anyOf : schema.oneOf\n ) as unknown[];\n\n // All subschemas must validate only strings\n return (\n subschemas.length > 0 &&\n subschemas.every((subschema) => validatesOnlyStrings(subschema))\n );\n }\n\n // We're not going to try on this one, it's too complex - we just assume if it has a \"not\" key and hasn't matched one of the above checks, it's not a string schema.\n if (\"not\" in schema) {\n return false; // The not case can validate non-strings\n }\n\n if (\"$ref\" in schema && typeof schema.$ref === \"string\") {\n const ref = schema.$ref as string;\n const resolved = dereference(schema as Schema);\n if (resolved[ref]) {\n return validatesOnlyStrings(resolved[ref]);\n }\n return false;\n }\n\n // ignore recursive refs and other cases where type is omitted for now\n // ignore other cases for now where type is omitted\n\n return false;\n}\n\n// Re-export of the types used throughout langchain for json schema serialization.\n// The plan is to eventually nix zod-to-json-schema altogether in place for\n// zod v4 / a more standardized way of serializing validated inputs, so its re-exported\n// here to remove the dependency on zod-to-json-schema in downstream packages until\n// a determination is made.\n\nexport {\n type JsonSchema7Type,\n type JsonSchema7Type as JSONSchema,\n type JsonSchema7ArrayType,\n type JsonSchema7ObjectType,\n type JsonSchema7StringType,\n type JsonSchema7NumberType,\n type JsonSchema7NullableType,\n} from \"./zod-to-json-schema/index.js\";\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"json_schema.cjs","names":["schema: InteropZodType | JSONSchema","params?: ToJSONSchemaParams","isZodSchemaV4","interopZodTransformInputSchema","isZodObjectV4","interopZodObjectStrict","isZodSchemaV3","zodToJsonSchema","schema: unknown"],"sources":["../../src/utils/json_schema.ts"],"sourcesContent":["import { toJSONSchema } from \"zod/v4/core\";\nimport { dereference, type Schema } from \"@cfworker/json-schema\";\nimport {\n isZodSchemaV3,\n isZodSchemaV4,\n InteropZodType,\n interopZodObjectStrict,\n isZodObjectV4,\n ZodObjectV4,\n interopZodTransformInputSchema,\n} from \"./types/zod.js\";\nimport {\n type JsonSchema7Type as JSONSchema,\n zodToJsonSchema,\n} from \"./zod-to-json-schema/index.js\";\n\nexport { deepCompareStrict, Validator } from \"@cfworker/json-schema\";\n\nexport type ToJSONSchemaParams = NonNullable<\n Parameters<typeof toJSONSchema>[1]\n>;\n\n/**\n * Converts a Zod schema or JSON schema to a JSON schema.\n * @param schema - The schema to convert.\n * @param params - The parameters to pass to the toJSONSchema function.\n * @returns The converted schema.\n */\nexport function toJsonSchema(\n schema: InteropZodType | JSONSchema,\n params?: ToJSONSchemaParams\n): JSONSchema {\n if (isZodSchemaV4(schema)) {\n const inputSchema = interopZodTransformInputSchema(schema, true);\n if (isZodObjectV4(inputSchema)) {\n const strictSchema = interopZodObjectStrict(\n inputSchema,\n true\n ) as ZodObjectV4;\n return toJSONSchema(strictSchema, params);\n } else {\n return toJSONSchema(schema, params);\n }\n }\n if (isZodSchemaV3(schema)) {\n return zodToJsonSchema(schema);\n }\n return schema as JSONSchema;\n}\n\n/**\n * Validates if a JSON schema validates only strings. May return false negatives in some edge cases\n * (like recursive or unresolvable refs).\n *\n * @param schema - The schema to validate.\n * @returns `true` if the schema validates only strings, `false` otherwise.\n */\nexport function validatesOnlyStrings(schema: unknown): boolean {\n // Null, undefined, or empty schema\n if (\n !schema ||\n typeof schema !== \"object\" ||\n Object.keys(schema).length === 0 ||\n Array.isArray(schema)\n ) {\n return false; // Validates anything, not just strings\n }\n\n // Explicit type constraint\n if (\"type\" in schema) {\n if (typeof schema.type === \"string\") {\n return schema.type === \"string\";\n }\n\n if (Array.isArray(schema.type)) {\n // not sure why someone would do `\"type\": [\"string\"]` or especially `\"type\": [\"string\",\n // \"string\", \"string\", ...]` but we're not here to judge\n return schema.type.every((t) => t === \"string\");\n }\n return false; // Invalid or non-string type\n }\n\n // Enum with only string values\n if (\"enum\" in schema) {\n return (\n Array.isArray(schema.enum) &&\n schema.enum.length > 0 &&\n schema.enum.every((val) => typeof val === \"string\")\n );\n }\n\n // String constant\n if (\"const\" in schema) {\n return typeof schema.const === \"string\";\n }\n\n // Schema combinations\n if (\"allOf\" in schema && Array.isArray(schema.allOf)) {\n // If any subschema validates only strings, then the overall schema validates only strings\n return schema.allOf.some((subschema) => validatesOnlyStrings(subschema));\n }\n\n if (\n (\"anyOf\" in schema && Array.isArray(schema.anyOf)) ||\n (\"oneOf\" in schema && Array.isArray(schema.oneOf))\n ) {\n const subschemas = (\n \"anyOf\" in schema ? schema.anyOf : schema.oneOf\n ) as unknown[];\n\n // All subschemas must validate only strings\n return (\n subschemas.length > 0 &&\n subschemas.every((subschema) => validatesOnlyStrings(subschema))\n );\n }\n\n // We're not going to try on this one, it's too complex - we just assume if it has a \"not\" key and hasn't matched one of the above checks, it's not a string schema.\n if (\"not\" in schema) {\n return false; // The not case can validate non-strings\n }\n\n if (\"$ref\" in schema && typeof schema.$ref === \"string\") {\n const ref = schema.$ref as string;\n const resolved = dereference(schema as Schema);\n if (resolved[ref]) {\n return validatesOnlyStrings(resolved[ref]);\n }\n return false;\n }\n\n // ignore recursive refs and other cases where type is omitted for now\n // ignore other cases for now where type is omitted\n\n return false;\n}\n\n// Re-export of the types used throughout langchain for json schema serialization.\n// The plan is to eventually nix zod-to-json-schema altogether in place for\n// zod v4 / a more standardized way of serializing validated inputs, so its re-exported\n// here to remove the dependency on zod-to-json-schema in downstream packages until\n// a determination is made.\n\nexport {\n type JsonSchema7Type,\n type JsonSchema7Type as JSONSchema,\n type JsonSchema7ArrayType,\n type JsonSchema7ObjectType,\n type JsonSchema7StringType,\n type JsonSchema7NumberType,\n type JsonSchema7NullableType,\n} from \"./zod-to-json-schema/index.js\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,aACdA,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EACvD,MAAM,MAAM,OAAO;EACnB,MAAM,mDAAuB,OAAiB;AAC9C,MAAI,SAAS,KACX,QAAO,qBAAqB,SAAS,KAAK;AAE5C,SAAO;CACR;AAKD,QAAO;AACR"}
|
|
@@ -5,15 +5,18 @@ import { JsonSchema7StringType } from "./zod-to-json-schema/parsers/string.cjs";
|
|
|
5
5
|
import { JsonSchema7NullableType } from "./zod-to-json-schema/parsers/nullable.cjs";
|
|
6
6
|
import { JsonSchema7ObjectType } from "./zod-to-json-schema/parsers/object.cjs";
|
|
7
7
|
import { JsonSchema7Type } from "./zod-to-json-schema/parseTypes.cjs";
|
|
8
|
+
import { toJSONSchema } from "zod/v4/core";
|
|
8
9
|
import { Validator, deepCompareStrict } from "@cfworker/json-schema";
|
|
9
10
|
|
|
10
11
|
//#region src/utils/json_schema.d.ts
|
|
12
|
+
type ToJSONSchemaParams = NonNullable<Parameters<typeof toJSONSchema>[1]>;
|
|
11
13
|
/**
|
|
12
14
|
* Converts a Zod schema or JSON schema to a JSON schema.
|
|
13
15
|
* @param schema - The schema to convert.
|
|
16
|
+
* @param params - The parameters to pass to the toJSONSchema function.
|
|
14
17
|
* @returns The converted schema.
|
|
15
18
|
*/
|
|
16
|
-
declare function toJsonSchema(schema: InteropZodType | JsonSchema7Type): JsonSchema7Type;
|
|
19
|
+
declare function toJsonSchema(schema: InteropZodType | JsonSchema7Type, params?: ToJSONSchemaParams): JsonSchema7Type;
|
|
17
20
|
/**
|
|
18
21
|
* Validates if a JSON schema validates only strings. May return false negatives in some edge cases
|
|
19
22
|
* (like recursive or unresolvable refs).
|
|
@@ -23,5 +26,5 @@ declare function toJsonSchema(schema: InteropZodType | JsonSchema7Type): JsonSch
|
|
|
23
26
|
*/
|
|
24
27
|
declare function validatesOnlyStrings(schema: unknown): boolean;
|
|
25
28
|
//#endregion
|
|
26
|
-
export { type JsonSchema7Type as JSONSchema, type JsonSchema7ArrayType, type JsonSchema7NullableType, type JsonSchema7NumberType, type JsonSchema7ObjectType, type JsonSchema7StringType, type JsonSchema7Type, Validator, deepCompareStrict, toJsonSchema, validatesOnlyStrings };
|
|
29
|
+
export { type JsonSchema7Type as JSONSchema, type JsonSchema7ArrayType, type JsonSchema7NullableType, type JsonSchema7NumberType, type JsonSchema7ObjectType, type JsonSchema7StringType, type JsonSchema7Type, ToJSONSchemaParams, Validator, deepCompareStrict, toJsonSchema, validatesOnlyStrings };
|
|
27
30
|
//# sourceMappingURL=json_schema.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json_schema.d.cts","names":["InteropZodType","JsonSchema7Type","JSONSchema","deepCompareStrict","Validator","toJsonSchema","validatesOnlyStrings","JsonSchema7ArrayType","JsonSchema7ObjectType","JsonSchema7StringType","JsonSchema7NumberType","JsonSchema7NullableType"],"sources":["../../src/utils/json_schema.d.ts"],"sourcesContent":["import { InteropZodType } from \"./types/zod.js\";\nimport { type JsonSchema7Type as JSONSchema } from \"./zod-to-json-schema/index.js\";\nexport { deepCompareStrict, Validator } from \"@cfworker/json-schema\";\n/**\n * Converts a Zod schema or JSON schema to a JSON schema.\n * @param schema - The schema to convert.\n * @returns The converted schema.\n */\nexport declare function toJsonSchema(schema: InteropZodType | JSONSchema): JSONSchema;\n/**\n * Validates if a JSON schema validates only strings. May return false negatives in some edge cases\n * (like recursive or unresolvable refs).\n *\n * @param schema - The schema to validate.\n * @returns `true` if the schema validates only strings, `false` otherwise.\n */\nexport declare function validatesOnlyStrings(schema: unknown): boolean;\nexport { type JsonSchema7Type, type JsonSchema7Type as JSONSchema, type JsonSchema7ArrayType, type JsonSchema7ObjectType, type JsonSchema7StringType, type JsonSchema7NumberType, type JsonSchema7NullableType, } from \"./zod-to-json-schema/index.js\";\n//# sourceMappingURL=json_schema.d.ts.map"],"mappings":"
|
|
1
|
+
{"version":3,"file":"json_schema.d.cts","names":["toJSONSchema","InteropZodType","JsonSchema7Type","JSONSchema","deepCompareStrict","Validator","ToJSONSchemaParams","Parameters","NonNullable","toJsonSchema","validatesOnlyStrings","JsonSchema7ArrayType","JsonSchema7ObjectType","JsonSchema7StringType","JsonSchema7NumberType","JsonSchema7NullableType"],"sources":["../../src/utils/json_schema.d.ts"],"sourcesContent":["import { toJSONSchema } from \"zod/v4/core\";\nimport { InteropZodType } from \"./types/zod.js\";\nimport { type JsonSchema7Type as JSONSchema } from \"./zod-to-json-schema/index.js\";\nexport { deepCompareStrict, Validator } from \"@cfworker/json-schema\";\nexport type ToJSONSchemaParams = NonNullable<Parameters<typeof toJSONSchema>[1]>;\n/**\n * Converts a Zod schema or JSON schema to a JSON schema.\n * @param schema - The schema to convert.\n * @param params - The parameters to pass to the toJSONSchema function.\n * @returns The converted schema.\n */\nexport declare function toJsonSchema(schema: InteropZodType | JSONSchema, params?: ToJSONSchemaParams): JSONSchema;\n/**\n * Validates if a JSON schema validates only strings. May return false negatives in some edge cases\n * (like recursive or unresolvable refs).\n *\n * @param schema - The schema to validate.\n * @returns `true` if the schema validates only strings, `false` otherwise.\n */\nexport declare function validatesOnlyStrings(schema: unknown): boolean;\nexport { type JsonSchema7Type, type JsonSchema7Type as JSONSchema, type JsonSchema7ArrayType, type JsonSchema7ObjectType, type JsonSchema7StringType, type JsonSchema7NumberType, type JsonSchema7NullableType, } from \"./zod-to-json-schema/index.js\";\n//# sourceMappingURL=json_schema.d.ts.map"],"mappings":";;;;;;;;;;;KAIYM,kBAAAA,GAAqBE,YAAYD,kBAAkBP;;;;;;;AAAnDM,iBAOYG,YAAAA,CAPM,MAAA,EAOeR,cAPf,GAOgCE,eAPhC,EAAA,MAAA,CAAA,EAOqDG,kBAPrD,CAAA,EAO0EH,eAP1E;;;;AAAc;AAO5C;;;AAAmFG,iBAQ3DI,oBAAAA,CAR2DJ,MAAAA,EAAAA,OAAAA,CAAAA,EAAAA,OAAAA"}
|
|
@@ -6,15 +6,18 @@ import { JsonSchema7NullableType } from "./zod-to-json-schema/parsers/nullable.j
|
|
|
6
6
|
import { JsonSchema7ObjectType } from "./zod-to-json-schema/parsers/object.js";
|
|
7
7
|
import { JsonSchema7Type } from "./zod-to-json-schema/parseTypes.js";
|
|
8
8
|
import "./zod-to-json-schema/index.js";
|
|
9
|
+
import { toJSONSchema } from "zod/v4/core";
|
|
9
10
|
import { Validator, deepCompareStrict } from "@cfworker/json-schema";
|
|
10
11
|
|
|
11
12
|
//#region src/utils/json_schema.d.ts
|
|
13
|
+
type ToJSONSchemaParams = NonNullable<Parameters<typeof toJSONSchema>[1]>;
|
|
12
14
|
/**
|
|
13
15
|
* Converts a Zod schema or JSON schema to a JSON schema.
|
|
14
16
|
* @param schema - The schema to convert.
|
|
17
|
+
* @param params - The parameters to pass to the toJSONSchema function.
|
|
15
18
|
* @returns The converted schema.
|
|
16
19
|
*/
|
|
17
|
-
declare function toJsonSchema(schema: InteropZodType | JsonSchema7Type): JsonSchema7Type;
|
|
20
|
+
declare function toJsonSchema(schema: InteropZodType | JsonSchema7Type, params?: ToJSONSchemaParams): JsonSchema7Type;
|
|
18
21
|
/**
|
|
19
22
|
* Validates if a JSON schema validates only strings. May return false negatives in some edge cases
|
|
20
23
|
* (like recursive or unresolvable refs).
|
|
@@ -24,5 +27,5 @@ declare function toJsonSchema(schema: InteropZodType | JsonSchema7Type): JsonSch
|
|
|
24
27
|
*/
|
|
25
28
|
declare function validatesOnlyStrings(schema: unknown): boolean;
|
|
26
29
|
//#endregion
|
|
27
|
-
export { type JsonSchema7Type as JSONSchema, type JsonSchema7ArrayType, type JsonSchema7NullableType, type JsonSchema7NumberType, type JsonSchema7ObjectType, type JsonSchema7StringType, type JsonSchema7Type, Validator, deepCompareStrict, toJsonSchema, validatesOnlyStrings };
|
|
30
|
+
export { type JsonSchema7Type as JSONSchema, type JsonSchema7ArrayType, type JsonSchema7NullableType, type JsonSchema7NumberType, type JsonSchema7ObjectType, type JsonSchema7StringType, type JsonSchema7Type, ToJSONSchemaParams, Validator, deepCompareStrict, toJsonSchema, validatesOnlyStrings };
|
|
28
31
|
//# sourceMappingURL=json_schema.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json_schema.d.ts","names":["InteropZodType","JsonSchema7Type","JSONSchema","deepCompareStrict","Validator","toJsonSchema","validatesOnlyStrings","JsonSchema7ArrayType","JsonSchema7ObjectType","JsonSchema7StringType","JsonSchema7NumberType","JsonSchema7NullableType"],"sources":["../../src/utils/json_schema.d.ts"],"sourcesContent":["import { InteropZodType } from \"./types/zod.js\";\nimport { type JsonSchema7Type as JSONSchema } from \"./zod-to-json-schema/index.js\";\nexport { deepCompareStrict, Validator } from \"@cfworker/json-schema\";\n/**\n * Converts a Zod schema or JSON schema to a JSON schema.\n * @param schema - The schema to convert.\n * @returns The converted schema.\n */\nexport declare function toJsonSchema(schema: InteropZodType | JSONSchema): JSONSchema;\n/**\n * Validates if a JSON schema validates only strings. May return false negatives in some edge cases\n * (like recursive or unresolvable refs).\n *\n * @param schema - The schema to validate.\n * @returns `true` if the schema validates only strings, `false` otherwise.\n */\nexport declare function validatesOnlyStrings(schema: unknown): boolean;\nexport { type JsonSchema7Type, type JsonSchema7Type as JSONSchema, type JsonSchema7ArrayType, type JsonSchema7ObjectType, type JsonSchema7StringType, type JsonSchema7NumberType, type JsonSchema7NullableType, } from \"./zod-to-json-schema/index.js\";\n//# sourceMappingURL=json_schema.d.ts.map"],"mappings":"
|
|
1
|
+
{"version":3,"file":"json_schema.d.ts","names":["toJSONSchema","InteropZodType","JsonSchema7Type","JSONSchema","deepCompareStrict","Validator","ToJSONSchemaParams","Parameters","NonNullable","toJsonSchema","validatesOnlyStrings","JsonSchema7ArrayType","JsonSchema7ObjectType","JsonSchema7StringType","JsonSchema7NumberType","JsonSchema7NullableType"],"sources":["../../src/utils/json_schema.d.ts"],"sourcesContent":["import { toJSONSchema } from \"zod/v4/core\";\nimport { InteropZodType } from \"./types/zod.js\";\nimport { type JsonSchema7Type as JSONSchema } from \"./zod-to-json-schema/index.js\";\nexport { deepCompareStrict, Validator } from \"@cfworker/json-schema\";\nexport type ToJSONSchemaParams = NonNullable<Parameters<typeof toJSONSchema>[1]>;\n/**\n * Converts a Zod schema or JSON schema to a JSON schema.\n * @param schema - The schema to convert.\n * @param params - The parameters to pass to the toJSONSchema function.\n * @returns The converted schema.\n */\nexport declare function toJsonSchema(schema: InteropZodType | JSONSchema, params?: ToJSONSchemaParams): JSONSchema;\n/**\n * Validates if a JSON schema validates only strings. May return false negatives in some edge cases\n * (like recursive or unresolvable refs).\n *\n * @param schema - The schema to validate.\n * @returns `true` if the schema validates only strings, `false` otherwise.\n */\nexport declare function validatesOnlyStrings(schema: unknown): boolean;\nexport { type JsonSchema7Type, type JsonSchema7Type as JSONSchema, type JsonSchema7ArrayType, type JsonSchema7ObjectType, type JsonSchema7StringType, type JsonSchema7NumberType, type JsonSchema7NullableType, } from \"./zod-to-json-schema/index.js\";\n//# sourceMappingURL=json_schema.d.ts.map"],"mappings":";;;;;;;;;;;;KAIYM,kBAAAA,GAAqBE,YAAYD,kBAAkBP;;;;;;;iBAOvCS,YAAAA,SAAqBR,iBAAiBE,0BAAqBG,qBAAqBH;AAPxG;;;;AAA4C;AAO5C;;AAA8DA,iBAQtCO,oBAAAA,CARsCP,MAAAA,EAAAA,OAAAA,CAAAA,EAAAA,OAAAA"}
|
|
@@ -16,15 +16,16 @@ __export(json_schema_exports, {
|
|
|
16
16
|
/**
|
|
17
17
|
* Converts a Zod schema or JSON schema to a JSON schema.
|
|
18
18
|
* @param schema - The schema to convert.
|
|
19
|
+
* @param params - The parameters to pass to the toJSONSchema function.
|
|
19
20
|
* @returns The converted schema.
|
|
20
21
|
*/
|
|
21
|
-
function toJsonSchema(schema) {
|
|
22
|
+
function toJsonSchema(schema, params) {
|
|
22
23
|
if (isZodSchemaV4(schema)) {
|
|
23
24
|
const inputSchema = interopZodTransformInputSchema(schema, true);
|
|
24
25
|
if (isZodObjectV4(inputSchema)) {
|
|
25
26
|
const strictSchema = interopZodObjectStrict(inputSchema, true);
|
|
26
|
-
return toJSONSchema(strictSchema);
|
|
27
|
-
} else return toJSONSchema(schema);
|
|
27
|
+
return toJSONSchema(strictSchema, params);
|
|
28
|
+
} else return toJSONSchema(schema, params);
|
|
28
29
|
}
|
|
29
30
|
if (isZodSchemaV3(schema)) return zodToJsonSchema(schema);
|
|
30
31
|
return schema;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json_schema.js","names":["schema: InteropZodType | JSONSchema","schema: unknown"],"sources":["../../src/utils/json_schema.ts"],"sourcesContent":["import { toJSONSchema } from \"zod/v4/core\";\nimport { dereference, type Schema } from \"@cfworker/json-schema\";\nimport {\n isZodSchemaV3,\n isZodSchemaV4,\n InteropZodType,\n interopZodObjectStrict,\n isZodObjectV4,\n ZodObjectV4,\n interopZodTransformInputSchema,\n} from \"./types/zod.js\";\nimport {\n type JsonSchema7Type as JSONSchema,\n zodToJsonSchema,\n} from \"./zod-to-json-schema/index.js\";\n\nexport { deepCompareStrict, Validator } from \"@cfworker/json-schema\";\n\n/**\n * Converts a Zod schema or JSON schema to a JSON schema.\n * @param schema - The schema to convert.\n * @returns The converted schema.\n */\nexport function toJsonSchema(schema: InteropZodType | JSONSchema): JSONSchema {\n if (isZodSchemaV4(schema)) {\n const inputSchema = interopZodTransformInputSchema(schema, true);\n if (isZodObjectV4(inputSchema)) {\n const strictSchema = interopZodObjectStrict(\n inputSchema,\n true\n ) as ZodObjectV4;\n return toJSONSchema(strictSchema);\n } else {\n return toJSONSchema(schema);\n }\n }\n if (isZodSchemaV3(schema)) {\n return zodToJsonSchema(schema);\n }\n return schema as JSONSchema;\n}\n\n/**\n * Validates if a JSON schema validates only strings. May return false negatives in some edge cases\n * (like recursive or unresolvable refs).\n *\n * @param schema - The schema to validate.\n * @returns `true` if the schema validates only strings, `false` otherwise.\n */\nexport function validatesOnlyStrings(schema: unknown): boolean {\n // Null, undefined, or empty schema\n if (\n !schema ||\n typeof schema !== \"object\" ||\n Object.keys(schema).length === 0 ||\n Array.isArray(schema)\n ) {\n return false; // Validates anything, not just strings\n }\n\n // Explicit type constraint\n if (\"type\" in schema) {\n if (typeof schema.type === \"string\") {\n return schema.type === \"string\";\n }\n\n if (Array.isArray(schema.type)) {\n // not sure why someone would do `\"type\": [\"string\"]` or especially `\"type\": [\"string\",\n // \"string\", \"string\", ...]` but we're not here to judge\n return schema.type.every((t) => t === \"string\");\n }\n return false; // Invalid or non-string type\n }\n\n // Enum with only string values\n if (\"enum\" in schema) {\n return (\n Array.isArray(schema.enum) &&\n schema.enum.length > 0 &&\n schema.enum.every((val) => typeof val === \"string\")\n );\n }\n\n // String constant\n if (\"const\" in schema) {\n return typeof schema.const === \"string\";\n }\n\n // Schema combinations\n if (\"allOf\" in schema && Array.isArray(schema.allOf)) {\n // If any subschema validates only strings, then the overall schema validates only strings\n return schema.allOf.some((subschema) => validatesOnlyStrings(subschema));\n }\n\n if (\n (\"anyOf\" in schema && Array.isArray(schema.anyOf)) ||\n (\"oneOf\" in schema && Array.isArray(schema.oneOf))\n ) {\n const subschemas = (\n \"anyOf\" in schema ? schema.anyOf : schema.oneOf\n ) as unknown[];\n\n // All subschemas must validate only strings\n return (\n subschemas.length > 0 &&\n subschemas.every((subschema) => validatesOnlyStrings(subschema))\n );\n }\n\n // We're not going to try on this one, it's too complex - we just assume if it has a \"not\" key and hasn't matched one of the above checks, it's not a string schema.\n if (\"not\" in schema) {\n return false; // The not case can validate non-strings\n }\n\n if (\"$ref\" in schema && typeof schema.$ref === \"string\") {\n const ref = schema.$ref as string;\n const resolved = dereference(schema as Schema);\n if (resolved[ref]) {\n return validatesOnlyStrings(resolved[ref]);\n }\n return false;\n }\n\n // ignore recursive refs and other cases where type is omitted for now\n // ignore other cases for now where type is omitted\n\n return false;\n}\n\n// Re-export of the types used throughout langchain for json schema serialization.\n// The plan is to eventually nix zod-to-json-schema altogether in place for\n// zod v4 / a more standardized way of serializing validated inputs, so its re-exported\n// here to remove the dependency on zod-to-json-schema in downstream packages until\n// a determination is made.\n\nexport {\n type JsonSchema7Type,\n type JsonSchema7Type as JSONSchema,\n type JsonSchema7ArrayType,\n type JsonSchema7ObjectType,\n type JsonSchema7StringType,\n type JsonSchema7NumberType,\n type JsonSchema7NullableType,\n} from \"./zod-to-json-schema/index.js\";\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"json_schema.js","names":["schema: InteropZodType | JSONSchema","params?: ToJSONSchemaParams","schema: unknown"],"sources":["../../src/utils/json_schema.ts"],"sourcesContent":["import { toJSONSchema } from \"zod/v4/core\";\nimport { dereference, type Schema } from \"@cfworker/json-schema\";\nimport {\n isZodSchemaV3,\n isZodSchemaV4,\n InteropZodType,\n interopZodObjectStrict,\n isZodObjectV4,\n ZodObjectV4,\n interopZodTransformInputSchema,\n} from \"./types/zod.js\";\nimport {\n type JsonSchema7Type as JSONSchema,\n zodToJsonSchema,\n} from \"./zod-to-json-schema/index.js\";\n\nexport { deepCompareStrict, Validator } from \"@cfworker/json-schema\";\n\nexport type ToJSONSchemaParams = NonNullable<\n Parameters<typeof toJSONSchema>[1]\n>;\n\n/**\n * Converts a Zod schema or JSON schema to a JSON schema.\n * @param schema - The schema to convert.\n * @param params - The parameters to pass to the toJSONSchema function.\n * @returns The converted schema.\n */\nexport function toJsonSchema(\n schema: InteropZodType | JSONSchema,\n params?: ToJSONSchemaParams\n): JSONSchema {\n if (isZodSchemaV4(schema)) {\n const inputSchema = interopZodTransformInputSchema(schema, true);\n if (isZodObjectV4(inputSchema)) {\n const strictSchema = interopZodObjectStrict(\n inputSchema,\n true\n ) as ZodObjectV4;\n return toJSONSchema(strictSchema, params);\n } else {\n return toJSONSchema(schema, params);\n }\n }\n if (isZodSchemaV3(schema)) {\n return zodToJsonSchema(schema);\n }\n return schema as JSONSchema;\n}\n\n/**\n * Validates if a JSON schema validates only strings. May return false negatives in some edge cases\n * (like recursive or unresolvable refs).\n *\n * @param schema - The schema to validate.\n * @returns `true` if the schema validates only strings, `false` otherwise.\n */\nexport function validatesOnlyStrings(schema: unknown): boolean {\n // Null, undefined, or empty schema\n if (\n !schema ||\n typeof schema !== \"object\" ||\n Object.keys(schema).length === 0 ||\n Array.isArray(schema)\n ) {\n return false; // Validates anything, not just strings\n }\n\n // Explicit type constraint\n if (\"type\" in schema) {\n if (typeof schema.type === \"string\") {\n return schema.type === \"string\";\n }\n\n if (Array.isArray(schema.type)) {\n // not sure why someone would do `\"type\": [\"string\"]` or especially `\"type\": [\"string\",\n // \"string\", \"string\", ...]` but we're not here to judge\n return schema.type.every((t) => t === \"string\");\n }\n return false; // Invalid or non-string type\n }\n\n // Enum with only string values\n if (\"enum\" in schema) {\n return (\n Array.isArray(schema.enum) &&\n schema.enum.length > 0 &&\n schema.enum.every((val) => typeof val === \"string\")\n );\n }\n\n // String constant\n if (\"const\" in schema) {\n return typeof schema.const === \"string\";\n }\n\n // Schema combinations\n if (\"allOf\" in schema && Array.isArray(schema.allOf)) {\n // If any subschema validates only strings, then the overall schema validates only strings\n return schema.allOf.some((subschema) => validatesOnlyStrings(subschema));\n }\n\n if (\n (\"anyOf\" in schema && Array.isArray(schema.anyOf)) ||\n (\"oneOf\" in schema && Array.isArray(schema.oneOf))\n ) {\n const subschemas = (\n \"anyOf\" in schema ? schema.anyOf : schema.oneOf\n ) as unknown[];\n\n // All subschemas must validate only strings\n return (\n subschemas.length > 0 &&\n subschemas.every((subschema) => validatesOnlyStrings(subschema))\n );\n }\n\n // We're not going to try on this one, it's too complex - we just assume if it has a \"not\" key and hasn't matched one of the above checks, it's not a string schema.\n if (\"not\" in schema) {\n return false; // The not case can validate non-strings\n }\n\n if (\"$ref\" in schema && typeof schema.$ref === \"string\") {\n const ref = schema.$ref as string;\n const resolved = dereference(schema as Schema);\n if (resolved[ref]) {\n return validatesOnlyStrings(resolved[ref]);\n }\n return false;\n }\n\n // ignore recursive refs and other cases where type is omitted for now\n // ignore other cases for now where type is omitted\n\n return false;\n}\n\n// Re-export of the types used throughout langchain for json schema serialization.\n// The plan is to eventually nix zod-to-json-schema altogether in place for\n// zod v4 / a more standardized way of serializing validated inputs, so its re-exported\n// here to remove the dependency on zod-to-json-schema in downstream packages until\n// a determination is made.\n\nexport {\n type JsonSchema7Type,\n type JsonSchema7Type as JSONSchema,\n type JsonSchema7ArrayType,\n type JsonSchema7ObjectType,\n type JsonSchema7StringType,\n type JsonSchema7NumberType,\n type JsonSchema7NullableType,\n} from \"./zod-to-json-schema/index.js\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,aACdA,QACAC,QACY;AACZ,KAAI,cAAc,OAAO,EAAE;EACzB,MAAM,cAAc,+BAA+B,QAAQ,KAAK;AAChE,MAAI,cAAc,YAAY,EAAE;GAC9B,MAAM,eAAe,uBACnB,aACA,KACD;AACD,UAAO,aAAa,cAAc,OAAO;EAC1C,MACC,QAAO,aAAa,QAAQ,OAAO;CAEtC;AACD,KAAI,cAAc,OAAO,CACvB,QAAO,gBAAgB,OAAO;AAEhC,QAAO;AACR;;;;;;;;AASD,SAAgB,qBAAqBC,QAA0B;AAE7D,KACE,CAAC,UACD,OAAO,WAAW,YAClB,OAAO,KAAK,OAAO,CAAC,WAAW,KAC/B,MAAM,QAAQ,OAAO,CAErB,QAAO;AAIT,KAAI,UAAU,QAAQ;AACpB,MAAI,OAAO,OAAO,SAAS,SACzB,QAAO,OAAO,SAAS;AAGzB,MAAI,MAAM,QAAQ,OAAO,KAAK,CAG5B,QAAO,OAAO,KAAK,MAAM,CAAC,MAAM,MAAM,SAAS;AAEjD,SAAO;CACR;AAGD,KAAI,UAAU,OACZ,QACE,MAAM,QAAQ,OAAO,KAAK,IAC1B,OAAO,KAAK,SAAS,KACrB,OAAO,KAAK,MAAM,CAAC,QAAQ,OAAO,QAAQ,SAAS;AAKvD,KAAI,WAAW,OACb,QAAO,OAAO,OAAO,UAAU;AAIjC,KAAI,WAAW,UAAU,MAAM,QAAQ,OAAO,MAAM,CAElD,QAAO,OAAO,MAAM,KAAK,CAAC,cAAc,qBAAqB,UAAU,CAAC;AAG1E,KACG,WAAW,UAAU,MAAM,QAAQ,OAAO,MAAM,IAChD,WAAW,UAAU,MAAM,QAAQ,OAAO,MAAM,EACjD;EACA,MAAM,aACJ,WAAW,SAAS,OAAO,QAAQ,OAAO;AAI5C,SACE,WAAW,SAAS,KACpB,WAAW,MAAM,CAAC,cAAc,qBAAqB,UAAU,CAAC;CAEnE;AAGD,KAAI,SAAS,OACX,QAAO;AAGT,KAAI,UAAU,UAAU,OAAO,OAAO,SAAS,UAAU;EACvD,MAAM,MAAM,OAAO;EACnB,MAAM,WAAW,YAAY,OAAiB;AAC9C,MAAI,SAAS,KACX,QAAO,qBAAqB,SAAS,KAAK;AAE5C,SAAO;CACR;AAKD,QAAO;AACR"}
|
|
@@ -153,7 +153,7 @@ var FakeStreamingChatModel = class FakeStreamingChatModel extends require_langua
|
|
|
153
153
|
* console.log({ secondResponse });
|
|
154
154
|
* ```
|
|
155
155
|
*/
|
|
156
|
-
var FakeListChatModel = class extends require_language_models_chat_models.BaseChatModel {
|
|
156
|
+
var FakeListChatModel = class FakeListChatModel extends require_language_models_chat_models.BaseChatModel {
|
|
157
157
|
static lc_name() {
|
|
158
158
|
return "FakeListChatModel";
|
|
159
159
|
}
|
|
@@ -163,6 +163,8 @@ var FakeListChatModel = class extends require_language_models_chat_models.BaseCh
|
|
|
163
163
|
sleep;
|
|
164
164
|
emitCustomEvent = false;
|
|
165
165
|
generationInfo;
|
|
166
|
+
tools = [];
|
|
167
|
+
toolStyle = "openai";
|
|
166
168
|
constructor(params) {
|
|
167
169
|
super(params);
|
|
168
170
|
const { responses, sleep, emitCustomEvent, generationInfo } = params;
|
|
@@ -234,6 +236,48 @@ var FakeListChatModel = class extends require_language_models_chat_models.BaseCh
|
|
|
234
236
|
if (this.i < this.responses.length - 1) this.i += 1;
|
|
235
237
|
else this.i = 0;
|
|
236
238
|
}
|
|
239
|
+
bindTools(tools) {
|
|
240
|
+
const merged = [...this.tools, ...tools];
|
|
241
|
+
const toolDicts = merged.map((t) => {
|
|
242
|
+
switch (this.toolStyle) {
|
|
243
|
+
case "openai": return {
|
|
244
|
+
type: "function",
|
|
245
|
+
function: {
|
|
246
|
+
name: t.name,
|
|
247
|
+
description: t.description,
|
|
248
|
+
parameters: require_utils_json_schema.toJsonSchema(t.schema)
|
|
249
|
+
}
|
|
250
|
+
};
|
|
251
|
+
case "anthropic": return {
|
|
252
|
+
name: t.name,
|
|
253
|
+
description: t.description,
|
|
254
|
+
input_schema: require_utils_json_schema.toJsonSchema(t.schema)
|
|
255
|
+
};
|
|
256
|
+
case "bedrock": return { toolSpec: {
|
|
257
|
+
name: t.name,
|
|
258
|
+
description: t.description,
|
|
259
|
+
inputSchema: require_utils_json_schema.toJsonSchema(t.schema)
|
|
260
|
+
} };
|
|
261
|
+
case "google": return {
|
|
262
|
+
name: t.name,
|
|
263
|
+
description: t.description,
|
|
264
|
+
parameters: require_utils_json_schema.toJsonSchema(t.schema)
|
|
265
|
+
};
|
|
266
|
+
default: throw new Error(`Unsupported tool style: ${this.toolStyle}`);
|
|
267
|
+
}
|
|
268
|
+
});
|
|
269
|
+
const wrapped = this.toolStyle === "google" ? [{ functionDeclarations: toolDicts }] : toolDicts;
|
|
270
|
+
const next = new FakeListChatModel({
|
|
271
|
+
responses: this.responses,
|
|
272
|
+
sleep: this.sleep,
|
|
273
|
+
emitCustomEvent: this.emitCustomEvent,
|
|
274
|
+
generationInfo: this.generationInfo
|
|
275
|
+
});
|
|
276
|
+
next.tools = merged;
|
|
277
|
+
next.toolStyle = this.toolStyle;
|
|
278
|
+
next.i = this.i;
|
|
279
|
+
return next.withConfig({ tools: wrapped });
|
|
280
|
+
}
|
|
237
281
|
withStructuredOutput(_params, _config) {
|
|
238
282
|
return require_base.RunnableLambda.from(async (input) => {
|
|
239
283
|
const message = await this.invoke(input);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chat_models.cjs","names":["BaseChatModel","messages: BaseMessage[]","options?: this[\"ParsedCallOptions\"]","runManager?: CallbackManagerForLLMRun","AIMessage","tools: (StructuredTool | ToolSpec)[]","toJsonSchema","_options: this[\"ParsedCallOptions\"]","_runManager?: CallbackManagerForLLMRun","generation: ChatResult","_messages: BaseMessage[]","ChatGenerationChunk","AIMessageChunk","params: FakeChatInput","text: string","options: this[\"ParsedCallOptions\"]","generationInfo?: Record<string, any>","_params:\n | StructuredOutputMethodParams<RunOutput, boolean>\n | InteropZodType<RunOutput>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>","_config?: StructuredOutputMethodOptions<boolean>","RunnableLambda"],"sources":["../../../src/utils/testing/chat_models.ts"],"sourcesContent":["import { CallbackManagerForLLMRun } from \"../../callbacks/manager.js\";\nimport {\n BaseChatModel,\n BaseChatModelCallOptions,\n BaseChatModelParams,\n} from \"../../language_models/chat_models.js\";\nimport { BaseLLMParams } from \"../../language_models/llms.js\";\nimport {\n BaseMessage,\n AIMessage,\n AIMessageChunk,\n} from \"../../messages/index.js\";\nimport { type ChatResult, ChatGenerationChunk } from \"../../outputs.js\";\nimport { Runnable, RunnableLambda } from \"../../runnables/base.js\";\nimport { StructuredTool } from \"../../tools/index.js\";\nimport {\n StructuredOutputMethodParams,\n BaseLanguageModelInput,\n StructuredOutputMethodOptions,\n} from \"../../language_models/base.js\";\n\nimport { toJsonSchema } from \"../json_schema.js\";\nimport { InteropZodType } from \"../types/zod.js\";\n\n/** Minimal shape actually needed by `bindTools` */\nexport interface ToolSpec {\n name: string;\n description?: string;\n schema: InteropZodType | Record<string, unknown>; // Either a Zod schema *or* a plain JSON-Schema object\n}\n\n/**\n * Interface specific to the Fake Streaming Chat model.\n */\nexport interface FakeStreamingChatModelCallOptions\n extends BaseChatModelCallOptions {}\n/**\n * Interface for the Constructor-field specific to the Fake Streaming Chat model (all optional because we fill in defaults).\n */\nexport interface FakeStreamingChatModelFields extends BaseChatModelParams {\n /** Milliseconds to pause between fallback char-by-char chunks */\n sleep?: number;\n\n /** Full AI messages to fall back to when no `chunks` supplied */\n responses?: BaseMessage[];\n\n /** Exact chunks to emit (can include tool-call deltas) */\n chunks?: AIMessageChunk[];\n\n /** How tool specs are formatted in `bindTools` */\n toolStyle?: \"openai\" | \"anthropic\" | \"bedrock\" | \"google\";\n\n /** Throw this error instead of streaming (useful in tests) */\n thrownErrorString?: string;\n}\n\nexport class FakeChatModel extends BaseChatModel {\n _combineLLMOutput() {\n return [];\n }\n\n _llmType(): string {\n return \"fake\";\n }\n\n async _generate(\n messages: BaseMessage[],\n options?: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n if (options?.stop?.length) {\n return {\n generations: [\n {\n message: new AIMessage(options.stop[0]),\n text: options.stop[0],\n },\n ],\n };\n }\n const text = messages\n .map((m) => {\n if (typeof m.content === \"string\") {\n return m.content;\n }\n return JSON.stringify(m.content, null, 2);\n })\n .join(\"\\n\");\n await runManager?.handleLLMNewToken(text);\n return {\n generations: [\n {\n message: new AIMessage(text),\n text,\n },\n ],\n llmOutput: {},\n };\n }\n}\n\nexport class FakeStreamingChatModel extends BaseChatModel<FakeStreamingChatModelCallOptions> {\n sleep = 50;\n\n responses: BaseMessage[] = [];\n\n chunks: AIMessageChunk[] = [];\n\n toolStyle: \"openai\" | \"anthropic\" | \"bedrock\" | \"google\" = \"openai\";\n\n thrownErrorString?: string;\n\n private tools: (StructuredTool | ToolSpec)[] = [];\n\n constructor({\n sleep = 50,\n responses = [],\n chunks = [],\n toolStyle = \"openai\",\n thrownErrorString,\n ...rest\n }: FakeStreamingChatModelFields & BaseLLMParams) {\n super(rest);\n this.sleep = sleep;\n this.responses = responses;\n this.chunks = chunks;\n this.toolStyle = toolStyle;\n this.thrownErrorString = thrownErrorString;\n }\n\n _llmType() {\n return \"fake\";\n }\n\n bindTools(tools: (StructuredTool | ToolSpec)[]) {\n const merged = [...this.tools, ...tools];\n\n const toolDicts = merged.map((t) => {\n switch (this.toolStyle) {\n case \"openai\":\n return {\n type: \"function\",\n function: {\n name: t.name,\n description: t.description,\n parameters: toJsonSchema(t.schema),\n },\n };\n case \"anthropic\":\n return {\n name: t.name,\n description: t.description,\n input_schema: toJsonSchema(t.schema),\n };\n case \"bedrock\":\n return {\n toolSpec: {\n name: t.name,\n description: t.description,\n inputSchema: toJsonSchema(t.schema),\n },\n };\n case \"google\":\n return {\n name: t.name,\n description: t.description,\n parameters: toJsonSchema(t.schema),\n };\n default:\n throw new Error(`Unsupported tool style: ${this.toolStyle}`);\n }\n });\n\n const wrapped =\n this.toolStyle === \"google\"\n ? [{ functionDeclarations: toolDicts }]\n : toolDicts;\n\n /* creating a *new* instance – mirrors LangChain .bind semantics for type-safety and avoiding noise */\n const next = new FakeStreamingChatModel({\n sleep: this.sleep,\n responses: this.responses,\n chunks: this.chunks,\n toolStyle: this.toolStyle,\n thrownErrorString: this.thrownErrorString,\n });\n next.tools = merged;\n\n return next.withConfig({ tools: wrapped } as BaseChatModelCallOptions);\n }\n\n async _generate(\n messages: BaseMessage[],\n _options: this[\"ParsedCallOptions\"],\n _runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n if (this.thrownErrorString) {\n throw new Error(this.thrownErrorString);\n }\n\n const content = this.responses?.[0]?.content ?? messages[0].content ?? \"\";\n\n const generation: ChatResult = {\n generations: [\n {\n text: \"\",\n message: new AIMessage({\n content,\n tool_calls: this.chunks?.[0]?.tool_calls,\n }),\n },\n ],\n };\n\n return generation;\n }\n\n async *_streamResponseChunks(\n _messages: BaseMessage[],\n _options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n if (this.thrownErrorString) {\n throw new Error(this.thrownErrorString);\n }\n if (this.chunks?.length) {\n for (const msgChunk of this.chunks) {\n const cg = new ChatGenerationChunk({\n message: new AIMessageChunk({\n content: msgChunk.content,\n tool_calls: msgChunk.tool_calls,\n additional_kwargs: msgChunk.additional_kwargs ?? {},\n }),\n text: msgChunk.content?.toString() ?? \"\",\n });\n\n yield cg;\n await runManager?.handleLLMNewToken(\n msgChunk.content as string,\n undefined,\n undefined,\n undefined,\n undefined,\n { chunk: cg }\n );\n }\n return;\n }\n\n const fallback =\n this.responses?.[0] ??\n new AIMessage(\n typeof _messages[0].content === \"string\" ? _messages[0].content : \"\"\n );\n const text = typeof fallback.content === \"string\" ? fallback.content : \"\";\n\n for (const ch of text) {\n await new Promise((r) => setTimeout(r, this.sleep));\n const cg = new ChatGenerationChunk({\n message: new AIMessageChunk({ content: ch }),\n text: ch,\n });\n yield cg;\n await runManager?.handleLLMNewToken(\n ch,\n undefined,\n undefined,\n undefined,\n undefined,\n { chunk: cg }\n );\n }\n }\n}\n\n/**\n * Interface for the input parameters specific to the Fake List Chat model.\n */\nexport interface FakeChatInput extends BaseChatModelParams {\n /** Responses to return */\n responses: string[];\n\n /** Time to sleep in milliseconds between responses */\n sleep?: number;\n\n emitCustomEvent?: boolean;\n\n /**\n * Generation info to include on the last chunk during streaming.\n * This gets merged into response_metadata by the base chat model.\n * Useful for testing response_metadata propagation (e.g., finish_reason).\n */\n generationInfo?: Record<string, unknown>;\n}\n\nexport interface FakeListChatModelCallOptions extends BaseChatModelCallOptions {\n thrownErrorString?: string;\n}\n\n/**\n * A fake Chat Model that returns a predefined list of responses. It can be used\n * for testing purposes.\n * @example\n * ```typescript\n * const chat = new FakeListChatModel({\n * responses: [\"I'll callback later.\", \"You 'console' them!\"]\n * });\n *\n * const firstMessage = new HumanMessage(\"You want to hear a JavaScript joke?\");\n * const secondMessage = new HumanMessage(\"How do you cheer up a JavaScript developer?\");\n *\n * // Call the chat model with a message and log the response\n * const firstResponse = await chat.call([firstMessage]);\n * console.log({ firstResponse });\n *\n * const secondResponse = await chat.call([secondMessage]);\n * console.log({ secondResponse });\n * ```\n */\nexport class FakeListChatModel extends BaseChatModel<FakeListChatModelCallOptions> {\n static lc_name() {\n return \"FakeListChatModel\";\n }\n\n lc_serializable = true;\n\n responses: string[];\n\n i = 0;\n\n sleep?: number;\n\n emitCustomEvent = false;\n\n generationInfo?: Record<string, unknown>;\n\n constructor(params: FakeChatInput) {\n super(params);\n const { responses, sleep, emitCustomEvent, generationInfo } = params;\n this.responses = responses;\n this.sleep = sleep;\n this.emitCustomEvent = emitCustomEvent ?? this.emitCustomEvent;\n this.generationInfo = generationInfo;\n }\n\n _combineLLMOutput() {\n return [];\n }\n\n _llmType(): string {\n return \"fake-list\";\n }\n\n async _generate(\n _messages: BaseMessage[],\n options?: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n await this._sleepIfRequested();\n if (options?.thrownErrorString) {\n throw new Error(options.thrownErrorString);\n }\n if (this.emitCustomEvent) {\n await runManager?.handleCustomEvent(\"some_test_event\", {\n someval: true,\n });\n }\n\n if (options?.stop?.length) {\n return {\n generations: [this._formatGeneration(options.stop[0])],\n };\n } else {\n const response = this._currentResponse();\n this._incrementResponse();\n\n return {\n generations: [this._formatGeneration(response)],\n llmOutput: {},\n };\n }\n }\n\n _formatGeneration(text: string) {\n return {\n message: new AIMessage(text),\n text,\n };\n }\n\n async *_streamResponseChunks(\n _messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n const response = this._currentResponse();\n this._incrementResponse();\n if (this.emitCustomEvent) {\n await runManager?.handleCustomEvent(\"some_test_event\", {\n someval: true,\n });\n }\n\n const responseChars = [...response];\n for (let i = 0; i < responseChars.length; i++) {\n const text = responseChars[i];\n const isLastChunk = i === responseChars.length - 1;\n await this._sleepIfRequested();\n if (options?.thrownErrorString) {\n throw new Error(options.thrownErrorString);\n }\n // Include generationInfo on the last chunk (like real providers do)\n // This gets merged into response_metadata by the base chat model\n const chunk = this._createResponseChunk(\n text,\n isLastChunk ? this.generationInfo : undefined\n );\n yield chunk;\n // eslint-disable-next-line no-void\n void runManager?.handleLLMNewToken(text);\n }\n }\n\n async _sleepIfRequested() {\n if (this.sleep !== undefined) {\n await this._sleep();\n }\n }\n\n async _sleep() {\n return new Promise<void>((resolve) => {\n setTimeout(() => resolve(), this.sleep);\n });\n }\n\n _createResponseChunk(\n text: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n generationInfo?: Record<string, any>\n ): ChatGenerationChunk {\n return new ChatGenerationChunk({\n message: new AIMessageChunk({ content: text }),\n text,\n generationInfo,\n });\n }\n\n _currentResponse() {\n return this.responses[this.i];\n }\n\n _incrementResponse() {\n if (this.i < this.responses.length - 1) {\n this.i += 1;\n } else {\n this.i = 0;\n }\n }\n\n withStructuredOutput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>\n >(\n _params:\n | StructuredOutputMethodParams<RunOutput, false>\n | InteropZodType<RunOutput>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<false>\n ): Runnable<BaseLanguageModelInput, RunOutput>;\n\n withStructuredOutput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>\n >(\n _params:\n | StructuredOutputMethodParams<RunOutput, true>\n | InteropZodType<RunOutput>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<true>\n ): Runnable<BaseLanguageModelInput, { raw: BaseMessage; parsed: RunOutput }>;\n\n withStructuredOutput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>\n >(\n _params:\n | StructuredOutputMethodParams<RunOutput, boolean>\n | InteropZodType<RunOutput>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n _config?: StructuredOutputMethodOptions<boolean>\n ):\n | Runnable<BaseLanguageModelInput, RunOutput>\n | Runnable<\n BaseLanguageModelInput,\n { raw: BaseMessage; parsed: RunOutput }\n > {\n return RunnableLambda.from(async (input) => {\n const message = await this.invoke(input);\n if (message.tool_calls?.[0]?.args) {\n return message.tool_calls[0].args as RunOutput;\n }\n if (typeof message.content === \"string\") {\n return JSON.parse(message.content);\n }\n throw new Error(\"No structured output found\");\n }) as Runnable;\n }\n}\n"],"mappings":";;;;;;;;AAwDA,IAAa,gBAAb,cAAmCA,kDAAc;CAC/C,oBAAoB;AAClB,SAAO,CAAE;CACV;CAED,WAAmB;AACjB,SAAO;CACR;CAED,MAAM,UACJC,UACAC,SACAC,YACqB;AACrB,MAAI,SAAS,MAAM,OACjB,QAAO,EACL,aAAa,CACX;GACE,SAAS,IAAIC,qBAAU,QAAQ,KAAK;GACpC,MAAM,QAAQ,KAAK;EACpB,CACF,EACF;EAEH,MAAM,OAAO,SACV,IAAI,CAAC,MAAM;AACV,OAAI,OAAO,EAAE,YAAY,SACvB,QAAO,EAAE;AAEX,UAAO,KAAK,UAAU,EAAE,SAAS,MAAM,EAAE;EAC1C,EAAC,CACD,KAAK,KAAK;EACb,MAAM,YAAY,kBAAkB,KAAK;AACzC,SAAO;GACL,aAAa,CACX;IACE,SAAS,IAAIA,qBAAU;IACvB;GACD,CACF;GACD,WAAW,CAAE;EACd;CACF;AACF;AAED,IAAa,yBAAb,MAAa,+BAA+BJ,kDAAiD;CAC3F,QAAQ;CAER,YAA2B,CAAE;CAE7B,SAA2B,CAAE;CAE7B,YAA2D;CAE3D;CAEA,AAAQ,QAAuC,CAAE;CAEjD,YAAY,EACV,QAAQ,IACR,YAAY,CAAE,GACd,SAAS,CAAE,GACX,YAAY,UACZ,kBACA,GAAG,MAC0C,EAAE;EAC/C,MAAM,KAAK;EACX,KAAK,QAAQ;EACb,KAAK,YAAY;EACjB,KAAK,SAAS;EACd,KAAK,YAAY;EACjB,KAAK,oBAAoB;CAC1B;CAED,WAAW;AACT,SAAO;CACR;CAED,UAAUK,OAAsC;EAC9C,MAAM,SAAS,CAAC,GAAG,KAAK,OAAO,GAAG,KAAM;EAExC,MAAM,YAAY,OAAO,IAAI,CAAC,MAAM;AAClC,WAAQ,KAAK,WAAb;IACE,KAAK,SACH,QAAO;KACL,MAAM;K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AAqB;AACnB,MAAI,KAAK,IAAI,KAAK,UAAU,SAAS,GACnC,KAAK,KAAK;OAEV,KAAK,IAAI;CAEZ;CA0BD,qBAIEK,SAKAC,SAMI;AACJ,SAAOC,4BAAe,KAAK,OAAO,UAAU;GAC1C,MAAM,UAAU,MAAM,KAAK,OAAO,MAAM;AACxC,OAAI,QAAQ,aAAa,IAAI,KAC3B,QAAO,QAAQ,WAAW,GAAG;AAE/B,OAAI,OAAO,QAAQ,YAAY,SAC7B,QAAO,KAAK,MAAM,QAAQ,QAAQ;AAEpC,SAAM,IAAI,MAAM;EACjB,EAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"chat_models.cjs","names":["BaseChatModel","messages: BaseMessage[]","options?: this[\"ParsedCallOptions\"]","runManager?: CallbackManagerForLLMRun","AIMessage","tools: (StructuredTool | ToolSpec)[]","toJsonSchema","_options: this[\"ParsedCallOptions\"]","_runManager?: CallbackManagerForLLMRun","generation: ChatResult","_messages: BaseMessage[]","ChatGenerationChunk","AIMessageChunk","params: FakeChatInput","text: string","options: this[\"ParsedCallOptions\"]","generationInfo?: Record<string, any>","_params:\n | StructuredOutputMethodParams<RunOutput, boolean>\n | InteropZodType<RunOutput>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>","_config?: StructuredOutputMethodOptions<boolean>","RunnableLambda"],"sources":["../../../src/utils/testing/chat_models.ts"],"sourcesContent":["import { CallbackManagerForLLMRun } from \"../../callbacks/manager.js\";\nimport {\n BaseChatModel,\n BaseChatModelCallOptions,\n BaseChatModelParams,\n} from \"../../language_models/chat_models.js\";\nimport { BaseLLMParams } from \"../../language_models/llms.js\";\nimport {\n BaseMessage,\n AIMessage,\n AIMessageChunk,\n} from \"../../messages/index.js\";\nimport { type ChatResult, ChatGenerationChunk } from \"../../outputs.js\";\nimport { Runnable, RunnableLambda } from \"../../runnables/base.js\";\nimport { StructuredTool } from \"../../tools/index.js\";\nimport {\n StructuredOutputMethodParams,\n BaseLanguageModelInput,\n StructuredOutputMethodOptions,\n} from \"../../language_models/base.js\";\n\nimport { toJsonSchema } from \"../json_schema.js\";\nimport { InteropZodType } from \"../types/zod.js\";\n\n/** Minimal shape actually needed by `bindTools` */\nexport interface ToolSpec {\n name: string;\n description?: string;\n schema: InteropZodType | Record<string, unknown>; // Either a Zod schema *or* a plain JSON-Schema object\n}\n\n/**\n * Interface specific to the Fake Streaming Chat model.\n */\nexport interface FakeStreamingChatModelCallOptions\n extends BaseChatModelCallOptions {}\n/**\n * Interface for the Constructor-field specific to the Fake Streaming Chat model (all optional because we fill in defaults).\n */\nexport interface FakeStreamingChatModelFields extends BaseChatModelParams {\n /** Milliseconds to pause between fallback char-by-char chunks */\n sleep?: number;\n\n /** Full AI messages to fall back to when no `chunks` supplied */\n responses?: BaseMessage[];\n\n /** Exact chunks to emit (can include tool-call deltas) */\n chunks?: AIMessageChunk[];\n\n /** How tool specs are formatted in `bindTools` */\n toolStyle?: \"openai\" | \"anthropic\" | \"bedrock\" | \"google\";\n\n /** Throw this error instead of streaming (useful in tests) */\n thrownErrorString?: string;\n}\n\nexport class FakeChatModel extends BaseChatModel {\n _combineLLMOutput() {\n return [];\n }\n\n _llmType(): string {\n return \"fake\";\n }\n\n async _generate(\n messages: BaseMessage[],\n options?: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n if (options?.stop?.length) {\n return {\n generations: [\n {\n message: new AIMessage(options.stop[0]),\n text: options.stop[0],\n },\n ],\n };\n }\n const text = messages\n .map((m) => {\n if (typeof m.content === \"string\") {\n return m.content;\n }\n return JSON.stringify(m.content, null, 2);\n })\n .join(\"\\n\");\n await runManager?.handleLLMNewToken(text);\n return {\n generations: [\n {\n message: new AIMessage(text),\n text,\n },\n ],\n llmOutput: {},\n };\n }\n}\n\nexport class FakeStreamingChatModel extends BaseChatModel<FakeStreamingChatModelCallOptions> {\n sleep = 50;\n\n responses: BaseMessage[] = [];\n\n chunks: AIMessageChunk[] = [];\n\n toolStyle: \"openai\" | \"anthropic\" | \"bedrock\" | \"google\" = \"openai\";\n\n thrownErrorString?: string;\n\n private tools: (StructuredTool | ToolSpec)[] = [];\n\n constructor({\n sleep = 50,\n responses = [],\n chunks = [],\n toolStyle = \"openai\",\n thrownErrorString,\n ...rest\n }: FakeStreamingChatModelFields & BaseLLMParams) {\n super(rest);\n this.sleep = sleep;\n this.responses = responses;\n this.chunks = chunks;\n this.toolStyle = toolStyle;\n this.thrownErrorString = thrownErrorString;\n }\n\n _llmType() {\n return \"fake\";\n }\n\n bindTools(tools: (StructuredTool | ToolSpec)[]) {\n const merged = [...this.tools, ...tools];\n\n const toolDicts = merged.map((t) => {\n switch (this.toolStyle) {\n case \"openai\":\n return {\n type: \"function\",\n function: {\n name: t.name,\n description: t.description,\n parameters: toJsonSchema(t.schema),\n },\n };\n case \"anthropic\":\n return {\n name: t.name,\n description: t.description,\n input_schema: toJsonSchema(t.schema),\n };\n case \"bedrock\":\n return {\n toolSpec: {\n name: t.name,\n description: t.description,\n inputSchema: toJsonSchema(t.schema),\n },\n };\n case \"google\":\n return {\n name: t.name,\n description: t.description,\n parameters: toJsonSchema(t.schema),\n };\n default:\n throw new Error(`Unsupported tool style: ${this.toolStyle}`);\n }\n });\n\n const wrapped =\n this.toolStyle === \"google\"\n ? [{ functionDeclarations: toolDicts }]\n : toolDicts;\n\n /* creating a *new* instance – mirrors LangChain .bind semantics for type-safety and avoiding noise */\n const next = new FakeStreamingChatModel({\n sleep: this.sleep,\n responses: this.responses,\n chunks: this.chunks,\n toolStyle: this.toolStyle,\n thrownErrorString: this.thrownErrorString,\n });\n next.tools = merged;\n\n return next.withConfig({ tools: wrapped } as BaseChatModelCallOptions);\n }\n\n async _generate(\n messages: BaseMessage[],\n _options: this[\"ParsedCallOptions\"],\n _runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n if (this.thrownErrorString) {\n throw new Error(this.thrownErrorString);\n }\n\n const content = this.responses?.[0]?.content ?? messages[0].content ?? \"\";\n\n const generation: ChatResult = {\n generations: [\n {\n text: \"\",\n message: new AIMessage({\n content,\n tool_calls: this.chunks?.[0]?.tool_calls,\n }),\n },\n ],\n };\n\n return generation;\n }\n\n async *_streamResponseChunks(\n _messages: BaseMessage[],\n _options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n if (this.thrownErrorString) {\n throw new Error(this.thrownErrorString);\n }\n if (this.chunks?.length) {\n for (const msgChunk of this.chunks) {\n const cg = new ChatGenerationChunk({\n message: new AIMessageChunk({\n content: msgChunk.content,\n tool_calls: msgChunk.tool_calls,\n additional_kwargs: msgChunk.additional_kwargs ?? {},\n }),\n text: msgChunk.content?.toString() ?? \"\",\n });\n\n yield cg;\n await runManager?.handleLLMNewToken(\n msgChunk.content as string,\n undefined,\n undefined,\n undefined,\n undefined,\n { chunk: cg }\n );\n }\n return;\n }\n\n const fallback =\n this.responses?.[0] ??\n new AIMessage(\n typeof _messages[0].content === \"string\" ? _messages[0].content : \"\"\n );\n const text = typeof fallback.content === \"string\" ? fallback.content : \"\";\n\n for (const ch of text) {\n await new Promise((r) => setTimeout(r, this.sleep));\n const cg = new ChatGenerationChunk({\n message: new AIMessageChunk({ content: ch }),\n text: ch,\n });\n yield cg;\n await runManager?.handleLLMNewToken(\n ch,\n undefined,\n undefined,\n undefined,\n undefined,\n { chunk: cg }\n );\n }\n }\n}\n\n/**\n * Interface for the input parameters specific to the Fake List Chat model.\n */\nexport interface FakeChatInput extends BaseChatModelParams {\n /** Responses to return */\n responses: string[];\n\n /** Time to sleep in milliseconds between responses */\n sleep?: number;\n\n emitCustomEvent?: boolean;\n\n /**\n * Generation info to include on the last chunk during streaming.\n * This gets merged into response_metadata by the base chat model.\n * Useful for testing response_metadata propagation (e.g., finish_reason).\n */\n generationInfo?: Record<string, unknown>;\n}\n\nexport interface FakeListChatModelCallOptions extends BaseChatModelCallOptions {\n thrownErrorString?: string;\n}\n\n/**\n * A fake Chat Model that returns a predefined list of responses. It can be used\n * for testing purposes.\n * @example\n * ```typescript\n * const chat = new FakeListChatModel({\n * responses: [\"I'll callback later.\", \"You 'console' them!\"]\n * });\n *\n * const firstMessage = new HumanMessage(\"You want to hear a JavaScript joke?\");\n * const secondMessage = new HumanMessage(\"How do you cheer up a JavaScript developer?\");\n *\n * // Call the chat model with a message and log the response\n * const firstResponse = await chat.call([firstMessage]);\n * console.log({ firstResponse });\n *\n * const secondResponse = await chat.call([secondMessage]);\n * console.log({ secondResponse });\n * ```\n */\nexport class FakeListChatModel extends BaseChatModel<FakeListChatModelCallOptions> {\n static lc_name() {\n return \"FakeListChatModel\";\n }\n\n lc_serializable = true;\n\n responses: string[];\n\n i = 0;\n\n sleep?: number;\n\n emitCustomEvent = false;\n\n generationInfo?: Record<string, unknown>;\n\n private tools: (StructuredTool | ToolSpec)[] = [];\n\n toolStyle: \"openai\" | \"anthropic\" | \"bedrock\" | \"google\" = \"openai\";\n\n constructor(params: FakeChatInput) {\n super(params);\n const { responses, sleep, emitCustomEvent, generationInfo } = params;\n this.responses = responses;\n this.sleep = sleep;\n this.emitCustomEvent = emitCustomEvent ?? this.emitCustomEvent;\n this.generationInfo = generationInfo;\n }\n\n _combineLLMOutput() {\n return [];\n }\n\n _llmType(): string {\n return \"fake-list\";\n }\n\n async _generate(\n _messages: BaseMessage[],\n options?: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n await this._sleepIfRequested();\n if (options?.thrownErrorString) {\n throw new Error(options.thrownErrorString);\n }\n if (this.emitCustomEvent) {\n await runManager?.handleCustomEvent(\"some_test_event\", {\n someval: true,\n });\n }\n\n if (options?.stop?.length) {\n return {\n generations: [this._formatGeneration(options.stop[0])],\n };\n } else {\n const response = this._currentResponse();\n this._incrementResponse();\n\n return {\n generations: [this._formatGeneration(response)],\n llmOutput: {},\n };\n }\n }\n\n _formatGeneration(text: string) {\n return {\n message: new AIMessage(text),\n text,\n };\n }\n\n async *_streamResponseChunks(\n _messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n const response = this._currentResponse();\n this._incrementResponse();\n if (this.emitCustomEvent) {\n await runManager?.handleCustomEvent(\"some_test_event\", {\n someval: true,\n });\n }\n\n const responseChars = [...response];\n for (let i = 0; i < responseChars.length; i++) {\n const text = responseChars[i];\n const isLastChunk = i === responseChars.length - 1;\n await this._sleepIfRequested();\n if (options?.thrownErrorString) {\n throw new Error(options.thrownErrorString);\n }\n // Include generationInfo on the last chunk (like real providers do)\n // This gets merged into response_metadata by the base chat model\n const chunk = this._createResponseChunk(\n text,\n isLastChunk ? this.generationInfo : undefined\n );\n yield chunk;\n // eslint-disable-next-line no-void\n void runManager?.handleLLMNewToken(text);\n }\n }\n\n async _sleepIfRequested() {\n if (this.sleep !== undefined) {\n await this._sleep();\n }\n }\n\n async _sleep() {\n return new Promise<void>((resolve) => {\n setTimeout(() => resolve(), this.sleep);\n });\n }\n\n _createResponseChunk(\n text: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n generationInfo?: Record<string, any>\n ): ChatGenerationChunk {\n return new ChatGenerationChunk({\n message: new AIMessageChunk({ content: text }),\n text,\n generationInfo,\n });\n }\n\n _currentResponse() {\n return this.responses[this.i];\n }\n\n _incrementResponse() {\n if (this.i < this.responses.length - 1) {\n this.i += 1;\n } else {\n this.i = 0;\n }\n }\n\n bindTools(tools: (StructuredTool | ToolSpec)[]) {\n const merged = [...this.tools, ...tools];\n\n const toolDicts = merged.map((t) => {\n switch (this.toolStyle) {\n case \"openai\":\n return {\n type: \"function\",\n function: {\n name: t.name,\n description: t.description,\n parameters: toJsonSchema(t.schema),\n },\n };\n case \"anthropic\":\n return {\n name: t.name,\n description: t.description,\n input_schema: toJsonSchema(t.schema),\n };\n case \"bedrock\":\n return {\n toolSpec: {\n name: t.name,\n description: t.description,\n inputSchema: toJsonSchema(t.schema),\n },\n };\n case \"google\":\n return {\n name: t.name,\n description: t.description,\n parameters: toJsonSchema(t.schema),\n };\n default:\n throw new Error(`Unsupported tool style: ${this.toolStyle}`);\n }\n });\n\n const wrapped =\n this.toolStyle === \"google\"\n ? [{ functionDeclarations: toolDicts }]\n : toolDicts;\n\n const next = new FakeListChatModel({\n responses: this.responses,\n sleep: this.sleep,\n emitCustomEvent: this.emitCustomEvent,\n generationInfo: this.generationInfo,\n });\n next.tools = merged;\n next.toolStyle = this.toolStyle;\n next.i = this.i;\n\n return next.withConfig({ tools: wrapped } as BaseChatModelCallOptions);\n }\n\n withStructuredOutput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>\n >(\n _params:\n | StructuredOutputMethodParams<RunOutput, false>\n | InteropZodType<RunOutput>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<false>\n ): Runnable<BaseLanguageModelInput, RunOutput>;\n\n withStructuredOutput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>\n >(\n _params:\n | StructuredOutputMethodParams<RunOutput, true>\n | InteropZodType<RunOutput>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<true>\n ): Runnable<BaseLanguageModelInput, { raw: BaseMessage; parsed: RunOutput }>;\n\n withStructuredOutput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>\n >(\n _params:\n | StructuredOutputMethodParams<RunOutput, boolean>\n | InteropZodType<RunOutput>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n _config?: StructuredOutputMethodOptions<boolean>\n ):\n | Runnable<BaseLanguageModelInput, RunOutput>\n | Runnable<\n BaseLanguageModelInput,\n { raw: BaseMessage; parsed: RunOutput }\n > {\n return RunnableLambda.from(async (input) => {\n const message = await this.invoke(input);\n if (message.tool_calls?.[0]?.args) {\n return message.tool_calls[0].args as RunOutput;\n }\n if (typeof message.content === \"string\") {\n return JSON.parse(message.content);\n }\n throw new Error(\"No structured output found\");\n }) as Runnable;\n }\n}\n"],"mappings":";;;;;;;;AAwDA,IAAa,gBAAb,cAAmCA,kDAAc;CAC/C,oBAAoB;AAClB,SAAO,CAAE;CACV;CAED,WAAmB;AACjB,SAAO;CACR;CAED,MAAM,UACJC,UACAC,SACAC,YACqB;AACrB,MAAI,SAAS,MAAM,OACjB,QAAO,EACL,aAAa,CACX;GACE,SAAS,IAAIC,qBAAU,QAAQ,KAAK;GACpC,MAAM,QAAQ,KAAK;EACpB,CACF,EACF;EAEH,MAAM,OAAO,SACV,IAAI,CAAC,MAAM;AACV,OAAI,OAAO,EAAE,YAAY,SACvB,QAAO,EAAE;AAEX,UAAO,KAAK,UAAU,EAAE,SAAS,MAAM,EAAE;EAC1C,EAAC,CACD,KAAK,KAAK;EACb,MAAM,YAAY,kBAAkB,KAAK;AACzC,SAAO;GACL,aAAa,CACX;IACE,SAAS,IAAIA,qBAAU;IACvB;GACD,CACF;GACD,WAAW,CAAE;EACd;CACF;AACF;AAED,IAAa,yBAAb,MAAa,+BAA+BJ,kDAAiD;CAC3F,QAAQ;CAER,YAA2B,CAAE;CAE7B,SAA2B,CAAE;CAE7B,YAA2D;CAE3D;CAEA,AAAQ,QAAuC,CAAE;CAEjD,YAAY,EACV,QAAQ,IACR,YAAY,CAAE,GACd,SAAS,CAAE,GACX,YAAY,UACZ,kBACA,GAAG,MAC0C,EAAE;EAC/C,MAAM,KAAK;EACX,KAAK,QAAQ;EACb,KAAK,YAAY;EACjB,KAAK,SAAS;EACd,KAAK,YAAY;EACjB,KAAK,oBAAoB;CAC1B;CAED,WAAW;AACT,SAAO;CACR;CAED,UAAUK,OAAsC;EAC9C,MAAM,SAAS,CAAC,GAAG,KAAK,OAAO,GAAG,KAAM;EAExC,MAAM,YAAY,OAAO,IAAI,CAAC,MAAM;A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,KAAK,OAAO,MAAM;AACxC,OAAI,QAAQ,aAAa,IAAI,KAC3B,QAAO,QAAQ,WAAW,GAAG;AAE/B,OAAI,OAAO,QAAQ,YAAY,SAC7B,QAAO,KAAK,MAAM,QAAQ,QAAQ;AAEpC,SAAM,IAAI,MAAM;EACjB,EAAC;CACH;AACF"}
|
|
@@ -108,6 +108,8 @@ declare class FakeListChatModel extends BaseChatModel<FakeListChatModelCallOptio
|
|
|
108
108
|
sleep?: number;
|
|
109
109
|
emitCustomEvent: boolean;
|
|
110
110
|
generationInfo?: Record<string, unknown>;
|
|
111
|
+
private tools;
|
|
112
|
+
toolStyle: "openai" | "anthropic" | "bedrock" | "google";
|
|
111
113
|
constructor(params: FakeChatInput);
|
|
112
114
|
_combineLLMOutput(): never[];
|
|
113
115
|
_llmType(): string;
|
|
@@ -122,6 +124,7 @@ declare class FakeListChatModel extends BaseChatModel<FakeListChatModelCallOptio
|
|
|
122
124
|
_createResponseChunk(text: string, generationInfo?: Record<string, any>): ChatGenerationChunk;
|
|
123
125
|
_currentResponse(): string;
|
|
124
126
|
_incrementResponse(): void;
|
|
127
|
+
bindTools(tools: (StructuredTool | ToolSpec)[]): Runnable<BaseLanguageModelInput, AIMessageChunk<MessageStructure>, FakeListChatModelCallOptions>;
|
|
125
128
|
withStructuredOutput<RunOutput extends Record<string, any> = Record<string, any>>(_params: StructuredOutputMethodParams<RunOutput, false> | InteropZodType<RunOutput> | Record<string, any>, config?: StructuredOutputMethodOptions<false>): Runnable<BaseLanguageModelInput, RunOutput>;
|
|
126
129
|
withStructuredOutput<RunOutput extends Record<string, any> = Record<string, any>>(_params: StructuredOutputMethodParams<RunOutput, true> | InteropZodType<RunOutput> | Record<string, any>, config?: StructuredOutputMethodOptions<true>): Runnable<BaseLanguageModelInput, {
|
|
127
130
|
raw: BaseMessage;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chat_models.d.cts","names":["CallbackManagerForLLMRun","BaseChatModel","BaseChatModelCallOptions","BaseChatModelParams","BaseLLMParams","BaseMessage","AIMessage","AIMessageChunk","ChatResult","ChatGenerationChunk","Runnable","StructuredTool","StructuredOutputMethodParams","BaseLanguageModelInput","StructuredOutputMethodOptions","InteropZodType","ToolSpec","Record","FakeStreamingChatModelCallOptions","FakeStreamingChatModelFields","FakeChatModel","Promise","FakeStreamingChatModel","sleep","responses","chunks","toolStyle","thrownErrorString","______messages_message_js0","MessageStructure","AsyncGenerator","FakeChatInput","FakeListChatModelCallOptions","FakeListChatModel","RunOutput"],"sources":["../../../src/utils/testing/chat_models.d.ts"],"sourcesContent":["import { CallbackManagerForLLMRun } from \"../../callbacks/manager.js\";\nimport { BaseChatModel, BaseChatModelCallOptions, BaseChatModelParams } from \"../../language_models/chat_models.js\";\nimport { BaseLLMParams } from \"../../language_models/llms.js\";\nimport { BaseMessage, AIMessage, AIMessageChunk } from \"../../messages/index.js\";\nimport { type ChatResult, ChatGenerationChunk } from \"../../outputs.js\";\nimport { Runnable } from \"../../runnables/base.js\";\nimport { StructuredTool } from \"../../tools/index.js\";\nimport { StructuredOutputMethodParams, BaseLanguageModelInput, StructuredOutputMethodOptions } from \"../../language_models/base.js\";\nimport { InteropZodType } from \"../types/zod.js\";\n/** Minimal shape actually needed by `bindTools` */\nexport interface ToolSpec {\n name: string;\n description?: string;\n schema: InteropZodType | Record<string, unknown>;\n}\n/**\n * Interface specific to the Fake Streaming Chat model.\n */\nexport interface FakeStreamingChatModelCallOptions extends BaseChatModelCallOptions {\n}\n/**\n * Interface for the Constructor-field specific to the Fake Streaming Chat model (all optional because we fill in defaults).\n */\nexport interface FakeStreamingChatModelFields extends BaseChatModelParams {\n /** Milliseconds to pause between fallback char-by-char chunks */\n sleep?: number;\n /** Full AI messages to fall back to when no `chunks` supplied */\n responses?: BaseMessage[];\n /** Exact chunks to emit (can include tool-call deltas) */\n chunks?: AIMessageChunk[];\n /** How tool specs are formatted in `bindTools` */\n toolStyle?: \"openai\" | \"anthropic\" | \"bedrock\" | \"google\";\n /** Throw this error instead of streaming (useful in tests) */\n thrownErrorString?: string;\n}\nexport declare class FakeChatModel extends BaseChatModel {\n _combineLLMOutput(): never[];\n _llmType(): string;\n _generate(messages: BaseMessage[], options?: this[\"ParsedCallOptions\"], runManager?: CallbackManagerForLLMRun): Promise<ChatResult>;\n}\nexport declare class FakeStreamingChatModel extends BaseChatModel<FakeStreamingChatModelCallOptions> {\n sleep: number;\n responses: BaseMessage[];\n chunks: AIMessageChunk[];\n toolStyle: \"openai\" | \"anthropic\" | \"bedrock\" | \"google\";\n thrownErrorString?: string;\n private tools;\n constructor({ sleep, responses, chunks, toolStyle, thrownErrorString, ...rest }: FakeStreamingChatModelFields & BaseLLMParams);\n _llmType(): string;\n bindTools(tools: (StructuredTool | ToolSpec)[]): Runnable<BaseLanguageModelInput, AIMessageChunk<import(\"../../messages/message.js\").MessageStructure>, FakeStreamingChatModelCallOptions>;\n _generate(messages: BaseMessage[], _options: this[\"ParsedCallOptions\"], _runManager?: CallbackManagerForLLMRun): Promise<ChatResult>;\n _streamResponseChunks(_messages: BaseMessage[], _options: this[\"ParsedCallOptions\"], runManager?: CallbackManagerForLLMRun): AsyncGenerator<ChatGenerationChunk>;\n}\n/**\n * Interface for the input parameters specific to the Fake List Chat model.\n */\nexport interface FakeChatInput extends BaseChatModelParams {\n /** Responses to return */\n responses: string[];\n /** Time to sleep in milliseconds between responses */\n sleep?: number;\n emitCustomEvent?: boolean;\n /**\n * Generation info to include on the last chunk during streaming.\n * This gets merged into response_metadata by the base chat model.\n * Useful for testing response_metadata propagation (e.g., finish_reason).\n */\n generationInfo?: Record<string, unknown>;\n}\nexport interface FakeListChatModelCallOptions extends BaseChatModelCallOptions {\n thrownErrorString?: string;\n}\n/**\n * A fake Chat Model that returns a predefined list of responses. It can be used\n * for testing purposes.\n * @example\n * ```typescript\n * const chat = new FakeListChatModel({\n * responses: [\"I'll callback later.\", \"You 'console' them!\"]\n * });\n *\n * const firstMessage = new HumanMessage(\"You want to hear a JavaScript joke?\");\n * const secondMessage = new HumanMessage(\"How do you cheer up a JavaScript developer?\");\n *\n * // Call the chat model with a message and log the response\n * const firstResponse = await chat.call([firstMessage]);\n * console.log({ firstResponse });\n *\n * const secondResponse = await chat.call([secondMessage]);\n * console.log({ secondResponse });\n * ```\n */\nexport declare class FakeListChatModel extends BaseChatModel<FakeListChatModelCallOptions> {\n static lc_name(): string;\n lc_serializable: boolean;\n responses: string[];\n i: number;\n sleep?: number;\n emitCustomEvent: boolean;\n generationInfo?: Record<string, unknown>;\n constructor(params: FakeChatInput);\n _combineLLMOutput(): never[];\n _llmType(): string;\n _generate(_messages: BaseMessage[], options?: this[\"ParsedCallOptions\"], runManager?: CallbackManagerForLLMRun): Promise<ChatResult>;\n _formatGeneration(text: string): {\n message: AIMessage<import(\"../../messages/message.js\").MessageStructure>;\n text: string;\n };\n _streamResponseChunks(_messages: BaseMessage[], options: this[\"ParsedCallOptions\"], runManager?: CallbackManagerForLLMRun): AsyncGenerator<ChatGenerationChunk>;\n _sleepIfRequested(): Promise<void>;\n _sleep(): Promise<void>;\n _createResponseChunk(text: string, generationInfo?: Record<string, any>): ChatGenerationChunk;\n _currentResponse(): string;\n _incrementResponse(): void;\n withStructuredOutput<RunOutput extends Record<string, any> = Record<string, any>>(_params: StructuredOutputMethodParams<RunOutput, false> | InteropZodType<RunOutput> | Record<string, any>, config?: StructuredOutputMethodOptions<false>): Runnable<BaseLanguageModelInput, RunOutput>;\n withStructuredOutput<RunOutput extends Record<string, any> = Record<string, any>>(_params: StructuredOutputMethodParams<RunOutput, true> | InteropZodType<RunOutput> | Record<string, any>, config?: StructuredOutputMethodOptions<true>): Runnable<BaseLanguageModelInput, {\n raw: BaseMessage;\n parsed: RunOutput;\n }>;\n}\n//# sourceMappingURL=chat_models.d.ts.map"],"mappings":";;;;;;;;;;;;;;UAUiBgB,QAAAA;;;EAAAA,MAAAA,EAGLD,cAHa,GAGIE,MAAjBF,CAAAA,MAAAA,EAAiBE,OAAM,CAAA;A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A,EAAAA,MAAAA;EAvBhMT,eAAAA,EAAAA,OAAAA;EAAa,cAAA,CAAA,EAOvCgB,MAPuC,CAAA,MAAA,EAAA,OAAA,CAAA;sBAQpCc;;;uBAGC1B,iEAAiEL,2BAA2BqB,QAAQb;;aAE5GF;;;mCAGoBD,gEAAgEL,2BAA2B8B,eAAerB;uBACtHY;YACXA;sDAC0CJ,sBAAsBR;;;yCAGnCQ,sBAAsBA,8BAA8BL,6BAA6BsB,oBAAoBnB,eAAemB,aAAajB,8BAA8BH,uCAAuCJ,SAASG,wBAAwBqB;yCACvOjB,sBAAsBA,8BAA8BL,6BAA6BsB,mBAAmBnB,eAAemB,aAAajB,8BAA8BH,sCAAsCJ,SAASG;SAC3OR;YACG6B"}
|
|
1
|
+
{"version":3,"file":"chat_models.d.cts","names":["CallbackManagerForLLMRun","BaseChatModel","BaseChatModelCallOptions","BaseChatModelParams","BaseLLMParams","BaseMessage","AIMessage","AIMessageChunk","ChatResult","ChatGenerationChunk","Runnable","StructuredTool","StructuredOutputMethodParams","BaseLanguageModelInput","StructuredOutputMethodOptions","InteropZodType","ToolSpec","Record","FakeStreamingChatModelCallOptions","FakeStreamingChatModelFields","FakeChatModel","Promise","FakeStreamingChatModel","sleep","responses","chunks","toolStyle","thrownErrorString","______messages_message_js0","MessageStructure","AsyncGenerator","FakeChatInput","FakeListChatModelCallOptions","FakeListChatModel","RunOutput"],"sources":["../../../src/utils/testing/chat_models.d.ts"],"sourcesContent":["import { CallbackManagerForLLMRun } from \"../../callbacks/manager.js\";\nimport { BaseChatModel, BaseChatModelCallOptions, BaseChatModelParams } from \"../../language_models/chat_models.js\";\nimport { BaseLLMParams } from \"../../language_models/llms.js\";\nimport { BaseMessage, AIMessage, AIMessageChunk } from \"../../messages/index.js\";\nimport { type ChatResult, ChatGenerationChunk } from \"../../outputs.js\";\nimport { Runnable } from \"../../runnables/base.js\";\nimport { StructuredTool } from \"../../tools/index.js\";\nimport { StructuredOutputMethodParams, BaseLanguageModelInput, StructuredOutputMethodOptions } from \"../../language_models/base.js\";\nimport { InteropZodType } from \"../types/zod.js\";\n/** Minimal shape actually needed by `bindTools` */\nexport interface ToolSpec {\n name: string;\n description?: string;\n schema: InteropZodType | Record<string, unknown>;\n}\n/**\n * Interface specific to the Fake Streaming Chat model.\n */\nexport interface FakeStreamingChatModelCallOptions extends BaseChatModelCallOptions {\n}\n/**\n * Interface for the Constructor-field specific to the Fake Streaming Chat model (all optional because we fill in defaults).\n */\nexport interface FakeStreamingChatModelFields extends BaseChatModelParams {\n /** Milliseconds to pause between fallback char-by-char chunks */\n sleep?: number;\n /** Full AI messages to fall back to when no `chunks` supplied */\n responses?: BaseMessage[];\n /** Exact chunks to emit (can include tool-call deltas) */\n chunks?: AIMessageChunk[];\n /** How tool specs are formatted in `bindTools` */\n toolStyle?: \"openai\" | \"anthropic\" | \"bedrock\" | \"google\";\n /** Throw this error instead of streaming (useful in tests) */\n thrownErrorString?: string;\n}\nexport declare class FakeChatModel extends BaseChatModel {\n _combineLLMOutput(): never[];\n _llmType(): string;\n _generate(messages: BaseMessage[], options?: this[\"ParsedCallOptions\"], runManager?: CallbackManagerForLLMRun): Promise<ChatResult>;\n}\nexport declare class FakeStreamingChatModel extends BaseChatModel<FakeStreamingChatModelCallOptions> {\n sleep: number;\n responses: BaseMessage[];\n chunks: AIMessageChunk[];\n toolStyle: \"openai\" | \"anthropic\" | \"bedrock\" | \"google\";\n thrownErrorString?: string;\n private tools;\n constructor({ sleep, responses, chunks, toolStyle, thrownErrorString, ...rest }: FakeStreamingChatModelFields & BaseLLMParams);\n _llmType(): string;\n bindTools(tools: (StructuredTool | ToolSpec)[]): Runnable<BaseLanguageModelInput, AIMessageChunk<import(\"../../messages/message.js\").MessageStructure>, FakeStreamingChatModelCallOptions>;\n _generate(messages: BaseMessage[], _options: this[\"ParsedCallOptions\"], _runManager?: CallbackManagerForLLMRun): Promise<ChatResult>;\n _streamResponseChunks(_messages: BaseMessage[], _options: this[\"ParsedCallOptions\"], runManager?: CallbackManagerForLLMRun): AsyncGenerator<ChatGenerationChunk>;\n}\n/**\n * Interface for the input parameters specific to the Fake List Chat model.\n */\nexport interface FakeChatInput extends BaseChatModelParams {\n /** Responses to return */\n responses: string[];\n /** Time to sleep in milliseconds between responses */\n sleep?: number;\n emitCustomEvent?: boolean;\n /**\n * Generation info to include on the last chunk during streaming.\n * This gets merged into response_metadata by the base chat model.\n * Useful for testing response_metadata propagation (e.g., finish_reason).\n */\n generationInfo?: Record<string, unknown>;\n}\nexport interface FakeListChatModelCallOptions extends BaseChatModelCallOptions {\n thrownErrorString?: string;\n}\n/**\n * A fake Chat Model that returns a predefined list of responses. It can be used\n * for testing purposes.\n * @example\n * ```typescript\n * const chat = new FakeListChatModel({\n * responses: [\"I'll callback later.\", \"You 'console' them!\"]\n * });\n *\n * const firstMessage = new HumanMessage(\"You want to hear a JavaScript joke?\");\n * const secondMessage = new HumanMessage(\"How do you cheer up a JavaScript developer?\");\n *\n * // Call the chat model with a message and log the response\n * const firstResponse = await chat.call([firstMessage]);\n * console.log({ firstResponse });\n *\n * const secondResponse = await chat.call([secondMessage]);\n * console.log({ secondResponse });\n * ```\n */\nexport declare class FakeListChatModel extends BaseChatModel<FakeListChatModelCallOptions> {\n static lc_name(): string;\n lc_serializable: boolean;\n responses: string[];\n i: number;\n sleep?: number;\n emitCustomEvent: boolean;\n generationInfo?: Record<string, unknown>;\n private tools;\n toolStyle: \"openai\" | \"anthropic\" | \"bedrock\" | \"google\";\n constructor(params: FakeChatInput);\n _combineLLMOutput(): never[];\n _llmType(): string;\n _generate(_messages: BaseMessage[], options?: this[\"ParsedCallOptions\"], runManager?: CallbackManagerForLLMRun): Promise<ChatResult>;\n _formatGeneration(text: string): {\n message: AIMessage<import(\"../../messages/message.js\").MessageStructure>;\n text: string;\n };\n _streamResponseChunks(_messages: BaseMessage[], options: this[\"ParsedCallOptions\"], runManager?: CallbackManagerForLLMRun): AsyncGenerator<ChatGenerationChunk>;\n _sleepIfRequested(): Promise<void>;\n _sleep(): Promise<void>;\n _createResponseChunk(text: string, generationInfo?: Record<string, any>): ChatGenerationChunk;\n _currentResponse(): string;\n _incrementResponse(): void;\n bindTools(tools: (StructuredTool | ToolSpec)[]): Runnable<BaseLanguageModelInput, AIMessageChunk<import(\"../../messages/message.js\").MessageStructure>, FakeListChatModelCallOptions>;\n withStructuredOutput<RunOutput extends Record<string, any> = Record<string, any>>(_params: StructuredOutputMethodParams<RunOutput, false> | InteropZodType<RunOutput> | Record<string, any>, config?: StructuredOutputMethodOptions<false>): Runnable<BaseLanguageModelInput, RunOutput>;\n withStructuredOutput<RunOutput extends Record<string, any> = Record<string, any>>(_params: StructuredOutputMethodParams<RunOutput, true> | InteropZodType<RunOutput> | Record<string, any>, config?: StructuredOutputMethodOptions<true>): Runnable<BaseLanguageModelInput, {\n raw: BaseMessage;\n parsed: RunOutput;\n }>;\n}\n//# sourceMappingURL=chat_models.d.ts.map"],"mappings":";;;;;;;;;;;;;;UAUiBgB,QAAAA;;;EAAAA,MAAAA,EAGLD,cAHa,GAGIE,MAAjBF,CAAAA,MAAAA,EAAiBE,OAAM,CAAA;AAKnC;AAKA;;;AAAsDd,UALrCe,iCAAAA,SAA0ChB,wBAKLC,CAAAA,CAAmB;AAYzE;;;AAG4HK,UAf3GW,4BAAAA,SAAqChB,mBAesEK,CAAAA;EAARa;EAHzEpB,KAAAA,CAAAA,EAAAA,MAAAA;EAAa;EAKnCqB,SAAAA,CAAAA,EAbLjB,WAaKiB,EAAsB;EAAuBJ;EAEnDb,MAAAA,CAAAA,EAbFE,cAaEF,EAAAA;EACHE;EAIMgB,SAAAA,CAAAA,EAAAA,QAAAA,GAAAA,WAAAA,GAAAA,SAAAA,GAAAA,QAAAA;EAAOC;EAAWC,iBAAAA,CAAAA,EAAAA,MAAAA;;AAAmBE,cAZlCP,aAAAA,SAAsBnB,aAAAA,CAYY0B;EAA8BR,iBAAAA,CAAAA,CAAAA,EAAAA,KAAAA,EAAAA;EAA+Bf,QA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