@langchain/core 1.1.19 → 1.1.21

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 (81) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/agents.d.cts.map +1 -1
  3. package/dist/callbacks/base.cjs.map +1 -1
  4. package/dist/callbacks/base.js.map +1 -1
  5. package/dist/documents/document.cjs.map +1 -1
  6. package/dist/documents/document.js.map +1 -1
  7. package/dist/embeddings.cjs.map +1 -1
  8. package/dist/embeddings.js.map +1 -1
  9. package/dist/language_models/base.cjs.map +1 -1
  10. package/dist/language_models/base.js.map +1 -1
  11. package/dist/load/import_map.cjs +2 -0
  12. package/dist/load/import_map.cjs.map +1 -1
  13. package/dist/load/import_map.js +2 -0
  14. package/dist/load/import_map.js.map +1 -1
  15. package/dist/load/serializable.cjs.map +1 -1
  16. package/dist/load/serializable.js.map +1 -1
  17. package/dist/memory.d.cts.map +1 -1
  18. package/dist/messages/ai.cjs.map +1 -1
  19. package/dist/messages/ai.js.map +1 -1
  20. package/dist/messages/base.cjs.map +1 -1
  21. package/dist/messages/base.js.map +1 -1
  22. package/dist/messages/content/tools.cjs.map +1 -1
  23. package/dist/messages/content/tools.js.map +1 -1
  24. package/dist/messages/function.cjs.map +1 -1
  25. package/dist/messages/function.js.map +1 -1
  26. package/dist/messages/message.cjs.map +1 -1
  27. package/dist/messages/message.js.map +1 -1
  28. package/dist/output_parsers/structured.cjs.map +1 -1
  29. package/dist/output_parsers/structured.js.map +1 -1
  30. package/dist/output_parsers/xml.cjs.map +1 -1
  31. package/dist/output_parsers/xml.js.map +1 -1
  32. package/dist/prompts/base.cjs.map +1 -1
  33. package/dist/prompts/base.js.map +1 -1
  34. package/dist/prompts/chat.cjs.map +1 -1
  35. package/dist/prompts/chat.js.map +1 -1
  36. package/dist/prompts/few_shot.cjs.map +1 -1
  37. package/dist/prompts/few_shot.js.map +1 -1
  38. package/dist/prompts/prompt.cjs.map +1 -1
  39. package/dist/prompts/prompt.js.map +1 -1
  40. package/dist/prompts/structured.cjs.map +1 -1
  41. package/dist/prompts/structured.js.map +1 -1
  42. package/dist/retrievers/index.cjs.map +1 -1
  43. package/dist/retrievers/index.js.map +1 -1
  44. package/dist/runnables/base.cjs.map +1 -1
  45. package/dist/runnables/base.js.map +1 -1
  46. package/dist/runnables/history.cjs.map +1 -1
  47. package/dist/runnables/history.js.map +1 -1
  48. package/dist/stores.d.ts.map +1 -1
  49. package/dist/tools/index.cjs.map +1 -1
  50. package/dist/tools/index.js.map +1 -1
  51. package/dist/tools/types.cjs.map +1 -1
  52. package/dist/tools/types.js.map +1 -1
  53. package/dist/tracers/event_stream.cjs.map +1 -1
  54. package/dist/tracers/event_stream.js.map +1 -1
  55. package/dist/tracers/log_stream.cjs.map +1 -1
  56. package/dist/tracers/log_stream.js.map +1 -1
  57. package/dist/utils/fast-json-patch/src/core.cjs +3 -10
  58. package/dist/utils/fast-json-patch/src/core.cjs.map +1 -1
  59. package/dist/utils/fast-json-patch/src/core.js +3 -10
  60. package/dist/utils/fast-json-patch/src/core.js.map +1 -1
  61. package/dist/utils/ssrf.cjs +271 -0
  62. package/dist/utils/ssrf.cjs.map +1 -0
  63. package/dist/utils/ssrf.d.cts +52 -0
  64. package/dist/utils/ssrf.d.cts.map +1 -0
  65. package/dist/utils/ssrf.d.ts +52 -0
  66. package/dist/utils/ssrf.d.ts.map +1 -0
  67. package/dist/utils/ssrf.js +260 -0
  68. package/dist/utils/ssrf.js.map +1 -0
  69. package/dist/utils/stream.cjs.map +1 -1
  70. package/dist/utils/stream.js.map +1 -1
  71. package/dist/utils/testing/chat_models.cjs.map +1 -1
  72. package/dist/utils/testing/chat_models.js.map +1 -1
  73. package/dist/utils/testing/tools.cjs.map +1 -1
  74. package/dist/utils/testing/tools.js.map +1 -1
  75. package/dist/vectorstores.cjs.map +1 -1
  76. package/dist/vectorstores.js.map +1 -1
  77. package/package.json +14 -3
  78. package/utils/ssrf.cjs +1 -0
  79. package/utils/ssrf.d.cts +1 -0
  80. package/utils/ssrf.d.ts +1 -0
  81. package/utils/ssrf.js +1 -0
@@ -1 +1 @@
1
- {"version":3,"file":"log_stream.cjs","names":["fields: { ops?: JSONPatchOperation[] }","other: RunLogPatch","applyPatch","fields: { ops?: JSONPatchOperation[]; state: RunState }","patch: RunLogPatch","handler: BaseCallbackHandler","run: Run","schemaFormat: SchemaFormat","x?: ChatGenerationChunk | GenerationChunk","BaseTracer","fields?: LogStreamCallbackHandlerInput","IterableReadableStream","_run: Run","runId: string","output: AsyncGenerator<T>","logEntry: LogEntry","ops: JSONPatchOperation[]","token: string","kwargs?: HandleLLMNewTokenCallbackFields","AIMessageChunk"],"sources":["../../src/tracers/log_stream.ts"],"sourcesContent":["import {\n applyPatch,\n type Operation as JSONPatchOperation,\n} from \"../utils/fast-json-patch/index.js\";\nimport { BaseTracer, type Run } from \"./base.js\";\nimport {\n BaseCallbackHandler,\n BaseCallbackHandlerInput,\n CallbackHandlerPrefersStreaming,\n HandleLLMNewTokenCallbackFields,\n} from \"../callbacks/base.js\";\nimport { IterableReadableStream } from \"../utils/stream.js\";\nimport { ChatGenerationChunk, GenerationChunk } from \"../outputs.js\";\nimport { AIMessageChunk } from \"../messages/ai.js\";\nimport type { StreamEvent, StreamEventData } from \"./event_stream.js\";\n\nexport type { StreamEvent, StreamEventData };\n\n/**\n * Interface that represents the structure of a log entry in the\n * `LogStreamCallbackHandler`.\n */\nexport type LogEntry = {\n /** ID of the sub-run. */\n id: string;\n /** Name of the object being run. */\n name: string;\n /** Type of the object being run, eg. prompt, chain, llm, etc. */\n type: string;\n /** List of tags for the run. */\n tags: string[];\n /** Key-value pairs of metadata for the run. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n metadata: Record<string, any>;\n /** ISO-8601 timestamp of when the run started. */\n start_time: string;\n /** List of general output chunks streamed by this run. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n streamed_output: any[];\n /** List of LLM tokens streamed by this run, if applicable. */\n streamed_output_str: string[];\n /** Inputs to this run. Not available currently via streamLog. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n inputs?: any;\n /** Final output of this run. Only available after the run has finished successfully. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n final_output?: any;\n /** ISO-8601 timestamp of when the run ended. Only available after the run has finished. */\n end_time?: string;\n};\n\nexport type RunState = {\n /** ID of the sub-run. */\n id: string;\n /** List of output chunks streamed by Runnable.stream() */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n streamed_output: any[];\n /** Final output of the run, usually the result of aggregating streamed_output. Only available after the run has finished successfully. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n final_output?: any;\n /**\n * List of sub-runs contained in this run, if any, in the order they were started.\n * If filters were supplied, this list will contain only the runs that matched the filters.\n */\n logs: Record<string, LogEntry>;\n /** Name of the object being run. */\n name: string;\n /** Type of the object being run, eg. prompt, chain, llm, etc. */\n type: string;\n};\n\n/**\n * List of jsonpatch JSONPatchOperations, which describe how to create the run state\n * from an empty dict. This is the minimal representation of the log, designed to\n * be serialized as JSON and sent over the wire to reconstruct the log on the other\n * side. Reconstruction of the state can be done with any jsonpatch-compliant library,\n * see https://jsonpatch.com for more information.\n */\nexport class RunLogPatch {\n ops: JSONPatchOperation[];\n\n constructor(fields: { ops?: JSONPatchOperation[] }) {\n this.ops = fields.ops ?? [];\n }\n\n concat(other: RunLogPatch) {\n const ops = this.ops.concat(other.ops);\n const states = applyPatch({}, ops);\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n return new RunLog({\n ops,\n state: states[states.length - 1].newDocument as RunState,\n });\n }\n}\n\nexport class RunLog extends RunLogPatch {\n state: RunState;\n\n constructor(fields: { ops?: JSONPatchOperation[]; state: RunState }) {\n super(fields);\n this.state = fields.state;\n }\n\n concat(other: RunLogPatch) {\n const ops = this.ops.concat(other.ops);\n const states = applyPatch(this.state, other.ops);\n return new RunLog({ ops, state: states[states.length - 1].newDocument });\n }\n\n static fromRunLogPatch(patch: RunLogPatch) {\n const states = applyPatch({}, patch.ops);\n return new RunLog({\n ops: patch.ops,\n state: states[states.length - 1].newDocument as RunState,\n });\n }\n}\n\nexport type SchemaFormat = \"original\" | \"streaming_events\";\n\nexport interface LogStreamCallbackHandlerInput\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 _schemaFormat?: SchemaFormat;\n}\n\nexport const isLogStreamHandler = (\n handler: BaseCallbackHandler\n): handler is LogStreamCallbackHandler => handler.name === \"log_stream_tracer\";\n\n/**\n * Extract standardized inputs from a run.\n *\n * Standardizes the inputs based on the type of the runnable used.\n *\n * @param run - Run object\n * @param schemaFormat - The schema format to use.\n *\n * @returns Valid inputs are only dict. By conventions, inputs always represented\n * invocation using named arguments.\n * A null means that the input is not yet known!\n */\nasync function _getStandardizedInputs(run: Run, schemaFormat: SchemaFormat) {\n if (schemaFormat === \"original\") {\n throw new Error(\n \"Do not assign inputs with original schema drop the key for now. \" +\n \"When inputs are added to streamLog they should be added with \" +\n \"standardized schema for streaming events.\"\n );\n }\n\n const { inputs } = run;\n\n if ([\"retriever\", \"llm\", \"prompt\"].includes(run.run_type)) {\n return inputs;\n }\n\n if (Object.keys(inputs).length === 1 && inputs?.input === \"\") {\n return undefined;\n }\n\n // new style chains\n // These nest an additional 'input' key inside the 'inputs' to make sure\n // the input is always a dict. We need to unpack and user the inner value.\n // We should try to fix this in Runnables and callbacks/tracers\n // Runnables should be using a null type here not a placeholder\n // dict.\n return inputs.input;\n}\n\nasync function _getStandardizedOutputs(run: Run, schemaFormat: SchemaFormat) {\n const { outputs } = run;\n if (schemaFormat === \"original\") {\n // Return the old schema, without standardizing anything\n return outputs;\n }\n\n if ([\"retriever\", \"llm\", \"prompt\"].includes(run.run_type)) {\n return outputs;\n }\n\n // TODO: Remove this hacky check\n if (\n outputs !== undefined &&\n Object.keys(outputs).length === 1 &&\n outputs?.output !== undefined\n ) {\n return outputs.output;\n }\n\n return outputs;\n}\n\nfunction isChatGenerationChunk(\n x?: ChatGenerationChunk | GenerationChunk\n): x is ChatGenerationChunk {\n return x !== undefined && (x as ChatGenerationChunk).message !== undefined;\n}\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 LogStreamCallbackHandler\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 protected _schemaFormat: SchemaFormat = \"original\";\n\n protected rootId?: string;\n\n private keyMapByRunId: Record<string, string> = {};\n\n private counterMapByRunName: Record<string, number> = {};\n\n protected transformStream: TransformStream;\n\n public writer: WritableStreamDefaultWriter;\n\n public receiveStream: IterableReadableStream<RunLogPatch>;\n\n name = \"log_stream_tracer\";\n\n lc_prefer_streaming = true;\n\n constructor(fields?: LogStreamCallbackHandlerInput) {\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._schemaFormat = fields?._schemaFormat ?? this._schemaFormat;\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: Run): boolean {\n if (run.id === this.rootId) {\n return false;\n }\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.run_type);\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.run_type);\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 output: AsyncGenerator<T>\n ): AsyncGenerator<T> {\n // Tap an output async iterator to stream its values to the log.\n for await (const chunk of output) {\n // root run is handled in .streamLog()\n if (runId !== this.rootId) {\n // if we can't find the run silently ignore\n // eg. because this run wasn't included in the log\n const key = this.keyMapByRunId[runId];\n if (key) {\n await this.writer.write(\n new RunLogPatch({\n ops: [\n {\n op: \"add\",\n path: `/logs/${key}/streamed_output/-`,\n value: chunk,\n },\n ],\n })\n );\n }\n }\n yield chunk;\n }\n }\n\n async onRunCreate(run: Run): Promise<void> {\n if (this.rootId === undefined) {\n this.rootId = run.id;\n await this.writer.write(\n new RunLogPatch({\n ops: [\n {\n op: \"replace\",\n path: \"\",\n value: {\n id: run.id,\n name: run.name,\n type: run.run_type,\n streamed_output: [],\n final_output: undefined,\n logs: {},\n },\n },\n ],\n })\n );\n }\n\n if (!this._includeRun(run)) {\n return;\n }\n\n if (this.counterMapByRunName[run.name] === undefined) {\n this.counterMapByRunName[run.name] = 0;\n }\n this.counterMapByRunName[run.name] += 1;\n const count = this.counterMapByRunName[run.name];\n this.keyMapByRunId[run.id] =\n count === 1 ? run.name : `${run.name}:${count}`;\n\n const logEntry: LogEntry = {\n id: run.id,\n name: run.name,\n type: run.run_type,\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n start_time: new Date(run.start_time).toISOString(),\n streamed_output: [],\n streamed_output_str: [],\n final_output: undefined,\n end_time: undefined,\n };\n\n if (this._schemaFormat === \"streaming_events\") {\n logEntry.inputs = await _getStandardizedInputs(run, this._schemaFormat);\n }\n\n await this.writer.write(\n new RunLogPatch({\n ops: [\n {\n op: \"add\",\n path: `/logs/${this.keyMapByRunId[run.id]}`,\n value: logEntry,\n },\n ],\n })\n );\n }\n\n async onRunUpdate(run: Run): Promise<void> {\n try {\n const runName = this.keyMapByRunId[run.id];\n if (runName === undefined) {\n return;\n }\n const ops: JSONPatchOperation[] = [];\n if (this._schemaFormat === \"streaming_events\") {\n ops.push({\n op: \"replace\",\n path: `/logs/${runName}/inputs`,\n value: await _getStandardizedInputs(run, this._schemaFormat),\n });\n }\n ops.push({\n op: \"add\",\n path: `/logs/${runName}/final_output`,\n value: await _getStandardizedOutputs(run, this._schemaFormat),\n });\n if (run.end_time !== undefined) {\n ops.push({\n op: \"add\",\n path: `/logs/${runName}/end_time`,\n value: new Date(run.end_time).toISOString(),\n });\n }\n const patch = new RunLogPatch({ ops });\n await this.writer.write(patch);\n } finally {\n if (run.id === this.rootId) {\n const patch = new RunLogPatch({\n ops: [\n {\n op: \"replace\",\n path: \"/final_output\",\n value: await _getStandardizedOutputs(run, this._schemaFormat),\n },\n ],\n });\n await this.writer.write(patch);\n if (this.autoClose) {\n await this.writer.close();\n }\n }\n }\n }\n\n async onLLMNewToken(\n run: Run,\n token: string,\n kwargs?: HandleLLMNewTokenCallbackFields\n ): Promise<void> {\n const runName = this.keyMapByRunId[run.id];\n if (runName === undefined) {\n return;\n }\n // TODO: Remove hack\n const isChatModel = run.inputs.messages !== undefined;\n let streamedOutputValue;\n if (isChatModel) {\n if (isChatGenerationChunk(kwargs?.chunk)) {\n streamedOutputValue = kwargs?.chunk;\n } else {\n streamedOutputValue = new AIMessageChunk({\n id: `run-${run.id}`,\n content: token,\n });\n }\n } else {\n streamedOutputValue = token;\n }\n const patch = new RunLogPatch({\n ops: [\n {\n op: \"add\",\n path: `/logs/${runName}/streamed_output_str/-`,\n value: token,\n },\n {\n op: \"add\",\n path: `/logs/${runName}/streamed_output/-`,\n value: streamedOutputValue,\n },\n ],\n });\n await this.writer.write(patch);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA8EA,IAAa,cAAb,MAAyB;CACvB;CAEA,YAAYA,QAAwC;EAClD,KAAK,MAAM,OAAO,OAAO,CAAE;CAC5B;CAED,OAAOC,OAAoB;EACzB,MAAM,MAAM,KAAK,IAAI,OAAO,MAAM,IAAI;EACtC,MAAM,SAASC,wBAAW,CAAE,GAAE,IAAI;AAElC,SAAO,IAAI,OAAO;GAChB;GACA,OAAO,OAAO,OAAO,SAAS,GAAG;EAClC;CACF;AACF;AAED,IAAa,SAAb,MAAa,eAAe,YAAY;CACtC;CAEA,YAAYC,QAAyD;EACnE,MAAM,OAAO;EACb,KAAK,QAAQ,OAAO;CACrB;CAED,OAAOF,OAAoB;EACzB,MAAM,MAAM,KAAK,IAAI,OAAO,MAAM,IAAI;EACtC,MAAM,SAASC,wBAAW,KAAK,OAAO,MAAM,IAAI;AAChD,SAAO,IAAI,OAAO;GAAE;GAAK,OAAO,OAAO,OAAO,SAAS,GAAG;EAAa;CACxE;CAED,OAAO,gBAAgBE,OAAoB;EACzC,MAAM,SAASF,wBAAW,CAAE,GAAE,MAAM,IAAI;AACxC,SAAO,IAAI,OAAO;GAChB,KAAK,MAAM;GACX,OAAO,OAAO,OAAO,SAAS,GAAG;EAClC;CACF;AACF;AAgBD,MAAa,qBAAqB,CAChCG,YACwC,QAAQ,SAAS;;;;;;;;;;;;;AAc3D,eAAe,uBAAuBC,KAAUC,cAA4B;AAC1E,KAAI,iBAAiB,WACnB,OAAM,IAAI,MACR;CAMJ,MAAM,EAAE,QAAQ,GAAG;AAEnB,KAAI;EAAC;EAAa;EAAO;CAAS,EAAC,SAAS,IAAI,SAAS,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: JSONPatchOperation[] }","other: RunLogPatch","applyPatch","fields: { ops?: JSONPatchOperation[]; state: RunState }","patch: RunLogPatch","handler: BaseCallbackHandler","run: Run","schemaFormat: SchemaFormat","x?: ChatGenerationChunk | GenerationChunk","BaseTracer","fields?: LogStreamCallbackHandlerInput","IterableReadableStream","_run: Run","runId: string","output: AsyncGenerator<T>","logEntry: LogEntry","ops: JSONPatchOperation[]","token: string","kwargs?: HandleLLMNewTokenCallbackFields","AIMessageChunk"],"sources":["../../src/tracers/log_stream.ts"],"sourcesContent":["import {\n applyPatch,\n type Operation as JSONPatchOperation,\n} from \"../utils/fast-json-patch/index.js\";\nimport { BaseTracer, type Run } from \"./base.js\";\nimport {\n BaseCallbackHandler,\n BaseCallbackHandlerInput,\n CallbackHandlerPrefersStreaming,\n HandleLLMNewTokenCallbackFields,\n} from \"../callbacks/base.js\";\nimport { IterableReadableStream } from \"../utils/stream.js\";\nimport { ChatGenerationChunk, GenerationChunk } from \"../outputs.js\";\nimport { AIMessageChunk } from \"../messages/ai.js\";\nimport type { StreamEvent, StreamEventData } from \"./event_stream.js\";\n\nexport type { StreamEvent, StreamEventData };\n\n/**\n * Interface that represents the structure of a log entry in the\n * `LogStreamCallbackHandler`.\n */\nexport type LogEntry = {\n /** ID of the sub-run. */\n id: string;\n /** Name of the object being run. */\n name: string;\n /** Type of the object being run, eg. prompt, chain, llm, etc. */\n type: string;\n /** List of tags for the run. */\n tags: string[];\n /** Key-value pairs of metadata for the run. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n metadata: Record<string, any>;\n /** ISO-8601 timestamp of when the run started. */\n start_time: string;\n /** List of general output chunks streamed by this run. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n streamed_output: any[];\n /** List of LLM tokens streamed by this run, if applicable. */\n streamed_output_str: string[];\n /** Inputs to this run. Not available currently via streamLog. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n inputs?: any;\n /** Final output of this run. Only available after the run has finished successfully. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n final_output?: any;\n /** ISO-8601 timestamp of when the run ended. Only available after the run has finished. */\n end_time?: string;\n};\n\nexport type RunState = {\n /** ID of the sub-run. */\n id: string;\n /** List of output chunks streamed by Runnable.stream() */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n streamed_output: any[];\n /** Final output of the run, usually the result of aggregating streamed_output. Only available after the run has finished successfully. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n final_output?: any;\n /**\n * List of sub-runs contained in this run, if any, in the order they were started.\n * If filters were supplied, this list will contain only the runs that matched the filters.\n */\n logs: Record<string, LogEntry>;\n /** Name of the object being run. */\n name: string;\n /** Type of the object being run, eg. prompt, chain, llm, etc. */\n type: string;\n};\n\n/**\n * List of jsonpatch JSONPatchOperations, which describe how to create the run state\n * from an empty dict. This is the minimal representation of the log, designed to\n * be serialized as JSON and sent over the wire to reconstruct the log on the other\n * side. Reconstruction of the state can be done with any jsonpatch-compliant library,\n * see https://jsonpatch.com for more information.\n */\nexport class RunLogPatch {\n ops: JSONPatchOperation[];\n\n constructor(fields: { ops?: JSONPatchOperation[] }) {\n this.ops = fields.ops ?? [];\n }\n\n concat(other: RunLogPatch) {\n const ops = this.ops.concat(other.ops);\n const states = applyPatch({}, ops);\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n return new RunLog({\n ops,\n state: states[states.length - 1].newDocument as RunState,\n });\n }\n}\n\nexport class RunLog extends RunLogPatch {\n state: RunState;\n\n constructor(fields: { ops?: JSONPatchOperation[]; state: RunState }) {\n super(fields);\n this.state = fields.state;\n }\n\n concat(other: RunLogPatch) {\n const ops = this.ops.concat(other.ops);\n const states = applyPatch(this.state, other.ops);\n return new RunLog({ ops, state: states[states.length - 1].newDocument });\n }\n\n static fromRunLogPatch(patch: RunLogPatch) {\n const states = applyPatch({}, patch.ops);\n return new RunLog({\n ops: patch.ops,\n state: states[states.length - 1].newDocument as RunState,\n });\n }\n}\n\nexport type SchemaFormat = \"original\" | \"streaming_events\";\n\nexport interface LogStreamCallbackHandlerInput extends BaseCallbackHandlerInput {\n autoClose?: boolean;\n includeNames?: string[];\n includeTypes?: string[];\n includeTags?: string[];\n excludeNames?: string[];\n excludeTypes?: string[];\n excludeTags?: string[];\n _schemaFormat?: SchemaFormat;\n}\n\nexport const isLogStreamHandler = (\n handler: BaseCallbackHandler\n): handler is LogStreamCallbackHandler => handler.name === \"log_stream_tracer\";\n\n/**\n * Extract standardized inputs from a run.\n *\n * Standardizes the inputs based on the type of the runnable used.\n *\n * @param run - Run object\n * @param schemaFormat - The schema format to use.\n *\n * @returns Valid inputs are only dict. By conventions, inputs always represented\n * invocation using named arguments.\n * A null means that the input is not yet known!\n */\nasync function _getStandardizedInputs(run: Run, schemaFormat: SchemaFormat) {\n if (schemaFormat === \"original\") {\n throw new Error(\n \"Do not assign inputs with original schema drop the key for now. \" +\n \"When inputs are added to streamLog they should be added with \" +\n \"standardized schema for streaming events.\"\n );\n }\n\n const { inputs } = run;\n\n if ([\"retriever\", \"llm\", \"prompt\"].includes(run.run_type)) {\n return inputs;\n }\n\n if (Object.keys(inputs).length === 1 && inputs?.input === \"\") {\n return undefined;\n }\n\n // new style chains\n // These nest an additional 'input' key inside the 'inputs' to make sure\n // the input is always a dict. We need to unpack and user the inner value.\n // We should try to fix this in Runnables and callbacks/tracers\n // Runnables should be using a null type here not a placeholder\n // dict.\n return inputs.input;\n}\n\nasync function _getStandardizedOutputs(run: Run, schemaFormat: SchemaFormat) {\n const { outputs } = run;\n if (schemaFormat === \"original\") {\n // Return the old schema, without standardizing anything\n return outputs;\n }\n\n if ([\"retriever\", \"llm\", \"prompt\"].includes(run.run_type)) {\n return outputs;\n }\n\n // TODO: Remove this hacky check\n if (\n outputs !== undefined &&\n Object.keys(outputs).length === 1 &&\n outputs?.output !== undefined\n ) {\n return outputs.output;\n }\n\n return outputs;\n}\n\nfunction isChatGenerationChunk(\n x?: ChatGenerationChunk | GenerationChunk\n): x is ChatGenerationChunk {\n return x !== undefined && (x as ChatGenerationChunk).message !== undefined;\n}\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 LogStreamCallbackHandler\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 protected _schemaFormat: SchemaFormat = \"original\";\n\n protected rootId?: string;\n\n private keyMapByRunId: Record<string, string> = {};\n\n private counterMapByRunName: Record<string, number> = {};\n\n protected transformStream: TransformStream;\n\n public writer: WritableStreamDefaultWriter;\n\n public receiveStream: IterableReadableStream<RunLogPatch>;\n\n name = \"log_stream_tracer\";\n\n lc_prefer_streaming = true;\n\n constructor(fields?: LogStreamCallbackHandlerInput) {\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._schemaFormat = fields?._schemaFormat ?? this._schemaFormat;\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: Run): boolean {\n if (run.id === this.rootId) {\n return false;\n }\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.run_type);\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.run_type);\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 output: AsyncGenerator<T>\n ): AsyncGenerator<T> {\n // Tap an output async iterator to stream its values to the log.\n for await (const chunk of output) {\n // root run is handled in .streamLog()\n if (runId !== this.rootId) {\n // if we can't find the run silently ignore\n // eg. because this run wasn't included in the log\n const key = this.keyMapByRunId[runId];\n if (key) {\n await this.writer.write(\n new RunLogPatch({\n ops: [\n {\n op: \"add\",\n path: `/logs/${key}/streamed_output/-`,\n value: chunk,\n },\n ],\n })\n );\n }\n }\n yield chunk;\n }\n }\n\n async onRunCreate(run: Run): Promise<void> {\n if (this.rootId === undefined) {\n this.rootId = run.id;\n await this.writer.write(\n new RunLogPatch({\n ops: [\n {\n op: \"replace\",\n path: \"\",\n value: {\n id: run.id,\n name: run.name,\n type: run.run_type,\n streamed_output: [],\n final_output: undefined,\n logs: {},\n },\n },\n ],\n })\n );\n }\n\n if (!this._includeRun(run)) {\n return;\n }\n\n if (this.counterMapByRunName[run.name] === undefined) {\n this.counterMapByRunName[run.name] = 0;\n }\n this.counterMapByRunName[run.name] += 1;\n const count = this.counterMapByRunName[run.name];\n this.keyMapByRunId[run.id] =\n count === 1 ? run.name : `${run.name}:${count}`;\n\n const logEntry: LogEntry = {\n id: run.id,\n name: run.name,\n type: run.run_type,\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n start_time: new Date(run.start_time).toISOString(),\n streamed_output: [],\n streamed_output_str: [],\n final_output: undefined,\n end_time: undefined,\n };\n\n if (this._schemaFormat === \"streaming_events\") {\n logEntry.inputs = await _getStandardizedInputs(run, this._schemaFormat);\n }\n\n await this.writer.write(\n new RunLogPatch({\n ops: [\n {\n op: \"add\",\n path: `/logs/${this.keyMapByRunId[run.id]}`,\n value: logEntry,\n },\n ],\n })\n );\n }\n\n async onRunUpdate(run: Run): Promise<void> {\n try {\n const runName = this.keyMapByRunId[run.id];\n if (runName === undefined) {\n return;\n }\n const ops: JSONPatchOperation[] = [];\n if (this._schemaFormat === \"streaming_events\") {\n ops.push({\n op: \"replace\",\n path: `/logs/${runName}/inputs`,\n value: await _getStandardizedInputs(run, this._schemaFormat),\n });\n }\n ops.push({\n op: \"add\",\n path: `/logs/${runName}/final_output`,\n value: await _getStandardizedOutputs(run, this._schemaFormat),\n });\n if (run.end_time !== undefined) {\n ops.push({\n op: \"add\",\n path: `/logs/${runName}/end_time`,\n value: new Date(run.end_time).toISOString(),\n });\n }\n const patch = new RunLogPatch({ ops });\n await this.writer.write(patch);\n } finally {\n if (run.id === this.rootId) {\n const patch = new RunLogPatch({\n ops: [\n {\n op: \"replace\",\n path: \"/final_output\",\n value: await _getStandardizedOutputs(run, this._schemaFormat),\n },\n ],\n });\n await this.writer.write(patch);\n if (this.autoClose) {\n await this.writer.close();\n }\n }\n }\n }\n\n async onLLMNewToken(\n run: Run,\n token: string,\n kwargs?: HandleLLMNewTokenCallbackFields\n ): Promise<void> {\n const runName = this.keyMapByRunId[run.id];\n if (runName === undefined) {\n return;\n }\n // TODO: Remove hack\n const isChatModel = run.inputs.messages !== undefined;\n let streamedOutputValue;\n if (isChatModel) {\n if (isChatGenerationChunk(kwargs?.chunk)) {\n streamedOutputValue = kwargs?.chunk;\n } else {\n streamedOutputValue = new AIMessageChunk({\n id: `run-${run.id}`,\n content: token,\n });\n }\n } else {\n streamedOutputValue = token;\n }\n const patch = new RunLogPatch({\n ops: [\n {\n op: \"add\",\n path: `/logs/${runName}/streamed_output_str/-`,\n value: token,\n },\n {\n op: \"add\",\n path: `/logs/${runName}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IAAI;IACJ,MAAM,CAAC,MAAM,EAAE,QAAQ,SAAS,CAAC;IACjC,OAAO,IAAI,KAAK,IAAI,UAAU,aAAa;GAC5C,EAAC;GAEJ,MAAM,QAAQ,IAAI,YAAY,EAAE,IAAK;GACrC,MAAM,KAAK,OAAO,MAAM,MAAM;EAC/B,UAAS;AACR,OAAI,IAAI,OAAO,KAAK,QAAQ;IAC1B,MAAM,QAAQ,IAAI,YAAY,EAC5B,KAAK,CACH;KACE,IAAI;KACJ,MAAM;KACN,OAAO,MAAM,wBAAwB,KAAK,KAAK,cAAc;IAC9D,CACF,EACF;IACD,MAAM,KAAK,OAAO,MAAM,MAAM;AAC9B,QAAI,KAAK,WACP,MAAM,KAAK,OAAO,OAAO;GAE5B;EACF;CACF;CAED,MAAM,cACJV,KACAW,OACAC,QACe;EACf,MAAM,UAAU,KAAK,cAAc,IAAI;AACvC,MAAI,YAAY,OACd;EAGF,MAAM,cAAc,IAAI,OAAO,aAAa;EAC5C,IAAI;AACJ,MAAI,YACF,KAAI,sBAAsB,QAAQ,MAAM,EACtC,sBAAsB,QAAQ;OAE9B,sBAAsB,IAAIC,0BAAe;GACvC,IAAI,CAAC,IAAI,EAAE,IAAI,IAAI;GACnB,SAAS;EACV;OAGH,sBAAsB;EAExB,MAAM,QAAQ,IAAI,YAAY,EAC5B,KAAK,CACH;GACE,IAAI;GACJ,MAAM,CAAC,MAAM,EAAE,QAAQ,sBAAsB,CAAC;GAC9C,OAAO;EACR,GACD;GACE,IAAI;GACJ,MAAM,CAAC,MAAM,EAAE,QAAQ,kBAAkB,CAAC;GAC1C,OAAO;EACR,CACF,EACF;EACD,MAAM,KAAK,OAAO,MAAM,MAAM;CAC/B;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"log_stream.js","names":["fields: { ops?: JSONPatchOperation[] }","other: RunLogPatch","fields: { ops?: JSONPatchOperation[]; state: RunState }","patch: RunLogPatch","handler: BaseCallbackHandler","run: Run","schemaFormat: SchemaFormat","x?: ChatGenerationChunk | GenerationChunk","fields?: LogStreamCallbackHandlerInput","_run: Run","runId: string","output: AsyncGenerator<T>","logEntry: LogEntry","ops: JSONPatchOperation[]","token: string","kwargs?: HandleLLMNewTokenCallbackFields"],"sources":["../../src/tracers/log_stream.ts"],"sourcesContent":["import {\n applyPatch,\n type Operation as JSONPatchOperation,\n} from \"../utils/fast-json-patch/index.js\";\nimport { BaseTracer, type Run } from \"./base.js\";\nimport {\n BaseCallbackHandler,\n BaseCallbackHandlerInput,\n CallbackHandlerPrefersStreaming,\n HandleLLMNewTokenCallbackFields,\n} from \"../callbacks/base.js\";\nimport { IterableReadableStream } from \"../utils/stream.js\";\nimport { ChatGenerationChunk, GenerationChunk } from \"../outputs.js\";\nimport { AIMessageChunk } from \"../messages/ai.js\";\nimport type { StreamEvent, StreamEventData } from \"./event_stream.js\";\n\nexport type { StreamEvent, StreamEventData };\n\n/**\n * Interface that represents the structure of a log entry in the\n * `LogStreamCallbackHandler`.\n */\nexport type LogEntry = {\n /** ID of the sub-run. */\n id: string;\n /** Name of the object being run. */\n name: string;\n /** Type of the object being run, eg. prompt, chain, llm, etc. */\n type: string;\n /** List of tags for the run. */\n tags: string[];\n /** Key-value pairs of metadata for the run. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n metadata: Record<string, any>;\n /** ISO-8601 timestamp of when the run started. */\n start_time: string;\n /** List of general output chunks streamed by this run. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n streamed_output: any[];\n /** List of LLM tokens streamed by this run, if applicable. */\n streamed_output_str: string[];\n /** Inputs to this run. Not available currently via streamLog. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n inputs?: any;\n /** Final output of this run. Only available after the run has finished successfully. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n final_output?: any;\n /** ISO-8601 timestamp of when the run ended. Only available after the run has finished. */\n end_time?: string;\n};\n\nexport type RunState = {\n /** ID of the sub-run. */\n id: string;\n /** List of output chunks streamed by Runnable.stream() */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n streamed_output: any[];\n /** Final output of the run, usually the result of aggregating streamed_output. Only available after the run has finished successfully. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n final_output?: any;\n /**\n * List of sub-runs contained in this run, if any, in the order they were started.\n * If filters were supplied, this list will contain only the runs that matched the filters.\n */\n logs: Record<string, LogEntry>;\n /** Name of the object being run. */\n name: string;\n /** Type of the object being run, eg. prompt, chain, llm, etc. */\n type: string;\n};\n\n/**\n * List of jsonpatch JSONPatchOperations, which describe how to create the run state\n * from an empty dict. This is the minimal representation of the log, designed to\n * be serialized as JSON and sent over the wire to reconstruct the log on the other\n * side. Reconstruction of the state can be done with any jsonpatch-compliant library,\n * see https://jsonpatch.com for more information.\n */\nexport class RunLogPatch {\n ops: JSONPatchOperation[];\n\n constructor(fields: { ops?: JSONPatchOperation[] }) {\n this.ops = fields.ops ?? [];\n }\n\n concat(other: RunLogPatch) {\n const ops = this.ops.concat(other.ops);\n const states = applyPatch({}, ops);\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n return new RunLog({\n ops,\n state: states[states.length - 1].newDocument as RunState,\n });\n }\n}\n\nexport class RunLog extends RunLogPatch {\n state: RunState;\n\n constructor(fields: { ops?: JSONPatchOperation[]; state: RunState }) {\n super(fields);\n this.state = fields.state;\n }\n\n concat(other: RunLogPatch) {\n const ops = this.ops.concat(other.ops);\n const states = applyPatch(this.state, other.ops);\n return new RunLog({ ops, state: states[states.length - 1].newDocument });\n }\n\n static fromRunLogPatch(patch: RunLogPatch) {\n const states = applyPatch({}, patch.ops);\n return new RunLog({\n ops: patch.ops,\n state: states[states.length - 1].newDocument as RunState,\n });\n }\n}\n\nexport type SchemaFormat = \"original\" | \"streaming_events\";\n\nexport interface LogStreamCallbackHandlerInput\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 _schemaFormat?: SchemaFormat;\n}\n\nexport const isLogStreamHandler = (\n handler: BaseCallbackHandler\n): handler is LogStreamCallbackHandler => handler.name === \"log_stream_tracer\";\n\n/**\n * Extract standardized inputs from a run.\n *\n * Standardizes the inputs based on the type of the runnable used.\n *\n * @param run - Run object\n * @param schemaFormat - The schema format to use.\n *\n * @returns Valid inputs are only dict. By conventions, inputs always represented\n * invocation using named arguments.\n * A null means that the input is not yet known!\n */\nasync function _getStandardizedInputs(run: Run, schemaFormat: SchemaFormat) {\n if (schemaFormat === \"original\") {\n throw new Error(\n \"Do not assign inputs with original schema drop the key for now. \" +\n \"When inputs are added to streamLog they should be added with \" +\n \"standardized schema for streaming events.\"\n );\n }\n\n const { inputs } = run;\n\n if ([\"retriever\", \"llm\", \"prompt\"].includes(run.run_type)) {\n return inputs;\n }\n\n if (Object.keys(inputs).length === 1 && inputs?.input === \"\") {\n return undefined;\n }\n\n // new style chains\n // These nest an additional 'input' key inside the 'inputs' to make sure\n // the input is always a dict. We need to unpack and user the inner value.\n // We should try to fix this in Runnables and callbacks/tracers\n // Runnables should be using a null type here not a placeholder\n // dict.\n return inputs.input;\n}\n\nasync function _getStandardizedOutputs(run: Run, schemaFormat: SchemaFormat) {\n const { outputs } = run;\n if (schemaFormat === \"original\") {\n // Return the old schema, without standardizing anything\n return outputs;\n }\n\n if ([\"retriever\", \"llm\", \"prompt\"].includes(run.run_type)) {\n return outputs;\n }\n\n // TODO: Remove this hacky check\n if (\n outputs !== undefined &&\n Object.keys(outputs).length === 1 &&\n outputs?.output !== undefined\n ) {\n return outputs.output;\n }\n\n return outputs;\n}\n\nfunction isChatGenerationChunk(\n x?: ChatGenerationChunk | GenerationChunk\n): x is ChatGenerationChunk {\n return x !== undefined && (x as ChatGenerationChunk).message !== undefined;\n}\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 LogStreamCallbackHandler\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 protected _schemaFormat: SchemaFormat = \"original\";\n\n protected rootId?: string;\n\n private keyMapByRunId: Record<string, string> = {};\n\n private counterMapByRunName: Record<string, number> = {};\n\n protected transformStream: TransformStream;\n\n public writer: WritableStreamDefaultWriter;\n\n public receiveStream: IterableReadableStream<RunLogPatch>;\n\n name = \"log_stream_tracer\";\n\n lc_prefer_streaming = true;\n\n constructor(fields?: LogStreamCallbackHandlerInput) {\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._schemaFormat = fields?._schemaFormat ?? this._schemaFormat;\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: Run): boolean {\n if (run.id === this.rootId) {\n return false;\n }\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.run_type);\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.run_type);\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 output: AsyncGenerator<T>\n ): AsyncGenerator<T> {\n // Tap an output async iterator to stream its values to the log.\n for await (const chunk of output) {\n // root run is handled in .streamLog()\n if (runId !== this.rootId) {\n // if we can't find the run silently ignore\n // eg. because this run wasn't included in the log\n const key = this.keyMapByRunId[runId];\n if (key) {\n await this.writer.write(\n new RunLogPatch({\n ops: [\n {\n op: \"add\",\n path: `/logs/${key}/streamed_output/-`,\n value: chunk,\n },\n ],\n })\n );\n }\n }\n yield chunk;\n }\n }\n\n async onRunCreate(run: Run): Promise<void> {\n if (this.rootId === undefined) {\n this.rootId = run.id;\n await this.writer.write(\n new RunLogPatch({\n ops: [\n {\n op: \"replace\",\n path: \"\",\n value: {\n id: run.id,\n name: run.name,\n type: run.run_type,\n streamed_output: [],\n final_output: undefined,\n logs: {},\n },\n },\n ],\n })\n );\n }\n\n if (!this._includeRun(run)) {\n return;\n }\n\n if (this.counterMapByRunName[run.name] === undefined) {\n this.counterMapByRunName[run.name] = 0;\n }\n this.counterMapByRunName[run.name] += 1;\n const count = this.counterMapByRunName[run.name];\n this.keyMapByRunId[run.id] =\n count === 1 ? run.name : `${run.name}:${count}`;\n\n const logEntry: LogEntry = {\n id: run.id,\n name: run.name,\n type: run.run_type,\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n start_time: new Date(run.start_time).toISOString(),\n streamed_output: [],\n streamed_output_str: [],\n final_output: undefined,\n end_time: undefined,\n };\n\n if (this._schemaFormat === \"streaming_events\") {\n logEntry.inputs = await _getStandardizedInputs(run, this._schemaFormat);\n }\n\n await this.writer.write(\n new RunLogPatch({\n ops: [\n {\n op: \"add\",\n path: `/logs/${this.keyMapByRunId[run.id]}`,\n value: logEntry,\n },\n ],\n })\n );\n }\n\n async onRunUpdate(run: Run): Promise<void> {\n try {\n const runName = this.keyMapByRunId[run.id];\n if (runName === undefined) {\n return;\n }\n const ops: JSONPatchOperation[] = [];\n if (this._schemaFormat === \"streaming_events\") {\n ops.push({\n op: \"replace\",\n path: `/logs/${runName}/inputs`,\n value: await _getStandardizedInputs(run, this._schemaFormat),\n });\n }\n ops.push({\n op: \"add\",\n path: `/logs/${runName}/final_output`,\n value: await _getStandardizedOutputs(run, this._schemaFormat),\n });\n if (run.end_time !== undefined) {\n ops.push({\n op: \"add\",\n path: `/logs/${runName}/end_time`,\n value: new Date(run.end_time).toISOString(),\n });\n }\n const patch = new RunLogPatch({ ops });\n await this.writer.write(patch);\n } finally {\n if (run.id === this.rootId) {\n const patch = new RunLogPatch({\n ops: [\n {\n op: \"replace\",\n path: \"/final_output\",\n value: await _getStandardizedOutputs(run, this._schemaFormat),\n },\n ],\n });\n await this.writer.write(patch);\n if (this.autoClose) {\n await this.writer.close();\n }\n }\n }\n }\n\n async onLLMNewToken(\n run: Run,\n token: string,\n kwargs?: HandleLLMNewTokenCallbackFields\n ): Promise<void> {\n const runName = this.keyMapByRunId[run.id];\n if (runName === undefined) {\n return;\n }\n // TODO: Remove hack\n const isChatModel = run.inputs.messages !== undefined;\n let streamedOutputValue;\n if (isChatModel) {\n if (isChatGenerationChunk(kwargs?.chunk)) {\n streamedOutputValue = kwargs?.chunk;\n } else {\n streamedOutputValue = new AIMessageChunk({\n id: `run-${run.id}`,\n content: token,\n });\n }\n } else {\n streamedOutputValue = token;\n }\n const patch = new RunLogPatch({\n ops: [\n {\n op: \"add\",\n path: `/logs/${runName}/streamed_output_str/-`,\n value: token,\n },\n {\n op: \"add\",\n path: `/logs/${runName}/streamed_output/-`,\n value: streamedOutputValue,\n },\n ],\n });\n await this.writer.write(patch);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA8EA,IAAa,cAAb,MAAyB;CACvB;CAEA,YAAYA,QAAwC;EAClD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MAAM,KAAK,OAAO,MAAM,MAAM;EAC/B,UAAS;AACR,OAAI,IAAI,OAAO,KAAK,QAAQ;IAC1B,MAAM,QAAQ,IAAI,YAAY,EAC5B,KAAK,CACH;KACE,IAAI;KACJ,MAAM;KACN,OAAO,MAAM,wBAAwB,KAAK,KAAK,cAAc;IAC9D,CACF,EACF;IACD,MAAM,KAAK,OAAO,MAAM,MAAM;AAC9B,QAAI,KAAK,WACP,MAAM,KAAK,OAAO,OAAO;GAE5B;EACF;CACF;CAED,MAAM,cACJR,KACAS,OACAC,QACe;EACf,MAAM,UAAU,KAAK,cAAc,IAAI;AACvC,MAAI,YAAY,OACd;EAGF,MAAM,cAAc,IAAI,OAAO,aAAa;EAC5C,IAAI;AACJ,MAAI,YACF,KAAI,sBAAsB,QAAQ,MAAM,EACtC,sBAAsB,QAAQ;OAE9B,sBAAsB,IAAI,eAAe;GACvC,IAAI,CAAC,IAAI,EAAE,IAAI,IAAI;GACnB,SAAS;EACV;OAGH,sBAAsB;EAExB,MAAM,QAAQ,IAAI,YAAY,EAC5B,KAAK,CACH;GACE,IAAI;GACJ,MAAM,CAAC,MAAM,EAAE,QAAQ,sBAAsB,CAAC;GAC9C,OAAO;EACR,GACD;GACE,IAAI;GACJ,MAAM,CAAC,MAAM,EAAE,QAAQ,kBAAkB,CAAC;GAC1C,OAAO;EACR,CACF,EACF;EACD,MAAM,KAAK,OAAO,MAAM,MAAM;CAC/B;AACF"}
1
+ {"version":3,"file":"log_stream.js","names":["fields: { ops?: JSONPatchOperation[] }","other: RunLogPatch","fields: { ops?: JSONPatchOperation[]; state: RunState }","patch: RunLogPatch","handler: BaseCallbackHandler","run: Run","schemaFormat: SchemaFormat","x?: ChatGenerationChunk | GenerationChunk","fields?: LogStreamCallbackHandlerInput","_run: Run","runId: string","output: AsyncGenerator<T>","logEntry: LogEntry","ops: JSONPatchOperation[]","token: string","kwargs?: HandleLLMNewTokenCallbackFields"],"sources":["../../src/tracers/log_stream.ts"],"sourcesContent":["import {\n applyPatch,\n type Operation as JSONPatchOperation,\n} from \"../utils/fast-json-patch/index.js\";\nimport { BaseTracer, type Run } from \"./base.js\";\nimport {\n BaseCallbackHandler,\n BaseCallbackHandlerInput,\n CallbackHandlerPrefersStreaming,\n HandleLLMNewTokenCallbackFields,\n} from \"../callbacks/base.js\";\nimport { IterableReadableStream } from \"../utils/stream.js\";\nimport { ChatGenerationChunk, GenerationChunk } from \"../outputs.js\";\nimport { AIMessageChunk } from \"../messages/ai.js\";\nimport type { StreamEvent, StreamEventData } from \"./event_stream.js\";\n\nexport type { StreamEvent, StreamEventData };\n\n/**\n * Interface that represents the structure of a log entry in the\n * `LogStreamCallbackHandler`.\n */\nexport type LogEntry = {\n /** ID of the sub-run. */\n id: string;\n /** Name of the object being run. */\n name: string;\n /** Type of the object being run, eg. prompt, chain, llm, etc. */\n type: string;\n /** List of tags for the run. */\n tags: string[];\n /** Key-value pairs of metadata for the run. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n metadata: Record<string, any>;\n /** ISO-8601 timestamp of when the run started. */\n start_time: string;\n /** List of general output chunks streamed by this run. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n streamed_output: any[];\n /** List of LLM tokens streamed by this run, if applicable. */\n streamed_output_str: string[];\n /** Inputs to this run. Not available currently via streamLog. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n inputs?: any;\n /** Final output of this run. Only available after the run has finished successfully. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n final_output?: any;\n /** ISO-8601 timestamp of when the run ended. Only available after the run has finished. */\n end_time?: string;\n};\n\nexport type RunState = {\n /** ID of the sub-run. */\n id: string;\n /** List of output chunks streamed by Runnable.stream() */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n streamed_output: any[];\n /** Final output of the run, usually the result of aggregating streamed_output. Only available after the run has finished successfully. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n final_output?: any;\n /**\n * List of sub-runs contained in this run, if any, in the order they were started.\n * If filters were supplied, this list will contain only the runs that matched the filters.\n */\n logs: Record<string, LogEntry>;\n /** Name of the object being run. */\n name: string;\n /** Type of the object being run, eg. prompt, chain, llm, etc. */\n type: string;\n};\n\n/**\n * List of jsonpatch JSONPatchOperations, which describe how to create the run state\n * from an empty dict. This is the minimal representation of the log, designed to\n * be serialized as JSON and sent over the wire to reconstruct the log on the other\n * side. Reconstruction of the state can be done with any jsonpatch-compliant library,\n * see https://jsonpatch.com for more information.\n */\nexport class RunLogPatch {\n ops: JSONPatchOperation[];\n\n constructor(fields: { ops?: JSONPatchOperation[] }) {\n this.ops = fields.ops ?? [];\n }\n\n concat(other: RunLogPatch) {\n const ops = this.ops.concat(other.ops);\n const states = applyPatch({}, ops);\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n return new RunLog({\n ops,\n state: states[states.length - 1].newDocument as RunState,\n });\n }\n}\n\nexport class RunLog extends RunLogPatch {\n state: RunState;\n\n constructor(fields: { ops?: JSONPatchOperation[]; state: RunState }) {\n super(fields);\n this.state = fields.state;\n }\n\n concat(other: RunLogPatch) {\n const ops = this.ops.concat(other.ops);\n const states = applyPatch(this.state, other.ops);\n return new RunLog({ ops, state: states[states.length - 1].newDocument });\n }\n\n static fromRunLogPatch(patch: RunLogPatch) {\n const states = applyPatch({}, patch.ops);\n return new RunLog({\n ops: patch.ops,\n state: states[states.length - 1].newDocument as RunState,\n });\n }\n}\n\nexport type SchemaFormat = \"original\" | \"streaming_events\";\n\nexport interface LogStreamCallbackHandlerInput extends BaseCallbackHandlerInput {\n autoClose?: boolean;\n includeNames?: string[];\n includeTypes?: string[];\n includeTags?: string[];\n excludeNames?: string[];\n excludeTypes?: string[];\n excludeTags?: string[];\n _schemaFormat?: SchemaFormat;\n}\n\nexport const isLogStreamHandler = (\n handler: BaseCallbackHandler\n): handler is LogStreamCallbackHandler => handler.name === \"log_stream_tracer\";\n\n/**\n * Extract standardized inputs from a run.\n *\n * Standardizes the inputs based on the type of the runnable used.\n *\n * @param run - Run object\n * @param schemaFormat - The schema format to use.\n *\n * @returns Valid inputs are only dict. By conventions, inputs always represented\n * invocation using named arguments.\n * A null means that the input is not yet known!\n */\nasync function _getStandardizedInputs(run: Run, schemaFormat: SchemaFormat) {\n if (schemaFormat === \"original\") {\n throw new Error(\n \"Do not assign inputs with original schema drop the key for now. \" +\n \"When inputs are added to streamLog they should be added with \" +\n \"standardized schema for streaming events.\"\n );\n }\n\n const { inputs } = run;\n\n if ([\"retriever\", \"llm\", \"prompt\"].includes(run.run_type)) {\n return inputs;\n }\n\n if (Object.keys(inputs).length === 1 && inputs?.input === \"\") {\n return undefined;\n }\n\n // new style chains\n // These nest an additional 'input' key inside the 'inputs' to make sure\n // the input is always a dict. We need to unpack and user the inner value.\n // We should try to fix this in Runnables and callbacks/tracers\n // Runnables should be using a null type here not a placeholder\n // dict.\n return inputs.input;\n}\n\nasync function _getStandardizedOutputs(run: Run, schemaFormat: SchemaFormat) {\n const { outputs } = run;\n if (schemaFormat === \"original\") {\n // Return the old schema, without standardizing anything\n return outputs;\n }\n\n if ([\"retriever\", \"llm\", \"prompt\"].includes(run.run_type)) {\n return outputs;\n }\n\n // TODO: Remove this hacky check\n if (\n outputs !== undefined &&\n Object.keys(outputs).length === 1 &&\n outputs?.output !== undefined\n ) {\n return outputs.output;\n }\n\n return outputs;\n}\n\nfunction isChatGenerationChunk(\n x?: ChatGenerationChunk | GenerationChunk\n): x is ChatGenerationChunk {\n return x !== undefined && (x as ChatGenerationChunk).message !== undefined;\n}\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 LogStreamCallbackHandler\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 protected _schemaFormat: SchemaFormat = \"original\";\n\n protected rootId?: string;\n\n private keyMapByRunId: Record<string, string> = {};\n\n private counterMapByRunName: Record<string, number> = {};\n\n protected transformStream: TransformStream;\n\n public writer: WritableStreamDefaultWriter;\n\n public receiveStream: IterableReadableStream<RunLogPatch>;\n\n name = \"log_stream_tracer\";\n\n lc_prefer_streaming = true;\n\n constructor(fields?: LogStreamCallbackHandlerInput) {\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._schemaFormat = fields?._schemaFormat ?? this._schemaFormat;\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: Run): boolean {\n if (run.id === this.rootId) {\n return false;\n }\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.run_type);\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.run_type);\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 output: AsyncGenerator<T>\n ): AsyncGenerator<T> {\n // Tap an output async iterator to stream its values to the log.\n for await (const chunk of output) {\n // root run is handled in .streamLog()\n if (runId !== this.rootId) {\n // if we can't find the run silently ignore\n // eg. because this run wasn't included in the log\n const key = this.keyMapByRunId[runId];\n if (key) {\n await this.writer.write(\n new RunLogPatch({\n ops: [\n {\n op: \"add\",\n path: `/logs/${key}/streamed_output/-`,\n value: chunk,\n },\n ],\n })\n );\n }\n }\n yield chunk;\n }\n }\n\n async onRunCreate(run: Run): Promise<void> {\n if (this.rootId === undefined) {\n this.rootId = run.id;\n await this.writer.write(\n new RunLogPatch({\n ops: [\n {\n op: \"replace\",\n path: \"\",\n value: {\n id: run.id,\n name: run.name,\n type: run.run_type,\n streamed_output: [],\n final_output: undefined,\n logs: {},\n },\n },\n ],\n })\n );\n }\n\n if (!this._includeRun(run)) {\n return;\n }\n\n if (this.counterMapByRunName[run.name] === undefined) {\n this.counterMapByRunName[run.name] = 0;\n }\n this.counterMapByRunName[run.name] += 1;\n const count = this.counterMapByRunName[run.name];\n this.keyMapByRunId[run.id] =\n count === 1 ? run.name : `${run.name}:${count}`;\n\n const logEntry: LogEntry = {\n id: run.id,\n name: run.name,\n type: run.run_type,\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n start_time: new Date(run.start_time).toISOString(),\n streamed_output: [],\n streamed_output_str: [],\n final_output: undefined,\n end_time: undefined,\n };\n\n if (this._schemaFormat === \"streaming_events\") {\n logEntry.inputs = await _getStandardizedInputs(run, this._schemaFormat);\n }\n\n await this.writer.write(\n new RunLogPatch({\n ops: [\n {\n op: \"add\",\n path: `/logs/${this.keyMapByRunId[run.id]}`,\n value: logEntry,\n },\n ],\n })\n );\n }\n\n async onRunUpdate(run: Run): Promise<void> {\n try {\n const runName = this.keyMapByRunId[run.id];\n if (runName === undefined) {\n return;\n }\n const ops: JSONPatchOperation[] = [];\n if (this._schemaFormat === \"streaming_events\") {\n ops.push({\n op: \"replace\",\n path: `/logs/${runName}/inputs`,\n value: await _getStandardizedInputs(run, this._schemaFormat),\n });\n }\n ops.push({\n op: \"add\",\n path: `/logs/${runName}/final_output`,\n value: await _getStandardizedOutputs(run, this._schemaFormat),\n });\n if (run.end_time !== undefined) {\n ops.push({\n op: \"add\",\n path: `/logs/${runName}/end_time`,\n value: new Date(run.end_time).toISOString(),\n });\n }\n const patch = new RunLogPatch({ ops });\n await this.writer.write(patch);\n } finally {\n if (run.id === this.rootId) {\n const patch = new RunLogPatch({\n ops: [\n {\n op: \"replace\",\n path: \"/final_output\",\n value: await _getStandardizedOutputs(run, this._schemaFormat),\n },\n ],\n });\n await this.writer.write(patch);\n if (this.autoClose) {\n await this.writer.close();\n }\n }\n }\n }\n\n async onLLMNewToken(\n run: Run,\n token: string,\n kwargs?: HandleLLMNewTokenCallbackFields\n ): Promise<void> {\n const runName = this.keyMapByRunId[run.id];\n if (runName === undefined) {\n return;\n }\n // TODO: Remove hack\n const isChatModel = run.inputs.messages !== undefined;\n let streamedOutputValue;\n if (isChatModel) {\n if (isChatGenerationChunk(kwargs?.chunk)) {\n streamedOutputValue = kwargs?.chunk;\n } else {\n streamedOutputValue = new AIMessageChunk({\n id: `run-${run.id}`,\n content: token,\n });\n }\n } else {\n streamedOutputValue = token;\n }\n const patch = new RunLogPatch({\n ops: [\n {\n op: \"add\",\n path: `/logs/${runName}/streamed_output_str/-`,\n value: token,\n },\n {\n op: \"add\",\n path: `/logs/${runName}/streamed_output/-`,\n value: streamedOutputValue,\n },\n ],\n });\n await this.writer.write(patch);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA8EA,IAAa,cAAb,MAAyB;CACvB;CAEA,YAAYA,QAAwC;EAClD,KAAK,MAAM,OAAO,OAAO,CAAE;CAC5B;CAED,OAAOC,OAAoB;EACzB,MAAM,MAAM,KAAK,IAAI,OAAO,MAAM,IAAI;EACtC,MAAM,SAAS,WAAW,CAAE,GAAE,IAAI;AAElC,SAAO,IAAI,OAAO;GAChB;G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AK,KAAK,cAAc;IAC9D,CACF,EACF;IACD,MAAM,KAAK,OAAO,MAAM,MAAM;AAC9B,QAAI,KAAK,WACP,MAAM,KAAK,OAAO,OAAO;GAE5B;EACF;CACF;CAED,MAAM,cACJR,KACAS,OACAC,QACe;EACf,MAAM,UAAU,KAAK,cAAc,IAAI;AACvC,MAAI,YAAY,OACd;EAGF,MAAM,cAAc,IAAI,OAAO,aAAa;EAC5C,IAAI;AACJ,MAAI,YACF,KAAI,sBAAsB,QAAQ,MAAM,EACtC,sBAAsB,QAAQ;OAE9B,sBAAsB,IAAI,eAAe;GACvC,IAAI,CAAC,IAAI,EAAE,IAAI,IAAI;GACnB,SAAS;EACV;OAGH,sBAAsB;EAExB,MAAM,QAAQ,IAAI,YAAY,EAC5B,KAAK,CACH;GACE,IAAI;GACJ,MAAM,CAAC,MAAM,EAAE,QAAQ,sBAAsB,CAAC;GAC9C,OAAO;EACR,GACD;GACE,IAAI;GACJ,MAAM,CAAC,MAAM,EAAE,QAAQ,kBAAkB,CAAC;GAC1C,OAAO;EACR,CACF,EACF;EACD,MAAM,KAAK,OAAO,MAAM,MAAM;CAC/B;AACF"}
@@ -16,21 +16,14 @@ 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
- }
26
19
  const objOps = {
27
20
  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
+ if (key === "__proto__" || key === "constructor") throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");
29
22
  obj[key] = this.value;
30
23
  return { newDocument: document };
31
24
  },
32
25
  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");
26
+ if (key === "__proto__" || key === "constructor") throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");
34
27
  var removed = obj[key];
35
28
  delete obj[key];
36
29
  return {
@@ -39,7 +32,7 @@ const objOps = {
39
32
  };
40
33
  },
41
34
  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");
35
+ if (key === "__proto__" || key === "constructor") throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");
43
36
  var removed = obj[key];
44
37
  obj[key] = this.value;
45
38
  return {
@@ -1 +1 @@
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,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,UAAUD,2BAAW,QAAQ;EAG/B,MAAM,gBAAgB,eAAe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,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","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 if (key === \"__proto__\" || key === \"constructor\") {\n throw new TypeError(\n \"JSON-Patch: modifying `__proto__` or `constructor` 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 (key === \"__proto__\" || key === \"constructor\") {\n throw new TypeError(\n \"JSON-Patch: modifying `__proto__` or `constructor` 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 (key === \"__proto__\" || key === \"constructor\") {\n throw new TypeError(\n \"JSON-Patch: modifying `__proto__` or `constructor` 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;AA2EzB,MAAM,SAAS;CACb,KAAK,SAAU,KAAK,KAAK,UAAU;AACjC,MAAI,QAAQ,eAAe,QAAQ,cACjC,OAAM,IAAI,UACR;EAGJ,IAAI,OAAO,KAAK;AAChB,SAAO,EAAE,aAAa,SAAU;CACjC;CACD,QAAQ,SAAU,KAAK,KAAK,UAAU;AACpC,MAAI,QAAQ,eAAe,QAAQ,cACjC,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,QAAQ,eAAe,QAAQ,cACjC,OAAM,IAAI,UACR;EAGJ,IAAI,UAAU,IAAI;EAClB,IAAI,OAAO,KAAK;AAChB,SAAO;GAAE,aAAa;GAAU;EAAS;CAC1C;CACD,MAAM,SAAU,KAAK,KAAK,UAAU;EAI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S,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,21 +16,14 @@ __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
- }
26
19
  const objOps = {
27
20
  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
+ if (key === "__proto__" || key === "constructor") throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");
29
22
  obj[key] = this.value;
30
23
  return { newDocument: document };
31
24
  },
32
25
  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");
26
+ if (key === "__proto__" || key === "constructor") throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");
34
27
  var removed = obj[key];
35
28
  delete obj[key];
36
29
  return {
@@ -39,7 +32,7 @@ const objOps = {
39
32
  };
40
33
  },
41
34
  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");
35
+ if (key === "__proto__" || key === "constructor") throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");
43
36
  var removed = obj[key];
44
37
  obj[key] = this.value;
45
38
  return {
@@ -1 +1 @@
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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,GAAG,UAAU,OAAU;EAEzD;CACF,SAAQ,GAAG;AACV,MAAI,aAAa,eACf,QAAO;MAEP,OAAM;CAET;AACF;AAwBD,SAAgB,WAAWC,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.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 if (key === \"__proto__\" || key === \"constructor\") {\n throw new TypeError(\n \"JSON-Patch: modifying `__proto__` or `constructor` 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 (key === \"__proto__\" || key === \"constructor\") {\n throw new TypeError(\n \"JSON-Patch: modifying `__proto__` or `constructor` 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 (key === \"__proto__\" || key === \"constructor\") {\n throw new TypeError(\n \"JSON-Patch: modifying `__proto__` or `constructor` 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;AA2EzB,MAAM,SAAS;CACb,KAAK,SAAU,KAAK,KAAK,UAAU;AACjC,MAAI,QAAQ,eAAe,QAAQ,cACjC,OAAM,IAAI,UACR;EAGJ,IAAI,OAAO,KAAK;AAChB,SAAO,EAAE,aAAa,SAAU;CACjC;CACD,QAAQ,SAAU,KAAK,KAAK,UAAU;AACpC,MAAI,QAAQ,eAAe,QAAQ,cACjC,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,QAAQ,eAAe,QAAQ,cACjC,OAAM,IAAI,UACR;EAGJ,IAAI,UAAU,IAAI;EAClB,IAAI,OAAO,KAAK;AAChB,SAAO;GAAE,aAAa;GA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