@langchain/core 1.1.5-dev-1765433794876 → 1.1.6

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.
Files changed (295) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/agents.cjs +1 -0
  3. package/agents.d.cts +1 -0
  4. package/agents.d.ts +1 -0
  5. package/agents.js +1 -0
  6. package/caches.cjs +1 -0
  7. package/caches.d.cts +1 -0
  8. package/caches.d.ts +1 -0
  9. package/caches.js +1 -0
  10. package/callbacks/base.cjs +1 -0
  11. package/callbacks/base.d.cts +1 -0
  12. package/callbacks/base.d.ts +1 -0
  13. package/callbacks/base.js +1 -0
  14. package/callbacks/dispatch/web.cjs +1 -0
  15. package/callbacks/dispatch/web.d.cts +1 -0
  16. package/callbacks/dispatch/web.d.ts +1 -0
  17. package/callbacks/dispatch/web.js +1 -0
  18. package/callbacks/dispatch.cjs +1 -0
  19. package/callbacks/dispatch.d.cts +1 -0
  20. package/callbacks/dispatch.d.ts +1 -0
  21. package/callbacks/dispatch.js +1 -0
  22. package/callbacks/manager.cjs +1 -0
  23. package/callbacks/manager.d.cts +1 -0
  24. package/callbacks/manager.d.ts +1 -0
  25. package/callbacks/manager.js +1 -0
  26. package/callbacks/promises.cjs +1 -0
  27. package/callbacks/promises.d.cts +1 -0
  28. package/callbacks/promises.d.ts +1 -0
  29. package/callbacks/promises.js +1 -0
  30. package/chat_history.cjs +1 -0
  31. package/chat_history.d.cts +1 -0
  32. package/chat_history.d.ts +1 -0
  33. package/chat_history.js +1 -0
  34. package/context.cjs +1 -0
  35. package/context.d.cts +1 -0
  36. package/context.d.ts +1 -0
  37. package/context.js +1 -0
  38. package/dist/caches/index.d.ts.map +1 -1
  39. package/dist/callbacks/base.d.ts.map +1 -1
  40. package/dist/language_models/chat_models.d.ts.map +1 -1
  41. package/dist/load/index.d.cts.map +1 -1
  42. package/dist/memory.d.ts.map +1 -1
  43. package/dist/messages/base.cjs +2 -2
  44. package/dist/messages/base.cjs.map +1 -1
  45. package/dist/messages/base.d.cts +1 -1
  46. package/dist/messages/base.d.cts.map +1 -1
  47. package/dist/messages/base.d.ts +1 -1
  48. package/dist/messages/base.d.ts.map +1 -1
  49. package/dist/messages/base.js +2 -2
  50. package/dist/messages/base.js.map +1 -1
  51. package/dist/messages/format.cjs +1 -1
  52. package/dist/messages/format.cjs.map +1 -1
  53. package/dist/messages/format.js +1 -1
  54. package/dist/messages/format.js.map +1 -1
  55. package/dist/messages/tool.d.cts.map +1 -1
  56. package/dist/runnables/graph_mermaid.cjs +9 -3
  57. package/dist/runnables/graph_mermaid.cjs.map +1 -1
  58. package/dist/runnables/graph_mermaid.js +9 -3
  59. package/dist/runnables/graph_mermaid.js.map +1 -1
  60. package/dist/tracers/base.cjs +9 -10
  61. package/dist/tracers/base.cjs.map +1 -1
  62. package/dist/tracers/base.js +9 -10
  63. package/dist/tracers/base.js.map +1 -1
  64. package/dist/tracers/event_stream.cjs +5 -1
  65. package/dist/tracers/event_stream.cjs.map +1 -1
  66. package/dist/tracers/event_stream.d.cts.map +1 -1
  67. package/dist/tracers/event_stream.d.ts.map +1 -1
  68. package/dist/tracers/event_stream.js +5 -1
  69. package/dist/tracers/event_stream.js.map +1 -1
  70. package/dist/utils/fast-json-patch/src/core.cjs +10 -0
  71. package/dist/utils/fast-json-patch/src/core.cjs.map +1 -1
  72. package/dist/utils/fast-json-patch/src/core.js +10 -0
  73. package/dist/utils/fast-json-patch/src/core.js.map +1 -1
  74. package/dist/utils/json_schema.cjs +4 -3
  75. package/dist/utils/json_schema.cjs.map +1 -1
  76. package/dist/utils/json_schema.d.cts +5 -2
  77. package/dist/utils/json_schema.d.cts.map +1 -1
  78. package/dist/utils/json_schema.d.ts +5 -2
  79. package/dist/utils/json_schema.d.ts.map +1 -1
  80. package/dist/utils/json_schema.js +4 -3
  81. package/dist/utils/json_schema.js.map +1 -1
  82. package/dist/utils/testing/chat_models.cjs +49 -2
  83. package/dist/utils/testing/chat_models.cjs.map +1 -1
  84. package/dist/utils/testing/chat_models.d.cts +4 -1
  85. package/dist/utils/testing/chat_models.d.cts.map +1 -1
  86. package/dist/utils/testing/chat_models.d.ts +4 -1
  87. package/dist/utils/testing/chat_models.d.ts.map +1 -1
  88. package/dist/utils/testing/chat_models.js +49 -2
  89. package/dist/utils/testing/chat_models.js.map +1 -1
  90. package/dist/utils/types/zod.cjs +1 -1
  91. package/dist/utils/types/zod.cjs.map +1 -1
  92. package/dist/utils/types/zod.js +1 -1
  93. package/dist/utils/types/zod.js.map +1 -1
  94. package/dist/vectorstores.d.cts.map +1 -1
  95. package/document_loaders/base.cjs +1 -0
  96. package/document_loaders/base.d.cts +1 -0
  97. package/document_loaders/base.d.ts +1 -0
  98. package/document_loaders/base.js +1 -0
  99. package/document_loaders/langsmith.cjs +1 -0
  100. package/document_loaders/langsmith.d.cts +1 -0
  101. package/document_loaders/langsmith.d.ts +1 -0
  102. package/document_loaders/langsmith.js +1 -0
  103. package/documents.cjs +1 -0
  104. package/documents.d.cts +1 -0
  105. package/documents.d.ts +1 -0
  106. package/documents.js +1 -0
  107. package/embeddings.cjs +1 -0
  108. package/embeddings.d.cts +1 -0
  109. package/embeddings.d.ts +1 -0
  110. package/embeddings.js +1 -0
  111. package/example_selectors.cjs +1 -0
  112. package/example_selectors.d.cts +1 -0
  113. package/example_selectors.d.ts +1 -0
  114. package/example_selectors.js +1 -0
  115. package/indexing.cjs +1 -0
  116. package/indexing.d.cts +1 -0
  117. package/indexing.d.ts +1 -0
  118. package/indexing.js +1 -0
  119. package/language_models/base.cjs +1 -0
  120. package/language_models/base.d.cts +1 -0
  121. package/language_models/base.d.ts +1 -0
  122. package/language_models/base.js +1 -0
  123. package/language_models/chat_models.cjs +1 -0
  124. package/language_models/chat_models.d.cts +1 -0
  125. package/language_models/chat_models.d.ts +1 -0
  126. package/language_models/chat_models.js +1 -0
  127. package/language_models/llms.cjs +1 -0
  128. package/language_models/llms.d.cts +1 -0
  129. package/language_models/llms.d.ts +1 -0
  130. package/language_models/llms.js +1 -0
  131. package/language_models/profile.cjs +1 -0
  132. package/language_models/profile.d.cts +1 -0
  133. package/language_models/profile.d.ts +1 -0
  134. package/language_models/profile.js +1 -0
  135. package/load/serializable.cjs +1 -0
  136. package/load/serializable.d.cts +1 -0
  137. package/load/serializable.d.ts +1 -0
  138. package/load/serializable.js +1 -0
  139. package/load.cjs +1 -0
  140. package/load.d.cts +1 -0
  141. package/load.d.ts +1 -0
  142. package/load.js +1 -0
  143. package/memory.cjs +1 -0
  144. package/memory.d.cts +1 -0
  145. package/memory.d.ts +1 -0
  146. package/memory.js +1 -0
  147. package/messages/tool.cjs +1 -0
  148. package/messages/tool.d.cts +1 -0
  149. package/messages/tool.d.ts +1 -0
  150. package/messages/tool.js +1 -0
  151. package/messages.cjs +1 -0
  152. package/messages.d.cts +1 -0
  153. package/messages.d.ts +1 -0
  154. package/messages.js +1 -0
  155. package/output_parsers/openai_functions.cjs +1 -0
  156. package/output_parsers/openai_functions.d.cts +1 -0
  157. package/output_parsers/openai_functions.d.ts +1 -0
  158. package/output_parsers/openai_functions.js +1 -0
  159. package/output_parsers/openai_tools.cjs +1 -0
  160. package/output_parsers/openai_tools.d.cts +1 -0
  161. package/output_parsers/openai_tools.d.ts +1 -0
  162. package/output_parsers/openai_tools.js +1 -0
  163. package/output_parsers.cjs +1 -0
  164. package/output_parsers.d.cts +1 -0
  165. package/output_parsers.d.ts +1 -0
  166. package/output_parsers.js +1 -0
  167. package/outputs.cjs +1 -0
  168. package/outputs.d.cts +1 -0
  169. package/outputs.d.ts +1 -0
  170. package/outputs.js +1 -0
  171. package/package.json +1 -1
  172. package/prompt_values.cjs +1 -0
  173. package/prompt_values.d.cts +1 -0
  174. package/prompt_values.d.ts +1 -0
  175. package/prompt_values.js +1 -0
  176. package/prompts.cjs +1 -0
  177. package/prompts.d.cts +1 -0
  178. package/prompts.d.ts +1 -0
  179. package/prompts.js +1 -0
  180. package/retrievers/document_compressors.cjs +1 -0
  181. package/retrievers/document_compressors.d.cts +1 -0
  182. package/retrievers/document_compressors.d.ts +1 -0
  183. package/retrievers/document_compressors.js +1 -0
  184. package/retrievers.cjs +1 -0
  185. package/retrievers.d.cts +1 -0
  186. package/retrievers.d.ts +1 -0
  187. package/retrievers.js +1 -0
  188. package/runnables/graph.cjs +1 -0
  189. package/runnables/graph.d.cts +1 -0
  190. package/runnables/graph.d.ts +1 -0
  191. package/runnables/graph.js +1 -0
  192. package/runnables.cjs +1 -0
  193. package/runnables.d.cts +1 -0
  194. package/runnables.d.ts +1 -0
  195. package/runnables.js +1 -0
  196. package/singletons.cjs +1 -0
  197. package/singletons.d.cts +1 -0
  198. package/singletons.d.ts +1 -0
  199. package/singletons.js +1 -0
  200. package/stores.cjs +1 -0
  201. package/stores.d.cts +1 -0
  202. package/stores.d.ts +1 -0
  203. package/stores.js +1 -0
  204. package/structured_query.cjs +1 -0
  205. package/structured_query.d.cts +1 -0
  206. package/structured_query.d.ts +1 -0
  207. package/structured_query.js +1 -0
  208. package/tools.cjs +1 -0
  209. package/tools.d.cts +1 -0
  210. package/tools.d.ts +1 -0
  211. package/tools.js +1 -0
  212. package/tracers/base.cjs +1 -0
  213. package/tracers/base.d.cts +1 -0
  214. package/tracers/base.d.ts +1 -0
  215. package/tracers/base.js +1 -0
  216. package/tracers/console.cjs +1 -0
  217. package/tracers/console.d.cts +1 -0
  218. package/tracers/console.d.ts +1 -0
  219. package/tracers/console.js +1 -0
  220. package/tracers/log_stream.cjs +1 -0
  221. package/tracers/log_stream.d.cts +1 -0
  222. package/tracers/log_stream.d.ts +1 -0
  223. package/tracers/log_stream.js +1 -0
  224. package/tracers/run_collector.cjs +1 -0
  225. package/tracers/run_collector.d.cts +1 -0
  226. package/tracers/run_collector.d.ts +1 -0
  227. package/tracers/run_collector.js +1 -0
  228. package/tracers/tracer_langchain.cjs +1 -0
  229. package/tracers/tracer_langchain.d.cts +1 -0
  230. package/tracers/tracer_langchain.d.ts +1 -0
  231. package/tracers/tracer_langchain.js +1 -0
  232. package/types/stream.cjs +1 -0
  233. package/types/stream.d.cts +1 -0
  234. package/types/stream.d.ts +1 -0
  235. package/types/stream.js +1 -0
  236. package/utils/async_caller.cjs +1 -0
  237. package/utils/async_caller.d.cts +1 -0
  238. package/utils/async_caller.d.ts +1 -0
  239. package/utils/async_caller.js +1 -0
  240. package/utils/chunk_array.cjs +1 -0
  241. package/utils/chunk_array.d.cts +1 -0
  242. package/utils/chunk_array.d.ts +1 -0
  243. package/utils/chunk_array.js +1 -0
  244. package/utils/env.cjs +1 -0
  245. package/utils/env.d.cts +1 -0
  246. package/utils/env.d.ts +1 -0
  247. package/utils/env.js +1 -0
  248. package/utils/event_source_parse.cjs +1 -0
  249. package/utils/event_source_parse.d.cts +1 -0
  250. package/utils/event_source_parse.d.ts +1 -0
  251. package/utils/event_source_parse.js +1 -0
  252. package/utils/format.cjs +1 -0
  253. package/utils/format.d.cts +1 -0
  254. package/utils/format.d.ts +1 -0
  255. package/utils/format.js +1 -0
  256. package/utils/function_calling.cjs +1 -0
  257. package/utils/function_calling.d.cts +1 -0
  258. package/utils/function_calling.d.ts +1 -0
  259. package/utils/function_calling.js +1 -0
  260. package/utils/hash.cjs +1 -0
  261. package/utils/hash.d.cts +1 -0
  262. package/utils/hash.d.ts +1 -0
  263. package/utils/hash.js +1 -0
  264. package/utils/json_patch.cjs +1 -0
  265. package/utils/json_patch.d.cts +1 -0
  266. package/utils/json_patch.d.ts +1 -0
  267. package/utils/json_patch.js +1 -0
  268. package/utils/json_schema.cjs +1 -0
  269. package/utils/json_schema.d.cts +1 -0
  270. package/utils/json_schema.d.ts +1 -0
  271. package/utils/json_schema.js +1 -0
  272. package/utils/math.cjs +1 -0
  273. package/utils/math.d.cts +1 -0
  274. package/utils/math.d.ts +1 -0
  275. package/utils/math.js +1 -0
  276. package/utils/stream.cjs +1 -0
  277. package/utils/stream.d.cts +1 -0
  278. package/utils/stream.d.ts +1 -0
  279. package/utils/stream.js +1 -0
  280. package/utils/testing.cjs +1 -0
  281. package/utils/testing.d.cts +1 -0
  282. package/utils/testing.d.ts +1 -0
  283. package/utils/testing.js +1 -0
  284. package/utils/tiktoken.cjs +1 -0
  285. package/utils/tiktoken.d.cts +1 -0
  286. package/utils/tiktoken.d.ts +1 -0
  287. package/utils/tiktoken.js +1 -0
  288. package/utils/types.cjs +1 -0
  289. package/utils/types.d.cts +1 -0
  290. package/utils/types.d.ts +1 -0
  291. package/utils/types.js +1 -0
  292. package/vectorstores.cjs +1 -0
  293. package/vectorstores.d.cts +1 -0
  294. package/vectorstores.d.ts +1 -0
  295. package/vectorstores.js +1 -0
@@ -1 +1 @@
1
- {"version":3,"file":"event_stream.d.ts","names":["BaseTracer","Run","BaseCallbackHandler","BaseCallbackHandlerInput","CallbackHandlerPrefersStreaming","IterableReadableStream","StreamEventData","StreamEvent","Record","RunInfo","EventStreamCallbackHandlerInput","isStreamEventsHandler","EventStreamCallbackHandler","T","TransformStream","WritableStreamDefaultWriter","Symbol","asyncIterator","Promise","AsyncGenerator"],"sources":["../../src/tracers/event_stream.d.ts"],"sourcesContent":["import { BaseTracer, type Run } from \"./base.js\";\nimport { BaseCallbackHandler, BaseCallbackHandlerInput, CallbackHandlerPrefersStreaming } from \"../callbacks/base.js\";\nimport { IterableReadableStream } from \"../utils/stream.js\";\n/**\n * Data associated with a StreamEvent.\n */\nexport type StreamEventData = {\n /**\n * The input passed to the runnable that generated the event.\n * Inputs will sometimes be available at the *START* of the runnable, and\n * sometimes at the *END* of the runnable.\n * If a runnable is able to stream its inputs, then its input by definition\n * won't be known until the *END* of the runnable when it has finished streaming\n * its inputs.\n */\n input?: any;\n /**\n * The output of the runnable that generated the event.\n * Outputs will only be available at the *END* of the runnable.\n * For most runnables, this field can be inferred from the `chunk` field,\n * though there might be some exceptions for special cased runnables (e.g., like\n * chat models), which may return more information.\n */\n output?: any;\n /**\n * A streaming chunk from the output that generated the event.\n * chunks support addition in general, and adding them up should result\n * in the output of the runnable that generated the event.\n */\n chunk?: any;\n};\n/**\n * A streaming event.\n *\n * Schema of a streaming event which is produced from the streamEvents method.\n */\nexport type StreamEvent = {\n /**\n * Event names are of the format: on_[runnable_type]_(start|stream|end).\n *\n * Runnable types are one of:\n * - llm - used by non chat models\n * - chat_model - used by chat models\n * - prompt -- e.g., ChatPromptTemplate\n * - tool -- LangChain tools\n * - chain - most Runnables are of this type\n *\n * Further, the events are categorized as one of:\n * - start - when the runnable starts\n * - stream - when the runnable is streaming\n * - end - when the runnable ends\n *\n * start, stream and end are associated with slightly different `data` payload.\n *\n * Please see the documentation for `EventData` for more details.\n */\n event: string;\n /** The name of the runnable that generated the event. */\n name: string;\n /**\n * An randomly generated ID to keep track of the execution of the given runnable.\n *\n * Each child runnable that gets invoked as part of the execution of a parent runnable\n * is assigned its own unique ID.\n */\n run_id: string;\n /**\n * Tags associated with the runnable that generated this event.\n * Tags are always inherited from parent runnables.\n */\n tags?: string[];\n /** Metadata associated with the runnable that generated this event. */\n metadata: Record<string, any>;\n /**\n * Event data.\n *\n * The contents of the event data depend on the event type.\n */\n data: StreamEventData;\n};\ntype RunInfo = {\n name: string;\n tags: string[];\n metadata: Record<string, any>;\n runType: string;\n inputs?: Record<string, any>;\n};\nexport interface EventStreamCallbackHandlerInput extends BaseCallbackHandlerInput {\n autoClose?: boolean;\n includeNames?: string[];\n includeTypes?: string[];\n includeTags?: string[];\n excludeNames?: string[];\n excludeTypes?: string[];\n excludeTags?: string[];\n}\nexport declare const isStreamEventsHandler: (handler: BaseCallbackHandler) => handler is EventStreamCallbackHandler;\n/**\n * Class that extends the `BaseTracer` class from the\n * `langchain.callbacks.tracers.base` module. It represents a callback\n * handler that logs the execution of runs and emits `RunLog` instances to a\n * `RunLogStream`.\n */\nexport declare class EventStreamCallbackHandler extends BaseTracer implements CallbackHandlerPrefersStreaming {\n protected autoClose: boolean;\n protected includeNames?: string[];\n protected includeTypes?: string[];\n protected includeTags?: string[];\n protected excludeNames?: string[];\n protected excludeTypes?: string[];\n protected excludeTags?: string[];\n private runInfoMap;\n private tappedPromises;\n protected transformStream: TransformStream;\n writer: WritableStreamDefaultWriter;\n receiveStream: IterableReadableStream<StreamEvent>;\n name: string;\n lc_prefer_streaming: boolean;\n constructor(fields?: EventStreamCallbackHandlerInput);\n [Symbol.asyncIterator](): IterableReadableStream<StreamEvent>;\n protected persistRun(_run: Run): Promise<void>;\n _includeRun(run: RunInfo): boolean;\n tapOutputIterable<T>(runId: string, outputStream: AsyncGenerator<T>): AsyncGenerator<T>;\n send(payload: StreamEvent, run: RunInfo): Promise<void>;\n sendEndEvent(payload: StreamEvent, run: RunInfo): Promise<void>;\n onLLMStart(run: Run): Promise<void>;\n onLLMNewToken(run: Run, token: string, kwargs?: {\n chunk: any;\n }): Promise<void>;\n onLLMEnd(run: Run): Promise<void>;\n onChainStart(run: Run): Promise<void>;\n onChainEnd(run: Run): Promise<void>;\n onToolStart(run: Run): Promise<void>;\n onToolEnd(run: Run): Promise<void>;\n onRetrieverStart(run: Run): Promise<void>;\n onRetrieverEnd(run: Run): Promise<void>;\n handleCustomEvent(eventName: string, data: any, runId: string): Promise<void>;\n finish(): Promise<void>;\n}\nexport {};\n//# sourceMappingURL=event_stream.d.ts.map"],"mappings":";;;;;;AAMA;AA8BA;AAmDiBU,KAjFLJ,eAAAA,GAiFKI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAnDLH,WAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YAoCEC;;;;;;QAMJF;;UASOI,+BAAAA,SAAwCP"}
1
+ {"version":3,"file":"event_stream.d.ts","names":["BaseTracer","Run","BaseCallbackHandler","BaseCallbackHandlerInput","CallbackHandlerPrefersStreaming","IterableReadableStream","StreamEventData","StreamEvent","Record","RunInfo","EventStreamCallbackHandlerInput","isStreamEventsHandler","EventStreamCallbackHandler","T","TransformStream","WritableStreamDefaultWriter","Symbol","asyncIterator","Promise","AsyncGenerator"],"sources":["../../src/tracers/event_stream.d.ts"],"sourcesContent":["import { BaseTracer, type Run } from \"./base.js\";\nimport { BaseCallbackHandler, BaseCallbackHandlerInput, CallbackHandlerPrefersStreaming } from \"../callbacks/base.js\";\nimport { IterableReadableStream } from \"../utils/stream.js\";\n/**\n * Data associated with a StreamEvent.\n */\nexport type StreamEventData = {\n /**\n * The input passed to the runnable that generated the event.\n * Inputs will sometimes be available at the *START* of the runnable, and\n * sometimes at the *END* of the runnable.\n * If a runnable is able to stream its inputs, then its input by definition\n * won't be known until the *END* of the runnable when it has finished streaming\n * its inputs.\n */\n input?: any;\n /**\n * The output of the runnable that generated the event.\n * Outputs will only be available at the *END* of the runnable.\n * For most runnables, this field can be inferred from the `chunk` field,\n * though there might be some exceptions for special cased runnables (e.g., like\n * chat models), which may return more information.\n */\n output?: any;\n /**\n * A streaming chunk from the output that generated the event.\n * chunks support addition in general, and adding them up should result\n * in the output of the runnable that generated the event.\n */\n chunk?: any;\n};\n/**\n * A streaming event.\n *\n * Schema of a streaming event which is produced from the streamEvents method.\n */\nexport type StreamEvent = {\n /**\n * Event names are of the format: on_[runnable_type]_(start|stream|end).\n *\n * Runnable types are one of:\n * - llm - used by non chat models\n * - chat_model - used by chat models\n * - prompt -- e.g., ChatPromptTemplate\n * - tool -- LangChain tools\n * - chain - most Runnables are of this type\n *\n * Further, the events are categorized as one of:\n * - start - when the runnable starts\n * - stream - when the runnable is streaming\n * - end - when the runnable ends\n *\n * start, stream and end are associated with slightly different `data` payload.\n *\n * Please see the documentation for `EventData` for more details.\n */\n event: string;\n /** The name of the runnable that generated the event. */\n name: string;\n /**\n * An randomly generated ID to keep track of the execution of the given runnable.\n *\n * Each child runnable that gets invoked as part of the execution of a parent runnable\n * is assigned its own unique ID.\n */\n run_id: string;\n /**\n * Tags associated with the runnable that generated this event.\n * Tags are always inherited from parent runnables.\n */\n tags?: string[];\n /** Metadata associated with the runnable that generated this event. */\n metadata: Record<string, any>;\n /**\n * Event data.\n *\n * The contents of the event data depend on the event type.\n */\n data: StreamEventData;\n};\ntype RunInfo = {\n name: string;\n tags: string[];\n metadata: Record<string, any>;\n runType: string;\n inputs?: Record<string, any>;\n};\nexport interface EventStreamCallbackHandlerInput extends BaseCallbackHandlerInput {\n autoClose?: boolean;\n includeNames?: string[];\n includeTypes?: string[];\n includeTags?: string[];\n excludeNames?: string[];\n excludeTypes?: string[];\n excludeTags?: string[];\n}\nexport declare const isStreamEventsHandler: (handler: BaseCallbackHandler) => handler is EventStreamCallbackHandler;\n/**\n * Class that extends the `BaseTracer` class from the\n * `langchain.callbacks.tracers.base` module. It represents a callback\n * handler that logs the execution of runs and emits `RunLog` instances to a\n * `RunLogStream`.\n */\nexport declare class EventStreamCallbackHandler extends BaseTracer implements CallbackHandlerPrefersStreaming {\n protected autoClose: boolean;\n protected includeNames?: string[];\n protected includeTypes?: string[];\n protected includeTags?: string[];\n protected excludeNames?: string[];\n protected excludeTypes?: string[];\n protected excludeTags?: string[];\n private runInfoMap;\n private tappedPromises;\n protected transformStream: TransformStream;\n writer: WritableStreamDefaultWriter;\n receiveStream: IterableReadableStream<StreamEvent>;\n private readableStreamClosed;\n name: string;\n lc_prefer_streaming: boolean;\n constructor(fields?: EventStreamCallbackHandlerInput);\n [Symbol.asyncIterator](): IterableReadableStream<StreamEvent>;\n protected persistRun(_run: Run): Promise<void>;\n _includeRun(run: RunInfo): boolean;\n tapOutputIterable<T>(runId: string, outputStream: AsyncGenerator<T>): AsyncGenerator<T>;\n send(payload: StreamEvent, run: RunInfo): Promise<void>;\n sendEndEvent(payload: StreamEvent, run: RunInfo): Promise<void>;\n onLLMStart(run: Run): Promise<void>;\n onLLMNewToken(run: Run, token: string, kwargs?: {\n chunk: any;\n }): Promise<void>;\n onLLMEnd(run: Run): Promise<void>;\n onChainStart(run: Run): Promise<void>;\n onChainEnd(run: Run): Promise<void>;\n onToolStart(run: Run): Promise<void>;\n onToolEnd(run: Run): Promise<void>;\n onRetrieverStart(run: Run): Promise<void>;\n onRetrieverEnd(run: Run): Promise<void>;\n handleCustomEvent(eventName: string, data: any, runId: string): Promise<void>;\n finish(): Promise<void>;\n}\nexport {};\n//# sourceMappingURL=event_stream.d.ts.map"],"mappings":";;;;;;AAMA;AA8BA;AAmDiBU,KAjFLJ,eAAAA,GAiFKI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAnDLH,WAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YAoCEC;;;;;;QAMJF;;UASOI,+BAAAA,SAAwCP"}
@@ -30,6 +30,7 @@ var EventStreamCallbackHandler = class extends BaseTracer {
30
30
  transformStream;
31
31
  writer;
32
32
  receiveStream;
33
+ readableStreamClosed = false;
33
34
  name = "event_stream_tracer";
34
35
  lc_prefer_streaming = true;
35
36
  constructor(fields) {
@@ -44,7 +45,9 @@ var EventStreamCallbackHandler = class extends BaseTracer {
44
45
  this.excludeNames = fields?.excludeNames;
45
46
  this.excludeTypes = fields?.excludeTypes;
46
47
  this.excludeTags = fields?.excludeTags;
47
- this.transformStream = new TransformStream();
48
+ this.transformStream = new TransformStream({ flush: () => {
49
+ this.readableStreamClosed = true;
50
+ } });
48
51
  this.writer = this.transformStream.writable.getWriter();
49
52
  this.receiveStream = IterableReadableStream.fromReadableStream(this.transformStream.readable);
50
53
  }
@@ -112,6 +115,7 @@ var EventStreamCallbackHandler = class extends BaseTracer {
112
115
  }
113
116
  }
114
117
  async send(payload, run) {
118
+ if (this.readableStreamClosed) return;
115
119
  if (this._includeRun(run)) await this.writer.write(payload);
116
120
  }
117
121
  async sendEndEvent(payload, run) {
@@ -1 +1 @@
1
- {"version":3,"file":"event_stream.js","names":["handler: BaseCallbackHandler","fields?: EventStreamCallbackHandlerInput","_run: Run","run: RunInfo","runId: string","outputStream: AsyncGenerator<T>","eventType: string","data: unknown","tappedPromiseResolver: (() => void) | undefined","event: StreamEvent","payload: StreamEvent","run: Run","token: string","kwargs?: { chunk: any }","eventName: string","generations: ChatGeneration[][] | Generation[][] | undefined","output: BaseMessage | Record<string, any> | undefined","runInfo: RunInfo","eventData: StreamEventData","data: StreamEventData","data: any"],"sources":["../../src/tracers/event_stream.ts"],"sourcesContent":["import { BaseTracer, type Run } from \"./base.js\";\nimport {\n BaseCallbackHandler,\n BaseCallbackHandlerInput,\n CallbackHandlerPrefersStreaming,\n} from \"../callbacks/base.js\";\nimport { IterableReadableStream } from \"../utils/stream.js\";\nimport { AIMessageChunk } from \"../messages/ai.js\";\nimport { ChatGeneration, Generation, GenerationChunk } from \"../outputs.js\";\nimport { BaseMessage } from \"../messages/base.js\";\n\n/**\n * Data associated with a StreamEvent.\n */\nexport type StreamEventData = {\n /**\n * The input passed to the runnable that generated the event.\n * Inputs will sometimes be available at the *START* of the runnable, and\n * sometimes at the *END* of the runnable.\n * If a runnable is able to stream its inputs, then its input by definition\n * won't be known until the *END* of the runnable when it has finished streaming\n * its inputs.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input?: any;\n\n /**\n * The output of the runnable that generated the event.\n * Outputs will only be available at the *END* of the runnable.\n * For most runnables, this field can be inferred from the `chunk` field,\n * though there might be some exceptions for special cased runnables (e.g., like\n * chat models), which may return more information.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n output?: any;\n\n /**\n * A streaming chunk from the output that generated the event.\n * chunks support addition in general, and adding them up should result\n * in the output of the runnable that generated the event.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n chunk?: any;\n};\n\n/**\n * A streaming event.\n *\n * Schema of a streaming event which is produced from the streamEvents method.\n */\nexport type StreamEvent = {\n /**\n * Event names are of the format: on_[runnable_type]_(start|stream|end).\n *\n * Runnable types are one of:\n * - llm - used by non chat models\n * - chat_model - used by chat models\n * - prompt -- e.g., ChatPromptTemplate\n * - tool -- LangChain tools\n * - chain - most Runnables are of this type\n *\n * Further, the events are categorized as one of:\n * - start - when the runnable starts\n * - stream - when the runnable is streaming\n * - end - when the runnable ends\n *\n * start, stream and end are associated with slightly different `data` payload.\n *\n * Please see the documentation for `EventData` for more details.\n */\n event: string;\n /** The name of the runnable that generated the event. */\n name: string;\n /**\n * An randomly generated ID to keep track of the execution of the given runnable.\n *\n * Each child runnable that gets invoked as part of the execution of a parent runnable\n * is assigned its own unique ID.\n */\n run_id: string;\n /**\n * Tags associated with the runnable that generated this event.\n * Tags are always inherited from parent runnables.\n */\n tags?: string[];\n /** Metadata associated with the runnable that generated this event. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n metadata: Record<string, any>;\n /**\n * Event data.\n *\n * The contents of the event data depend on the event type.\n */\n data: StreamEventData;\n};\n\ntype RunInfo = {\n name: string;\n tags: string[];\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n metadata: Record<string, any>;\n runType: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n inputs?: Record<string, any>;\n};\n\nexport interface EventStreamCallbackHandlerInput\n extends BaseCallbackHandlerInput {\n autoClose?: boolean;\n includeNames?: string[];\n includeTypes?: string[];\n includeTags?: string[];\n excludeNames?: string[];\n excludeTypes?: string[];\n excludeTags?: string[];\n}\n\nfunction assignName({\n name,\n serialized,\n}: {\n name?: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n serialized?: Record<string, any>;\n}): string {\n if (name !== undefined) {\n return name;\n }\n if (serialized?.name !== undefined) {\n return serialized.name;\n } else if (serialized?.id !== undefined && Array.isArray(serialized?.id)) {\n return serialized.id[serialized.id.length - 1];\n }\n return \"Unnamed\";\n}\n\nexport const isStreamEventsHandler = (\n handler: BaseCallbackHandler\n): handler is EventStreamCallbackHandler =>\n handler.name === \"event_stream_tracer\";\n\n/**\n * Class that extends the `BaseTracer` class from the\n * `langchain.callbacks.tracers.base` module. It represents a callback\n * handler that logs the execution of runs and emits `RunLog` instances to a\n * `RunLogStream`.\n */\nexport class EventStreamCallbackHandler\n extends BaseTracer\n implements CallbackHandlerPrefersStreaming\n{\n protected autoClose = true;\n\n protected includeNames?: string[];\n\n protected includeTypes?: string[];\n\n protected includeTags?: string[];\n\n protected excludeNames?: string[];\n\n protected excludeTypes?: string[];\n\n protected excludeTags?: string[];\n\n private runInfoMap: Map<string, RunInfo> = new Map();\n\n private tappedPromises: Map<string, Promise<void>> = new Map();\n\n protected transformStream: TransformStream;\n\n public writer: WritableStreamDefaultWriter;\n\n public receiveStream: IterableReadableStream<StreamEvent>;\n\n name = \"event_stream_tracer\";\n\n lc_prefer_streaming = true;\n\n constructor(fields?: EventStreamCallbackHandlerInput) {\n super({ _awaitHandler: true, ...fields });\n this.autoClose = fields?.autoClose ?? true;\n this.includeNames = fields?.includeNames;\n this.includeTypes = fields?.includeTypes;\n this.includeTags = fields?.includeTags;\n this.excludeNames = fields?.excludeNames;\n this.excludeTypes = fields?.excludeTypes;\n this.excludeTags = fields?.excludeTags;\n this.transformStream = new TransformStream();\n this.writer = this.transformStream.writable.getWriter();\n this.receiveStream = IterableReadableStream.fromReadableStream(\n this.transformStream.readable\n );\n }\n\n [Symbol.asyncIterator]() {\n return this.receiveStream;\n }\n\n protected async persistRun(_run: Run): Promise<void> {\n // This is a legacy method only called once for an entire run tree\n // and is therefore not useful here\n }\n\n _includeRun(run: RunInfo): boolean {\n const runTags = run.tags ?? [];\n let include =\n this.includeNames === undefined &&\n this.includeTags === undefined &&\n this.includeTypes === undefined;\n if (this.includeNames !== undefined) {\n include = include || this.includeNames.includes(run.name);\n }\n if (this.includeTypes !== undefined) {\n include = include || this.includeTypes.includes(run.runType);\n }\n if (this.includeTags !== undefined) {\n include =\n include ||\n runTags.find((tag) => this.includeTags?.includes(tag)) !== undefined;\n }\n if (this.excludeNames !== undefined) {\n include = include && !this.excludeNames.includes(run.name);\n }\n if (this.excludeTypes !== undefined) {\n include = include && !this.excludeTypes.includes(run.runType);\n }\n if (this.excludeTags !== undefined) {\n include =\n include && runTags.every((tag) => !this.excludeTags?.includes(tag));\n }\n return include;\n }\n\n async *tapOutputIterable<T>(\n runId: string,\n outputStream: AsyncGenerator<T>\n ): AsyncGenerator<T> {\n const firstChunk = await outputStream.next();\n if (firstChunk.done) {\n return;\n }\n const runInfo = this.runInfoMap.get(runId);\n // Run has finished, don't issue any stream events.\n // An example of this is for runnables that use the default\n // implementation of .stream(), which delegates to .invoke()\n // and calls .onChainEnd() before passing it to the iterator.\n if (runInfo === undefined) {\n yield firstChunk.value;\n return;\n }\n // Match format from handlers below\n function _formatOutputChunk(eventType: string, data: unknown) {\n if (eventType === \"llm\" && typeof data === \"string\") {\n return new GenerationChunk({ text: data });\n }\n return data;\n }\n let tappedPromise = this.tappedPromises.get(runId);\n // if we are the first to tap, issue stream events\n if (tappedPromise === undefined) {\n let tappedPromiseResolver: (() => void) | undefined;\n tappedPromise = new Promise((resolve) => {\n tappedPromiseResolver = resolve;\n });\n this.tappedPromises.set(runId, tappedPromise);\n try {\n const event: StreamEvent = {\n event: `on_${runInfo.runType}_stream`,\n run_id: runId,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n data: {},\n };\n await this.send(\n {\n ...event,\n data: {\n chunk: _formatOutputChunk(runInfo.runType, firstChunk.value),\n },\n },\n runInfo\n );\n yield firstChunk.value;\n for await (const chunk of outputStream) {\n // Don't yield tool and retriever stream events\n if (runInfo.runType !== \"tool\" && runInfo.runType !== \"retriever\") {\n await this.send(\n {\n ...event,\n data: {\n chunk: _formatOutputChunk(runInfo.runType, chunk),\n },\n },\n runInfo\n );\n }\n yield chunk;\n }\n } finally {\n tappedPromiseResolver?.();\n // Don't delete from the promises map to keep track of which runs have been tapped.\n }\n } else {\n // otherwise just pass through\n yield firstChunk.value;\n for await (const chunk of outputStream) {\n yield chunk;\n }\n }\n }\n\n async send(payload: StreamEvent, run: RunInfo) {\n if (this._includeRun(run)) {\n await this.writer.write(payload);\n }\n }\n\n async sendEndEvent(payload: StreamEvent, run: RunInfo) {\n const tappedPromise = this.tappedPromises.get(payload.run_id);\n if (tappedPromise !== undefined) {\n // eslint-disable-next-line no-void\n void tappedPromise.then(() => {\n // eslint-disable-next-line no-void\n void this.send(payload, run);\n });\n } else {\n await this.send(payload, run);\n }\n }\n\n async onLLMStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runType = run.inputs.messages !== undefined ? \"chat_model\" : \"llm\";\n const runInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType,\n inputs: run.inputs,\n };\n this.runInfoMap.set(run.id, runInfo);\n const eventName = `on_${runType}_start`;\n await this.send(\n {\n event: eventName,\n data: {\n input: run.inputs,\n },\n name: runName,\n tags: run.tags ?? [],\n run_id: run.id,\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onLLMNewToken(\n run: Run,\n token: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n kwargs?: { chunk: any }\n ): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n let chunk;\n let eventName;\n if (runInfo === undefined) {\n throw new Error(`onLLMNewToken: Run ID ${run.id} not found in run map.`);\n }\n // Top-level streaming events are covered by tapOutputIterable\n if (this.runInfoMap.size === 1) {\n return;\n }\n if (runInfo.runType === \"chat_model\") {\n eventName = \"on_chat_model_stream\";\n if (kwargs?.chunk === undefined) {\n chunk = new AIMessageChunk({ content: token, id: `run-${run.id}` });\n } else {\n chunk = kwargs.chunk.message;\n }\n } else if (runInfo.runType === \"llm\") {\n eventName = \"on_llm_stream\";\n if (kwargs?.chunk === undefined) {\n chunk = new GenerationChunk({ text: token });\n } else {\n chunk = kwargs.chunk;\n }\n } else {\n throw new Error(`Unexpected run type ${runInfo.runType}`);\n }\n await this.send(\n {\n event: eventName,\n data: {\n chunk,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n async onLLMEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n let eventName: string;\n if (runInfo === undefined) {\n throw new Error(`onLLMEnd: Run ID ${run.id} not found in run map.`);\n }\n const generations: ChatGeneration[][] | Generation[][] | undefined =\n run.outputs?.generations;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let output: BaseMessage | Record<string, any> | undefined;\n if (runInfo.runType === \"chat_model\") {\n for (const generation of generations ?? []) {\n if (output !== undefined) {\n break;\n }\n output = (generation[0] as ChatGeneration | undefined)?.message;\n }\n eventName = \"on_chat_model_end\";\n } else if (runInfo.runType === \"llm\") {\n output = {\n generations: generations?.map((generation) => {\n return generation.map((chunk) => {\n return {\n text: chunk.text,\n generationInfo: chunk.generationInfo,\n };\n });\n }),\n llmOutput: run.outputs?.llmOutput ?? {},\n };\n eventName = \"on_llm_end\";\n } else {\n throw new Error(`onLLMEnd: Unexpected run type: ${runInfo.runType}`);\n }\n await this.sendEndEvent(\n {\n event: eventName,\n data: {\n output,\n input: runInfo.inputs,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n async onChainStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runType = run.run_type ?? \"chain\";\n const runInfo: RunInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType: run.run_type,\n };\n let eventData: StreamEventData = {};\n // Workaround Runnable core code not sending input when transform streaming.\n if (run.inputs.input === \"\" && Object.keys(run.inputs).length === 1) {\n eventData = {};\n runInfo.inputs = {};\n } else if (run.inputs.input !== undefined) {\n eventData.input = run.inputs.input;\n runInfo.inputs = run.inputs.input;\n } else {\n eventData.input = run.inputs;\n runInfo.inputs = run.inputs;\n }\n this.runInfoMap.set(run.id, runInfo);\n await this.send(\n {\n event: `on_${runType}_start`,\n data: eventData,\n name: runName,\n tags: run.tags ?? [],\n run_id: run.id,\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onChainEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onChainEnd: Run ID ${run.id} not found in run map.`);\n }\n const eventName = `on_${run.run_type}_end`;\n const inputs = run.inputs ?? runInfo.inputs ?? {};\n const outputs = run.outputs?.output ?? run.outputs;\n const data: StreamEventData = {\n output: outputs,\n input: inputs,\n };\n if (inputs.input && Object.keys(inputs).length === 1) {\n data.input = inputs.input;\n runInfo.inputs = inputs.input;\n }\n await this.sendEndEvent(\n {\n event: eventName,\n data,\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onToolStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType: \"tool\",\n inputs: run.inputs ?? {},\n };\n this.runInfoMap.set(run.id, runInfo);\n await this.send(\n {\n event: \"on_tool_start\",\n data: {\n input: run.inputs ?? {},\n },\n name: runName,\n run_id: run.id,\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onToolEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onToolEnd: Run ID ${run.id} not found in run map.`);\n }\n if (runInfo.inputs === undefined) {\n throw new Error(\n `onToolEnd: Run ID ${run.id} is a tool call, and is expected to have traced inputs.`\n );\n }\n const output =\n run.outputs?.output === undefined ? run.outputs : run.outputs.output;\n await this.sendEndEvent(\n {\n event: \"on_tool_end\",\n data: {\n output,\n input: runInfo.inputs,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n async onRetrieverStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runType = \"retriever\";\n const runInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType,\n inputs: {\n query: run.inputs.query,\n },\n };\n this.runInfoMap.set(run.id, runInfo);\n await this.send(\n {\n event: \"on_retriever_start\",\n data: {\n input: {\n query: run.inputs.query,\n },\n },\n name: runName,\n tags: run.tags ?? [],\n run_id: run.id,\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onRetrieverEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onRetrieverEnd: Run ID ${run.id} not found in run map.`);\n }\n await this.sendEndEvent(\n {\n event: \"on_retriever_end\",\n data: {\n output: run.outputs?.documents ?? run.outputs,\n input: runInfo.inputs,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async handleCustomEvent(eventName: string, data: any, runId: string) {\n const runInfo = this.runInfoMap.get(runId);\n if (runInfo === undefined) {\n throw new Error(\n `handleCustomEvent: Run ID ${runId} not found in run map.`\n );\n }\n await this.send(\n {\n event: \"on_custom_event\",\n run_id: runId,\n name: eventName,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n data,\n },\n runInfo\n );\n }\n\n async finish() {\n const pendingPromises = [...this.tappedPromises.values()];\n // eslint-disable-next-line no-void\n void Promise.all(pendingPromises).finally(() => {\n // eslint-disable-next-line no-void\n void this.writer.close();\n });\n }\n}\n"],"mappings":";;;;;;AAqHA,SAAS,WAAW,EAClB,MACA,YAKD,EAAU;AACT,KAAI,SAAS,OACX,QAAO;AAET,KAAI,YAAY,SAAS,OACvB,QAAO,WAAW;UACT,YAAY,OAAO,UAAa,MAAM,QAAQ,YAAY,GAAG,CACtE,QAAO,WAAW,GAAG,WAAW,GAAG,SAAS;AAE9C,QAAO;AACR;AAED,MAAa,wBAAwB,CACnCA,YAEA,QAAQ,SAAS;;;;;;;AAQnB,IAAa,6BAAb,cACU,WAEV;CACE,AAAU,YAAY;CAEtB,AAAU;CAEV,AAAU;CAEV,AAAU;CAEV,AAAU;CAEV,AAAU;CAEV,AAAU;CAEV,AAAQ,6BA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fields?: EventStreamCallbackHandlerInput","_run: Run","run: RunInfo","runId: string","outputStream: AsyncGenerator<T>","eventType: string","data: unknown","tappedPromiseResolver: (() => void) | undefined","event: StreamEvent","payload: StreamEvent","run: Run","token: string","kwargs?: { chunk: any }","eventName: string","generations: ChatGeneration[][] | Generation[][] | undefined","output: BaseMessage | Record<string, any> | undefined","runInfo: RunInfo","eventData: StreamEventData","data: StreamEventData","data: any"],"sources":["../../src/tracers/event_stream.ts"],"sourcesContent":["import { BaseTracer, type Run } from \"./base.js\";\nimport {\n BaseCallbackHandler,\n BaseCallbackHandlerInput,\n CallbackHandlerPrefersStreaming,\n} from \"../callbacks/base.js\";\nimport { IterableReadableStream } from \"../utils/stream.js\";\nimport { AIMessageChunk } from \"../messages/ai.js\";\nimport { ChatGeneration, Generation, GenerationChunk } from \"../outputs.js\";\nimport { BaseMessage } from \"../messages/base.js\";\n\n/**\n * Data associated with a StreamEvent.\n */\nexport type StreamEventData = {\n /**\n * The input passed to the runnable that generated the event.\n * Inputs will sometimes be available at the *START* of the runnable, and\n * sometimes at the *END* of the runnable.\n * If a runnable is able to stream its inputs, then its input by definition\n * won't be known until the *END* of the runnable when it has finished streaming\n * its inputs.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input?: any;\n\n /**\n * The output of the runnable that generated the event.\n * Outputs will only be available at the *END* of the runnable.\n * For most runnables, this field can be inferred from the `chunk` field,\n * though there might be some exceptions for special cased runnables (e.g., like\n * chat models), which may return more information.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n output?: any;\n\n /**\n * A streaming chunk from the output that generated the event.\n * chunks support addition in general, and adding them up should result\n * in the output of the runnable that generated the event.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n chunk?: any;\n};\n\n/**\n * A streaming event.\n *\n * Schema of a streaming event which is produced from the streamEvents method.\n */\nexport type StreamEvent = {\n /**\n * Event names are of the format: on_[runnable_type]_(start|stream|end).\n *\n * Runnable types are one of:\n * - llm - used by non chat models\n * - chat_model - used by chat models\n * - prompt -- e.g., ChatPromptTemplate\n * - tool -- LangChain tools\n * - chain - most Runnables are of this type\n *\n * Further, the events are categorized as one of:\n * - start - when the runnable starts\n * - stream - when the runnable is streaming\n * - end - when the runnable ends\n *\n * start, stream and end are associated with slightly different `data` payload.\n *\n * Please see the documentation for `EventData` for more details.\n */\n event: string;\n /** The name of the runnable that generated the event. */\n name: string;\n /**\n * An randomly generated ID to keep track of the execution of the given runnable.\n *\n * Each child runnable that gets invoked as part of the execution of a parent runnable\n * is assigned its own unique ID.\n */\n run_id: string;\n /**\n * Tags associated with the runnable that generated this event.\n * Tags are always inherited from parent runnables.\n */\n tags?: string[];\n /** Metadata associated with the runnable that generated this event. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n metadata: Record<string, any>;\n /**\n * Event data.\n *\n * The contents of the event data depend on the event type.\n */\n data: StreamEventData;\n};\n\ntype RunInfo = {\n name: string;\n tags: string[];\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n metadata: Record<string, any>;\n runType: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n inputs?: Record<string, any>;\n};\n\nexport interface EventStreamCallbackHandlerInput\n extends BaseCallbackHandlerInput {\n autoClose?: boolean;\n includeNames?: string[];\n includeTypes?: string[];\n includeTags?: string[];\n excludeNames?: string[];\n excludeTypes?: string[];\n excludeTags?: string[];\n}\n\nfunction assignName({\n name,\n serialized,\n}: {\n name?: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n serialized?: Record<string, any>;\n}): string {\n if (name !== undefined) {\n return name;\n }\n if (serialized?.name !== undefined) {\n return serialized.name;\n } else if (serialized?.id !== undefined && Array.isArray(serialized?.id)) {\n return serialized.id[serialized.id.length - 1];\n }\n return \"Unnamed\";\n}\n\nexport const isStreamEventsHandler = (\n handler: BaseCallbackHandler\n): handler is EventStreamCallbackHandler =>\n handler.name === \"event_stream_tracer\";\n\n/**\n * Class that extends the `BaseTracer` class from the\n * `langchain.callbacks.tracers.base` module. It represents a callback\n * handler that logs the execution of runs and emits `RunLog` instances to a\n * `RunLogStream`.\n */\nexport class EventStreamCallbackHandler\n extends BaseTracer\n implements CallbackHandlerPrefersStreaming\n{\n protected autoClose = true;\n\n protected includeNames?: string[];\n\n protected includeTypes?: string[];\n\n protected includeTags?: string[];\n\n protected excludeNames?: string[];\n\n protected excludeTypes?: string[];\n\n protected excludeTags?: string[];\n\n private runInfoMap: Map<string, RunInfo> = new Map();\n\n private tappedPromises: Map<string, Promise<void>> = new Map();\n\n protected transformStream: TransformStream;\n\n public writer: WritableStreamDefaultWriter;\n\n public receiveStream: IterableReadableStream<StreamEvent>;\n\n private readableStreamClosed = false;\n\n name = \"event_stream_tracer\";\n\n lc_prefer_streaming = true;\n\n constructor(fields?: EventStreamCallbackHandlerInput) {\n super({ _awaitHandler: true, ...fields });\n this.autoClose = fields?.autoClose ?? true;\n this.includeNames = fields?.includeNames;\n this.includeTypes = fields?.includeTypes;\n this.includeTags = fields?.includeTags;\n this.excludeNames = fields?.excludeNames;\n this.excludeTypes = fields?.excludeTypes;\n this.excludeTags = fields?.excludeTags;\n this.transformStream = new TransformStream({\n flush: () => {\n this.readableStreamClosed = true;\n },\n });\n this.writer = this.transformStream.writable.getWriter();\n this.receiveStream = IterableReadableStream.fromReadableStream(\n this.transformStream.readable\n );\n }\n\n [Symbol.asyncIterator]() {\n return this.receiveStream;\n }\n\n protected async persistRun(_run: Run): Promise<void> {\n // This is a legacy method only called once for an entire run tree\n // and is therefore not useful here\n }\n\n _includeRun(run: RunInfo): boolean {\n const runTags = run.tags ?? [];\n let include =\n this.includeNames === undefined &&\n this.includeTags === undefined &&\n this.includeTypes === undefined;\n if (this.includeNames !== undefined) {\n include = include || this.includeNames.includes(run.name);\n }\n if (this.includeTypes !== undefined) {\n include = include || this.includeTypes.includes(run.runType);\n }\n if (this.includeTags !== undefined) {\n include =\n include ||\n runTags.find((tag) => this.includeTags?.includes(tag)) !== undefined;\n }\n if (this.excludeNames !== undefined) {\n include = include && !this.excludeNames.includes(run.name);\n }\n if (this.excludeTypes !== undefined) {\n include = include && !this.excludeTypes.includes(run.runType);\n }\n if (this.excludeTags !== undefined) {\n include =\n include && runTags.every((tag) => !this.excludeTags?.includes(tag));\n }\n return include;\n }\n\n async *tapOutputIterable<T>(\n runId: string,\n outputStream: AsyncGenerator<T>\n ): AsyncGenerator<T> {\n const firstChunk = await outputStream.next();\n if (firstChunk.done) {\n return;\n }\n const runInfo = this.runInfoMap.get(runId);\n // Run has finished, don't issue any stream events.\n // An example of this is for runnables that use the default\n // implementation of .stream(), which delegates to .invoke()\n // and calls .onChainEnd() before passing it to the iterator.\n if (runInfo === undefined) {\n yield firstChunk.value;\n return;\n }\n // Match format from handlers below\n function _formatOutputChunk(eventType: string, data: unknown) {\n if (eventType === \"llm\" && typeof data === \"string\") {\n return new GenerationChunk({ text: data });\n }\n return data;\n }\n let tappedPromise = this.tappedPromises.get(runId);\n // if we are the first to tap, issue stream events\n if (tappedPromise === undefined) {\n let tappedPromiseResolver: (() => void) | undefined;\n tappedPromise = new Promise((resolve) => {\n tappedPromiseResolver = resolve;\n });\n this.tappedPromises.set(runId, tappedPromise);\n try {\n const event: StreamEvent = {\n event: `on_${runInfo.runType}_stream`,\n run_id: runId,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n data: {},\n };\n await this.send(\n {\n ...event,\n data: {\n chunk: _formatOutputChunk(runInfo.runType, firstChunk.value),\n },\n },\n runInfo\n );\n yield firstChunk.value;\n for await (const chunk of outputStream) {\n // Don't yield tool and retriever stream events\n if (runInfo.runType !== \"tool\" && runInfo.runType !== \"retriever\") {\n await this.send(\n {\n ...event,\n data: {\n chunk: _formatOutputChunk(runInfo.runType, chunk),\n },\n },\n runInfo\n );\n }\n yield chunk;\n }\n } finally {\n tappedPromiseResolver?.();\n // Don't delete from the promises map to keep track of which runs have been tapped.\n }\n } else {\n // otherwise just pass through\n yield firstChunk.value;\n for await (const chunk of outputStream) {\n yield chunk;\n }\n }\n }\n\n async send(payload: StreamEvent, run: RunInfo) {\n if (this.readableStreamClosed) return;\n if (this._includeRun(run)) {\n await this.writer.write(payload);\n }\n }\n\n async sendEndEvent(payload: StreamEvent, run: RunInfo) {\n const tappedPromise = this.tappedPromises.get(payload.run_id);\n if (tappedPromise !== undefined) {\n // eslint-disable-next-line no-void\n void tappedPromise.then(() => {\n // eslint-disable-next-line no-void\n void this.send(payload, run);\n });\n } else {\n await this.send(payload, run);\n }\n }\n\n async onLLMStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runType = run.inputs.messages !== undefined ? \"chat_model\" : \"llm\";\n const runInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType,\n inputs: run.inputs,\n };\n this.runInfoMap.set(run.id, runInfo);\n const eventName = `on_${runType}_start`;\n await this.send(\n {\n event: eventName,\n data: {\n input: run.inputs,\n },\n name: runName,\n tags: run.tags ?? [],\n run_id: run.id,\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onLLMNewToken(\n run: Run,\n token: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n kwargs?: { chunk: any }\n ): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n let chunk;\n let eventName;\n if (runInfo === undefined) {\n throw new Error(`onLLMNewToken: Run ID ${run.id} not found in run map.`);\n }\n // Top-level streaming events are covered by tapOutputIterable\n if (this.runInfoMap.size === 1) {\n return;\n }\n if (runInfo.runType === \"chat_model\") {\n eventName = \"on_chat_model_stream\";\n if (kwargs?.chunk === undefined) {\n chunk = new AIMessageChunk({ content: token, id: `run-${run.id}` });\n } else {\n chunk = kwargs.chunk.message;\n }\n } else if (runInfo.runType === \"llm\") {\n eventName = \"on_llm_stream\";\n if (kwargs?.chunk === undefined) {\n chunk = new GenerationChunk({ text: token });\n } else {\n chunk = kwargs.chunk;\n }\n } else {\n throw new Error(`Unexpected run type ${runInfo.runType}`);\n }\n await this.send(\n {\n event: eventName,\n data: {\n chunk,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n async onLLMEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n let eventName: string;\n if (runInfo === undefined) {\n throw new Error(`onLLMEnd: Run ID ${run.id} not found in run map.`);\n }\n const generations: ChatGeneration[][] | Generation[][] | undefined =\n run.outputs?.generations;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let output: BaseMessage | Record<string, any> | undefined;\n if (runInfo.runType === \"chat_model\") {\n for (const generation of generations ?? []) {\n if (output !== undefined) {\n break;\n }\n output = (generation[0] as ChatGeneration | undefined)?.message;\n }\n eventName = \"on_chat_model_end\";\n } else if (runInfo.runType === \"llm\") {\n output = {\n generations: generations?.map((generation) => {\n return generation.map((chunk) => {\n return {\n text: chunk.text,\n generationInfo: chunk.generationInfo,\n };\n });\n }),\n llmOutput: run.outputs?.llmOutput ?? {},\n };\n eventName = \"on_llm_end\";\n } else {\n throw new Error(`onLLMEnd: Unexpected run type: ${runInfo.runType}`);\n }\n await this.sendEndEvent(\n {\n event: eventName,\n data: {\n output,\n input: runInfo.inputs,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n async onChainStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runType = run.run_type ?? \"chain\";\n const runInfo: RunInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType: run.run_type,\n };\n let eventData: StreamEventData = {};\n // Workaround Runnable core code not sending input when transform streaming.\n if (run.inputs.input === \"\" && Object.keys(run.inputs).length === 1) {\n eventData = {};\n runInfo.inputs = {};\n } else if (run.inputs.input !== undefined) {\n eventData.input = run.inputs.input;\n runInfo.inputs = run.inputs.input;\n } else {\n eventData.input = run.inputs;\n runInfo.inputs = run.inputs;\n }\n this.runInfoMap.set(run.id, runInfo);\n await this.send(\n {\n event: `on_${runType}_start`,\n data: eventData,\n name: runName,\n tags: run.tags ?? [],\n run_id: run.id,\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onChainEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onChainEnd: Run ID ${run.id} not found in run map.`);\n }\n const eventName = `on_${run.run_type}_end`;\n const inputs = run.inputs ?? runInfo.inputs ?? {};\n const outputs = run.outputs?.output ?? run.outputs;\n const data: StreamEventData = {\n output: outputs,\n input: inputs,\n };\n if (inputs.input && Object.keys(inputs).length === 1) {\n data.input = inputs.input;\n runInfo.inputs = inputs.input;\n }\n await this.sendEndEvent(\n {\n event: eventName,\n data,\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onToolStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType: \"tool\",\n inputs: run.inputs ?? {},\n };\n this.runInfoMap.set(run.id, runInfo);\n await this.send(\n {\n event: \"on_tool_start\",\n data: {\n input: run.inputs ?? {},\n },\n name: runName,\n run_id: run.id,\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onToolEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onToolEnd: Run ID ${run.id} not found in run map.`);\n }\n if (runInfo.inputs === undefined) {\n throw new Error(\n `onToolEnd: Run ID ${run.id} is a tool call, and is expected to have traced inputs.`\n );\n }\n const output =\n run.outputs?.output === undefined ? run.outputs : run.outputs.output;\n await this.sendEndEvent(\n {\n event: \"on_tool_end\",\n data: {\n output,\n input: runInfo.inputs,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n async onRetrieverStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runType = \"retriever\";\n const runInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType,\n inputs: {\n query: run.inputs.query,\n },\n };\n this.runInfoMap.set(run.id, runInfo);\n await this.send(\n {\n event: \"on_retriever_start\",\n data: {\n input: {\n query: run.inputs.query,\n },\n },\n name: runName,\n tags: run.tags ?? [],\n run_id: run.id,\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onRetrieverEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onRetrieverEnd: Run ID ${run.id} not found in run map.`);\n }\n await this.sendEndEvent(\n {\n event: \"on_retriever_end\",\n data: {\n output: run.outputs?.documents ?? run.outputs,\n input: runInfo.inputs,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async handleCustomEvent(eventName: string, data: any, runId: string) {\n const runInfo = this.runInfoMap.get(runId);\n if (runInfo === undefined) {\n throw new Error(\n `handleCustomEvent: Run ID ${runId} not found in run map.`\n );\n }\n await this.send(\n {\n event: \"on_custom_event\",\n run_id: runId,\n name: eventName,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n data,\n },\n runInfo\n );\n }\n\n async finish() {\n const pendingPromises = [...this.tappedPromises.values()];\n // eslint-disable-next-line no-void\n void Promise.all(pendingPromises).finally(() => {\n // eslint-disable-next-line no-void\n void this.writer.close();\n });\n }\n}\n"],"mappings":";;;;;;AAqHA,SAAS,WAAW,EAClB,MACA,YAKD,EAAU;AACT,KAAI,SAAS,OACX,QAAO;AAET,KAAI,YAAY,SAAS,OACv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M;AAC1C,MAAI,YAAY,OACd,OAAM,IAAI,MACR,CAAC,0BAA0B,EAAE,MAAM,sBAAsB,CAAC;EAG9D,MAAM,KAAK,KACT;GACE,OAAO;GACP,QAAQ;GACR,MAAM;GACN,MAAM,QAAQ;GACd,UAAU,QAAQ;GAClB;EACD,GACD,QACD;CACF;CAED,MAAM,SAAS;EACb,MAAM,kBAAkB,CAAC,GAAG,KAAK,eAAe,QAAQ,AAAC;EAEpD,QAAQ,IAAI,gBAAgB,CAAC,QAAQ,MAAM;GAEzC,KAAK,OAAO,OAAO;EACzB,EAAC;CACH;AACF"}
@@ -16,12 +16,21 @@ require_rolldown_runtime.__export(core_exports, {
16
16
  });
17
17
  const JsonPatchError = require_helpers.PatchError;
18
18
  const deepClone = require_helpers._deepClone;
19
+ /**
20
+ * Check if a key is a dangerous prototype property that could lead to prototype pollution.
21
+ * This provides defense-in-depth alongside the check in applyOperation.
22
+ */
23
+ function isDangerousKey(key) {
24
+ return Object.getOwnPropertyNames(Object.prototype).includes(key);
25
+ }
19
26
  const objOps = {
20
27
  add: function(obj, key, document) {
28
+ if (isDangerousKey(key)) throw new TypeError("JSON-Patch: modifying `__proto__`, `constructor`, or `prototype` prop is banned for security reasons");
21
29
  obj[key] = this.value;
22
30
  return { newDocument: document };
23
31
  },
24
32
  remove: function(obj, key, document) {
33
+ if (isDangerousKey(key)) throw new TypeError("JSON-Patch: modifying `__proto__`, `constructor`, or `prototype` prop is banned for security reasons");
25
34
  var removed = obj[key];
26
35
  delete obj[key];
27
36
  return {
@@ -30,6 +39,7 @@ const objOps = {
30
39
  };
31
40
  },
32
41
  replace: function(obj, key, document) {
42
+ if (isDangerousKey(key)) throw new TypeError("JSON-Patch: modifying `__proto__`, `constructor`, or `prototype` prop is banned for security reasons");
33
43
  var removed = obj[key];
34
44
  obj[key] = this.value;
35
45
  return {
@@ -1 +1 @@
1
- {"version":3,"file":"core.cjs","names":["PatchError","_deepClone","isInteger","document: any","pointer: string","document: T","operation: Operation","validateOperation: boolean | Validator<T>","mutateDocument: boolean","banPrototypeModifications: boolean","index: number","returnValue: OperationResult<T>","key: string | number","unescapePathComponent","patch: ReadonlyArray<Operation>","validateOperation?: boolean | Validator<T>","operationResult: OperationResult<T>","document?: any","existingPathFragment?: string","hasUndefined","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,iBAAiBA;AAC9B,MAAa,YAAYC;AA2EzB,MAAM,SAAS;CACb,KAAK,SAAU,KAAK,KAAK,UAAU;EACjC,IAAI,OAAO,KAAK;AAChB,SAAO,EAAE,aAAa,SAAU;CACjC;CACD,QAAQ,SAAU,KAAK,KAAK,UAAU;EACpC,IAAI,UAAU,IAAI;EAClB,OAAO,IAAI;AACX,SAAO;GAAE,aAAa;GAAU;EAAS;CAC1C;CACD,SAAS,SAAU,KAAK,KAAK,UAAU;EACrC,IAAI,UAAU,IAAI;EAClB,IAAI,OAAO,KAAK;AAChB,SAAO;GAAE,aAAa;GAAU;EAAS;CAC1C;CACD,MAAM,SAAU,KAAK,KAAK,UAAU;EAIlC,IAAI,UAAU,kBAAkB,UAAU,KAAK,KAAK;AAEpD,MAAI,SACF,UAAUA,2BAAW,QAAQ;EAG/B,MAAM,gBAAgB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AwBD,SAAgB,WAAWuB,GAAQC,GAAiB;AAClD,KAAI,MAAM,EAAG,QAAO;AAEpB,KAAI,KAAK,KAAK,OAAO,KAAK,YAAY,OAAO,KAAK,UAAU;EAC1D,IAAI,OAAO,MAAM,QAAQ,EAAE,EACzB,OAAO,MAAM,QAAQ,EAAE,EACvB,GACA,QACA;AAEF,MAAI,QAAQ,MAAM;GAChB,SAAS,EAAE;AACX,OAAI,UAAU,EAAE,OAAQ,QAAO;AAC/B,QAAK,IAAI,QAAQ,QAAQ,GAAK,KAAI,CAAC,WAAW,EAAE,IAAI,EAAE,GAAG,CAAE,QAAO;AAClE,UAAO;EACR;AAED,MAAI,QAAQ,KAAM,QAAO;EAEzB,IAAI,OAAO,OAAO,KAAK,EAAE;EACzB,SAAS,KAAK;AAEd,MAAI,WAAW,OAAO,KAAK,EAAE,CAAC,OAAQ,QAAO;AAE7C,OAAK,IAAI,QAAQ,QAAQ,GAAK,KAAI,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"}
1
+ {"version":3,"file":"core.cjs","names":["PatchError","_deepClone","key: string | number","isInteger","document: any","pointer: string","document: T","operation: Operation","validateOperation: boolean | Validator<T>","mutateDocument: boolean","banPrototypeModifications: boolean","index: number","returnValue: OperationResult<T>","unescapePathComponent","patch: ReadonlyArray<Operation>","validateOperation?: boolean | Validator<T>","operationResult: OperationResult<T>","document?: any","existingPathFragment?: string","hasUndefined","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,iBAAiBA;AAC9B,MAAa,YAAYC;;;;;AA8EzB,SAAS,eAAeC,KAA+B;AACrD,QAAO,OAAO,oBAAoB,OAAO,UAAU,CAAC,SAAS,IAAI;AAClE;AAGD,MAAM,SAAS;CACb,KAAK,SAAU,KAAK,KAAK,UAAU;AACjC,MAAI,eAAe,IAAI,CACrB,OAAM,IAAI,UACR;EAGJ,IAAI,OAAO,KAAK;AAChB,SAAO,EAAE,aAAa,SAAU;CACjC;CACD,QAAQ,SAAU,KAAK,KAAK,UAAU;AACpC,MAAI,eAAe,IAAI,CACrB,OAAM,IAAI,UACR;EAGJ,IAAI,UAAU,IAAI;EAClB,OAAO,IAAI;AACX,SAAO;GAAE,aAAa;GAAU;EAAS;CAC1C;CACD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SAAS,CAC1B,OAAM,IAAI,eACR,mCACA;AAGJ,MAAI,UAEF,WACEtB,2BAAW,SAAS,EACpBA,2BAAW,SAAS,EACpB,qBAAqB,KACtB;OACI;GACL,oBAAoB,qBAAqB;AACzC,QAAK,IAAI,IAAI,GAAG,IAAI,SAAS,QAAQ,KACnC,kBAAkB,SAAS,IAAI,GAAG,UAAU,OAAU;EAEzD;CACF,SAAQ,GAAG;AACV,MAAI,aAAa,eACf,QAAO;MAEP,OAAM;CAET;AACF;AAwBD,SAAgB,WAAWuB,GAAQC,GAAiB;AAClD,KAAI,MAAM,EAAG,QAAO;AAEpB,KAAI,KAAK,KAAK,OAAO,KAAK,YAAY,OAAO,KAAK,UAAU;EAC1D,IAAI,OAAO,MAAM,QAAQ,EAAE,EACzB,OAAO,MAAM,QAAQ,EAAE,EACvB,GACA,QACA;AAEF,MAAI,QAAQ,MAAM;GAChB,SAAS,EAAE;AACX,OAAI,UAAU,EAAE,OAAQ,QAAO;AAC/B,QAAK,IAAI,QAAQ,QAAQ,GAAK,KAAI,CAAC,WAAW,EAAE,IAAI,EAAE,GAAG,CAAE,QAAO;AAClE,UAAO;EACR;AAED,MAAI,QAAQ,KAAM,QAAO;EAEzB,IAAI,OAAO,OAAO,KAAK,EAAE;EACzB,SAAS,KAAK;AAEd,MAAI,WAAW,OAAO,KAAK,EAAE,CAAC,OAAQ,QAAO;AAE7C,OAAK,IAAI,QAAQ,QAAQ,GAAK,KAAI,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,12 +16,21 @@ __export(core_exports, {
16
16
  });
17
17
  const JsonPatchError = PatchError;
18
18
  const deepClone = _deepClone;
19
+ /**
20
+ * Check if a key is a dangerous prototype property that could lead to prototype pollution.
21
+ * This provides defense-in-depth alongside the check in applyOperation.
22
+ */
23
+ function isDangerousKey(key) {
24
+ return Object.getOwnPropertyNames(Object.prototype).includes(key);
25
+ }
19
26
  const objOps = {
20
27
  add: function(obj, key, document) {
28
+ if (isDangerousKey(key)) throw new TypeError("JSON-Patch: modifying `__proto__`, `constructor`, or `prototype` prop is banned for security reasons");
21
29
  obj[key] = this.value;
22
30
  return { newDocument: document };
23
31
  },
24
32
  remove: function(obj, key, document) {
33
+ if (isDangerousKey(key)) throw new TypeError("JSON-Patch: modifying `__proto__`, `constructor`, or `prototype` prop is banned for security reasons");
25
34
  var removed = obj[key];
26
35
  delete obj[key];
27
36
  return {
@@ -30,6 +39,7 @@ const objOps = {
30
39
  };
31
40
  },
32
41
  replace: function(obj, key, document) {
42
+ if (isDangerousKey(key)) throw new TypeError("JSON-Patch: modifying `__proto__`, `constructor`, or `prototype` prop is banned for security reasons");
33
43
  var removed = obj[key];
34
44
  obj[key] = this.value;
35
45
  return {
@@ -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;AAChB,SAAO,EAAE,aAAa,SAAU;CACjC;CACD,QAAQ,SAAU,KAAK,KAAK,UAAU;EACpC,IAAI,UAAU,IAAI;EAClB,OAAO,IAAI;AACX,SAAO;GAAE,aAAa;GAAU;EAAS;CAC1C;CACD,SAAS,SAAU,KAAK,KAAK,UAAU;EACrC,IAAI,UAAU,IAAI;EAClB,IAAI,OAAO,KAAK;AAChB,SAAO;GAAE,aAAa;GAAU;EAAS;CAC1C;CACD,MAAM,SAAU,KAAK,KAAK,UAAU;EAIlC,IAAI,UAAU,kBAAkB,UAAU,KAAK,KAAK;AAEpD,MAAI,SACF,UAAU,WAAW,QAAQ;EAG/B,MAAM,gBAAgB,eAAe,UAAU;GAC7C,IAAI;GACJ,MAAM,KAAK;EACZ,EAAC,CAAC;EAEH,eAAe,UAAU;GACvB,IAAI;GACJ,MAAM,KAAK;GACX,OAAO;EACR,EAAC;AAEF,SAAO;GAAE,aAAa;GAAU;EAAS;CAC1C;CACD,MAAM,SAAU,KAAK,KAAK,UAAU;EAClC,MAAM,cAAc,kBAAkB,UAAU,KAAK,KAAK;EAE1D,eAAe,UAAU;GACvB,IAAI;GACJ,MAAM,KAAK;GACX,OAAO,WAAW,YAAY;EAC/B,EAAC;AACF,SAAO,EAAE,aAAa,SAAU;CACjC;CACD,MAAM,SAAU,KAAK,KAAK,UAAU;AAClC,SAAO;GAAE,aAAa;GAAU,MAAM,WAAW,IAAI,MAAM,KAAK,MAAM;EAAE;CACzE;CACD,MAAM,SAAU,KAAK,KAAK,UAAU;EAClC,KAAK,QAAQ,IAAI;AACjB,SAA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AK,KAAI,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"}
1
+ {"version":3,"file":"core.js","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,UAAU,CAAC,SAAS,IAAI;AAClE;AAGD,MAAM,SAAS;CACb,KAAK,SAAU,KAAK,KAAK,UAAU;AACjC,MAAI,eAAe,IAAI,CACrB,OAAM,IAAI,UACR;EAGJ,IAAI,OAAO,KAAK;AAChB,SAAO,EAAE,aAAa,SAAU;CACjC;CACD,QAAQ,SAAU,KAAK,KAAK,UAAU;AACpC,MAAI,eAAe,IAAI,CACrB,OAAM,IAAI,UACR;EAGJ,IAAI,UAAU,IAAI;EAClB,OAAO,IAAI;AACX,SAAO;GAAE,aAAa;GAAU;EAAS;CAC1C;CACD,SAAS,SAAU,KAAK,KAAK,UAAU;AACrC,MAAI,eAAe,IAAI,CACrB,OAAM,IAAI,UACR;EAGJ,IAAI,UAAU,IAAI;EAClB,IAAI,OAAO,KAAK;AAChB,SAAO;GAAE,aAAa;GAAU;EAAS;CAC1C;CACD,MAAM,SAAU,KAAK,KAAK,UAAU;EAIlC,IAAI,UAAU,kBAAkB,UAAU,KAAK,KAAK;AAEpD,MAAI,SACF,UAAU,WAAW,QAAQ;EAG/B,MAAM,gBAAgB,eAAe,UAAU;GAC7C,IAAI;GACJ,MAAM,KAAK;EACZ,EAAC,CAAC;EAEH,eAAe,UAAU;GACvB,IAAI;GACJ,MAAM,KAAK;GACX,OAAO;EACR,EAAC;AAEF,SAAO;GAAE,aAAa;GAAU;EAAS;CAC1C;CACD,MAAM,SAAU,KAAK,KAAK,UAAU;EAClC,MAAM,cAAc,kBAAkB,UAAU,KAAK,KAAK;EAE1D,eAAe,UAAU;GACvB,IAAI;GACJ,MAAM,KAAK;GACX,OAAO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,CAAC,WAAW,EAAE,IAAI,EAAE,GAAG,CAAE,QAAO;AAClE,UAAO;EACR;AAED,MAAI,QAAQ,KAAM,QAAO;EAEzB,IAAI,OAAO,OAAO,KAAK,EAAE;EACzB,SAAS,KAAK;AAEd,MAAI,WAAW,OAAO,KAAK,EAAE,CAAC,OAAQ,QAAO;AAE7C,OAAK,IAAI,QAAQ,QAAQ,GAAK,KAAI,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;