🎩 You're Invited:Meet the Socket team at Black Hat in Las Vegas, August 3-6.RSVP
Sign In

@langchain/langgraph-checkpoint

Package Overview
Dependencies
Maintainers
12
Versions
32
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@langchain/langgraph-checkpoint - npm Package Compare versions

Comparing version
1.0.0
to
1.0.1
+4
-5
dist/base.cjs

@@ -1,5 +0,4 @@

const require_id = require('./id.cjs');
const require_types = require('./serde/types.cjs');
const require_jsonplus = require('./serde/jsonplus.cjs');
const require_id = require("./id.cjs");
const require_types = require("./serde/types.cjs");
const require_jsonplus = require("./serde/jsonplus.cjs");
//#region src/base.ts

@@ -80,3 +79,2 @@ function deepCopy(obj) {

}
//#endregion

@@ -91,2 +89,3 @@ exports.BaseCheckpointSaver = BaseCheckpointSaver;

exports.maxChannelVersion = maxChannelVersion;
//# sourceMappingURL=base.cjs.map

@@ -1,1 +0,1 @@

{"version":3,"file":"base.cjs","names":["uuid6","JsonPlusSerializer","WRITES_IDX_MAP: Record<string, number>","ERROR","SCHEDULED","INTERRUPT","RESUME"],"sources":["../src/base.ts"],"sourcesContent":["import type { RunnableConfig } from \"@langchain/core/runnables\";\nimport { SerializerProtocol } from \"./serde/base.js\";\nimport { uuid6 } from \"./id.js\";\nimport type {\n PendingWrite,\n CheckpointPendingWrite,\n CheckpointMetadata,\n} from \"./types.js\";\nimport { ERROR, INTERRUPT, RESUME, SCHEDULED } from \"./serde/types.js\";\nimport { JsonPlusSerializer } from \"./serde/jsonplus.js\";\n\n/** @inline */\ntype ChannelVersion = number | string;\n\nexport type ChannelVersions = Record<string, ChannelVersion>;\n\nexport interface Checkpoint<\n N extends string = string,\n C extends string = string\n> {\n /**\n * The version of the checkpoint format. Currently 4\n */\n v: number;\n /**\n * Checkpoint ID {uuid6}\n */\n id: string;\n /**\n * Timestamp {new Date().toISOString()}\n */\n ts: string;\n /**\n * @default {}\n */\n channel_values: Record<C, unknown>;\n /**\n * @default {}\n */\n channel_versions: Record<C, ChannelVersion>;\n /**\n * @default {}\n */\n versions_seen: Record<N, Record<C, ChannelVersion>>;\n}\n\nexport interface ReadonlyCheckpoint extends Readonly<Checkpoint> {\n readonly channel_values: Readonly<Record<string, unknown>>;\n readonly channel_versions: Readonly<Record<string, ChannelVersion>>;\n readonly versions_seen: Readonly<\n Record<string, Readonly<Record<string, ChannelVersion>>>\n >;\n}\n\nexport function deepCopy<T>(obj: T): T {\n if (typeof obj !== \"object\" || obj === null) {\n return obj;\n }\n\n const newObj = Array.isArray(obj) ? [] : {};\n\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n (newObj as Record<PropertyKey, unknown>)[key] = deepCopy(\n (obj as Record<string, unknown>)[key]\n );\n }\n }\n\n return newObj as T;\n}\n\n/** @hidden */\nexport function emptyCheckpoint(): Checkpoint {\n return {\n v: 4,\n id: uuid6(-2),\n ts: new Date().toISOString(),\n channel_values: {},\n channel_versions: {},\n versions_seen: {},\n };\n}\n\n/** @hidden */\nexport function copyCheckpoint(checkpoint: ReadonlyCheckpoint): Checkpoint {\n return {\n v: checkpoint.v,\n id: checkpoint.id,\n ts: checkpoint.ts,\n channel_values: { ...checkpoint.channel_values },\n channel_versions: { ...checkpoint.channel_versions },\n versions_seen: deepCopy(checkpoint.versions_seen),\n };\n}\n\nexport interface CheckpointTuple {\n config: RunnableConfig;\n checkpoint: Checkpoint;\n metadata?: CheckpointMetadata;\n parentConfig?: RunnableConfig;\n pendingWrites?: CheckpointPendingWrite[];\n}\n\nexport type CheckpointListOptions = {\n limit?: number;\n before?: RunnableConfig;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n filter?: Record<string, any>;\n};\n\nexport abstract class BaseCheckpointSaver<V extends string | number = number> {\n serde: SerializerProtocol = new JsonPlusSerializer();\n\n constructor(serde?: SerializerProtocol) {\n this.serde = serde || this.serde;\n }\n\n async get(config: RunnableConfig): Promise<Checkpoint | undefined> {\n const value = await this.getTuple(config);\n return value ? value.checkpoint : undefined;\n }\n\n abstract getTuple(\n config: RunnableConfig\n ): Promise<CheckpointTuple | undefined>;\n\n abstract list(\n config: RunnableConfig,\n options?: CheckpointListOptions\n ): AsyncGenerator<CheckpointTuple>;\n\n abstract put(\n config: RunnableConfig,\n checkpoint: Checkpoint,\n metadata: CheckpointMetadata,\n newVersions: ChannelVersions\n ): Promise<RunnableConfig>;\n\n /**\n * Store intermediate writes linked to a checkpoint.\n */\n abstract putWrites(\n config: RunnableConfig,\n writes: PendingWrite[],\n taskId: string\n ): Promise<void>;\n\n /**\n * Delete all checkpoints and writes associated with a specific thread ID.\n * @param threadId The thread ID whose checkpoints should be deleted.\n */\n abstract deleteThread(threadId: string): Promise<void>;\n\n /**\n * Generate the next version ID for a channel.\n *\n * Default is to use integer versions, incrementing by 1. If you override, you can use str/int/float versions,\n * as long as they are monotonically increasing.\n */\n getNextVersion(current: V | undefined): V {\n if (typeof current === \"string\") {\n throw new Error(\"Please override this method to use string versions.\");\n }\n return (\n current !== undefined && typeof current === \"number\" ? current + 1 : 1\n ) as V;\n }\n}\n\nexport function compareChannelVersions(\n a: ChannelVersion,\n b: ChannelVersion\n): number {\n if (typeof a === \"number\" && typeof b === \"number\") {\n return Math.sign(a - b);\n }\n\n return String(a).localeCompare(String(b));\n}\n\nexport function maxChannelVersion(\n ...versions: ChannelVersion[]\n): ChannelVersion {\n return versions.reduce((max, version, idx) => {\n if (idx === 0) return version;\n return compareChannelVersions(max, version) >= 0 ? max : version;\n });\n}\n\n/**\n * Mapping from error type to error index.\n * Regular writes just map to their index in the list of writes being saved.\n * Special writes (e.g. errors) map to negative indices, to avoid those writes from\n * conflicting with regular writes.\n * Each Checkpointer implementation should use this mapping in put_writes.\n */\nexport const WRITES_IDX_MAP: Record<string, number> = {\n [ERROR]: -1,\n [SCHEDULED]: -2,\n [INTERRUPT]: -3,\n [RESUME]: -4,\n};\n\nexport function getCheckpointId(config: RunnableConfig): string {\n return (\n config.configurable?.checkpoint_id || config.configurable?.thread_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D,MAAaC,iBAAyC;EACnDC,sBAAQ;EACRC,0BAAY;EACZC,0BAAY;EACZC,uBAAS;;AAGZ,SAAgB,gBAAgB,QAAgC;AAC9D,QACE,OAAO,cAAc,iBAAiB,OAAO,cAAc,aAAa"}
{"version":3,"file":"base.cjs","names":["uuid6","JsonPlusSerializer","ERROR","SCHEDULED","INTERRUPT","RESUME"],"sources":["../src/base.ts"],"sourcesContent":["import type { RunnableConfig } from \"@langchain/core/runnables\";\nimport { SerializerProtocol } from \"./serde/base.js\";\nimport { uuid6 } from \"./id.js\";\nimport type {\n PendingWrite,\n CheckpointPendingWrite,\n CheckpointMetadata,\n} from \"./types.js\";\nimport { ERROR, INTERRUPT, RESUME, SCHEDULED } from \"./serde/types.js\";\nimport { JsonPlusSerializer } from \"./serde/jsonplus.js\";\n\n/** @inline */\ntype ChannelVersion = number | string;\n\nexport type ChannelVersions = Record<string, ChannelVersion>;\n\nexport interface Checkpoint<\n N extends string = string,\n C extends string = string\n> {\n /**\n * The version of the checkpoint format. Currently 4\n */\n v: number;\n /**\n * Checkpoint ID {uuid6}\n */\n id: string;\n /**\n * Timestamp {new Date().toISOString()}\n */\n ts: string;\n /**\n * @default {}\n */\n channel_values: Record<C, unknown>;\n /**\n * @default {}\n */\n channel_versions: Record<C, ChannelVersion>;\n /**\n * @default {}\n */\n versions_seen: Record<N, Record<C, ChannelVersion>>;\n}\n\nexport interface ReadonlyCheckpoint extends Readonly<Checkpoint> {\n readonly channel_values: Readonly<Record<string, unknown>>;\n readonly channel_versions: Readonly<Record<string, ChannelVersion>>;\n readonly versions_seen: Readonly<\n Record<string, Readonly<Record<string, ChannelVersion>>>\n >;\n}\n\nexport function deepCopy<T>(obj: T): T {\n if (typeof obj !== \"object\" || obj === null) {\n return obj;\n }\n\n const newObj = Array.isArray(obj) ? [] : {};\n\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n (newObj as Record<PropertyKey, unknown>)[key] = deepCopy(\n (obj as Record<string, unknown>)[key]\n );\n }\n }\n\n return newObj as T;\n}\n\n/** @hidden */\nexport function emptyCheckpoint(): Checkpoint {\n return {\n v: 4,\n id: uuid6(-2),\n ts: new Date().toISOString(),\n channel_values: {},\n channel_versions: {},\n versions_seen: {},\n };\n}\n\n/** @hidden */\nexport function copyCheckpoint(checkpoint: ReadonlyCheckpoint): Checkpoint {\n return {\n v: checkpoint.v,\n id: checkpoint.id,\n ts: checkpoint.ts,\n channel_values: { ...checkpoint.channel_values },\n channel_versions: { ...checkpoint.channel_versions },\n versions_seen: deepCopy(checkpoint.versions_seen),\n };\n}\n\nexport interface CheckpointTuple {\n config: RunnableConfig;\n checkpoint: Checkpoint;\n metadata?: CheckpointMetadata;\n parentConfig?: RunnableConfig;\n pendingWrites?: CheckpointPendingWrite[];\n}\n\nexport type CheckpointListOptions = {\n limit?: number;\n before?: RunnableConfig;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n filter?: Record<string, any>;\n};\n\nexport abstract class BaseCheckpointSaver<V extends string | number = number> {\n serde: SerializerProtocol = new JsonPlusSerializer();\n\n constructor(serde?: SerializerProtocol) {\n this.serde = serde || this.serde;\n }\n\n async get(config: RunnableConfig): Promise<Checkpoint | undefined> {\n const value = await this.getTuple(config);\n return value ? value.checkpoint : undefined;\n }\n\n abstract getTuple(\n config: RunnableConfig\n ): Promise<CheckpointTuple | undefined>;\n\n abstract list(\n config: RunnableConfig,\n options?: CheckpointListOptions\n ): AsyncGenerator<CheckpointTuple>;\n\n abstract put(\n config: RunnableConfig,\n checkpoint: Checkpoint,\n metadata: CheckpointMetadata,\n newVersions: ChannelVersions\n ): Promise<RunnableConfig>;\n\n /**\n * Store intermediate writes linked to a checkpoint.\n */\n abstract putWrites(\n config: RunnableConfig,\n writes: PendingWrite[],\n taskId: string\n ): Promise<void>;\n\n /**\n * Delete all checkpoints and writes associated with a specific thread ID.\n * @param threadId The thread ID whose checkpoints should be deleted.\n */\n abstract deleteThread(threadId: string): Promise<void>;\n\n /**\n * Generate the next version ID for a channel.\n *\n * Default is to use integer versions, incrementing by 1. If you override, you can use str/int/float versions,\n * as long as they are monotonically increasing.\n */\n getNextVersion(current: V | undefined): V {\n if (typeof current === \"string\") {\n throw new Error(\"Please override this method to use string versions.\");\n }\n return (\n current !== undefined && typeof current === \"number\" ? current + 1 : 1\n ) as V;\n }\n}\n\nexport function compareChannelVersions(\n a: ChannelVersion,\n b: ChannelVersion\n): number {\n if (typeof a === \"number\" && typeof b === \"number\") {\n return Math.sign(a - b);\n }\n\n return String(a).localeCompare(String(b));\n}\n\nexport function maxChannelVersion(\n ...versions: ChannelVersion[]\n): ChannelVersion {\n return versions.reduce((max, version, idx) => {\n if (idx === 0) return version;\n return compareChannelVersions(max, version) >= 0 ? max : version;\n });\n}\n\n/**\n * Mapping from error type to error index.\n * Regular writes just map to their index in the list of writes being saved.\n * Special writes (e.g. errors) map to negative indices, to avoid those writes from\n * conflicting with regular writes.\n * Each Checkpointer implementation should use this mapping in put_writes.\n */\nexport const WRITES_IDX_MAP: Record<string, number> = {\n [ERROR]: -1,\n [SCHEDULED]: -2,\n [INTERRUPT]: -3,\n [RESUME]: -4,\n};\n\nexport function getCheckpointId(config: RunnableConfig): string {\n return (\n config.configurable?.checkpoint_id || config.configurable?.thread_ts || \"\"\n );\n}\n"],"mappings":";;;;AAsDA,SAAgB,SAAY,KAAW;AACrC,KAAI,OAAO,QAAQ,YAAY,QAAQ,KACrC,QAAO;CAGT,MAAM,SAAS,MAAM,QAAQ,IAAI,GAAG,EAAE,GAAG,EAAE;AAE3C,MAAK,MAAM,OAAO,IAChB,KAAI,OAAO,UAAU,eAAe,KAAK,KAAK,IAAI,CAC/C,QAAwC,OAAO,SAC7C,IAAgC,KAClC;AAIL,QAAO;;;AAIT,SAAgB,kBAA8B;AAC5C,QAAO;EACL,GAAG;EACH,IAAIA,WAAAA,MAAM,GAAG;EACb,qBAAI,IAAI,MAAM,EAAC,aAAa;EAC5B,gBAAgB,EAAE;EAClB,kBAAkB,EAAE;EACpB,eAAe,EAAE;EAClB;;;AAIH,SAAgB,eAAe,YAA4C;AACzE,QAAO;EACL,GAAG,WAAW;EACd,IAAI,WAAW;EACf,IAAI,WAAW;EACf,gBAAgB,EAAE,GAAG,WAAW,gBAAgB;EAChD,kBAAkB,EAAE,GAAG,WAAW,kBAAkB;EACpD,eAAe,SAAS,WAAW,cAAc;EAClD;;AAkBH,IAAsB,sBAAtB,MAA8E;CAC5E,QAA4B,IAAIC,iBAAAA,oBAAoB;CAEpD,YAAY,OAA4B;AACtC,OAAK,QAAQ,SAAS,KAAK;;CAG7B,MAAM,IAAI,QAAyD;EACjE,MAAM,QAAQ,MAAM,KAAK,SAAS,OAAO;AACzC,SAAO,QAAQ,MAAM,aAAa,KAAA;;;;;;;;CAwCpC,eAAe,SAA2B;AACxC,MAAI,OAAO,YAAY,SACrB,OAAM,IAAI,MAAM,sDAAsD;AAExE,SACE,YAAY,KAAA,KAAa,OAAO,YAAY,WAAW,UAAU,IAAI;;;AAK3E,SAAgB,uBACd,GACA,GACQ;AACR,KAAI,OAAO,MAAM,YAAY,OAAO,MAAM,SACxC,QAAO,KAAK,KAAK,IAAI,EAAE;AAGzB,QAAO,OAAO,EAAE,CAAC,cAAc,OAAO,EAAE,CAAC;;AAG3C,SAAgB,kBACd,GAAG,UACa;AAChB,QAAO,SAAS,QAAQ,KAAK,SAAS,QAAQ;AAC5C,MAAI,QAAQ,EAAG,QAAO;AACtB,SAAO,uBAAuB,KAAK,QAAQ,IAAI,IAAI,MAAM;GACzD;;;;;;;;;AAUJ,MAAa,iBAAyC;EACnDC,cAAAA,QAAQ;EACRC,cAAAA,YAAY;EACZC,cAAAA,YAAY;EACZC,cAAAA,SAAS;CACX;AAED,SAAgB,gBAAgB,QAAgC;AAC9D,QACE,OAAO,cAAc,iBAAiB,OAAO,cAAc,aAAa"}

@@ -55,3 +55,2 @@ import { SerializerProtocol } from "./serde/base.cjs";

before?: RunnableConfig;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
filter?: Record<string, any>;

@@ -58,0 +57,0 @@ };

@@ -1,1 +0,1 @@

{"version":3,"file":"base.d.cts","names":["RunnableConfig","SerializerProtocol","PendingWrite","CheckpointPendingWrite","CheckpointMetadata","ChannelVersion","ChannelVersions","Record","Checkpoint","C","N","ReadonlyCheckpoint","Readonly","deepCopy","T","emptyCheckpoint","copyCheckpoint","CheckpointTuple","CheckpointListOptions","BaseCheckpointSaver","Promise","AsyncGenerator","V","compareChannelVersions","maxChannelVersion","WRITES_IDX_MAP","getCheckpointId"],"sources":["../src/base.d.ts"],"sourcesContent":["import type { RunnableConfig } from \"@langchain/core/runnables\";\nimport { SerializerProtocol } from \"./serde/base.js\";\nimport type { PendingWrite, CheckpointPendingWrite, CheckpointMetadata } from \"./types.js\";\n/** @inline */\ntype ChannelVersion = number | string;\nexport type ChannelVersions = Record<string, ChannelVersion>;\nexport interface Checkpoint<N extends string = string, C extends string = string> {\n /**\n * The version of the checkpoint format. Currently 4\n */\n v: number;\n /**\n * Checkpoint ID {uuid6}\n */\n id: string;\n /**\n * Timestamp {new Date().toISOString()}\n */\n ts: string;\n /**\n * @default {}\n */\n channel_values: Record<C, unknown>;\n /**\n * @default {}\n */\n channel_versions: Record<C, ChannelVersion>;\n /**\n * @default {}\n */\n versions_seen: Record<N, Record<C, ChannelVersion>>;\n}\nexport interface ReadonlyCheckpoint extends Readonly<Checkpoint> {\n readonly channel_values: Readonly<Record<string, unknown>>;\n readonly channel_versions: Readonly<Record<string, ChannelVersion>>;\n readonly versions_seen: Readonly<Record<string, Readonly<Record<string, ChannelVersion>>>>;\n}\nexport declare function deepCopy<T>(obj: T): T;\n/** @hidden */\nexport declare function emptyCheckpoint(): Checkpoint;\n/** @hidden */\nexport declare function copyCheckpoint(checkpoint: ReadonlyCheckpoint): Checkpoint;\nexport interface CheckpointTuple {\n config: RunnableConfig;\n checkpoint: Checkpoint;\n metadata?: CheckpointMetadata;\n parentConfig?: RunnableConfig;\n pendingWrites?: CheckpointPendingWrite[];\n}\nexport type CheckpointListOptions = {\n limit?: number;\n before?: RunnableConfig;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n filter?: Record<string, any>;\n};\nexport declare abstract class BaseCheckpointSaver<V extends string | number = number> {\n serde: SerializerProtocol;\n constructor(serde?: SerializerProtocol);\n get(config: RunnableConfig): Promise<Checkpoint | undefined>;\n abstract getTuple(config: RunnableConfig): Promise<CheckpointTuple | undefined>;\n abstract list(config: RunnableConfig, options?: CheckpointListOptions): AsyncGenerator<CheckpointTuple>;\n abstract put(config: RunnableConfig, checkpoint: Checkpoint, metadata: CheckpointMetadata, newVersions: ChannelVersions): Promise<RunnableConfig>;\n /**\n * Store intermediate writes linked to a checkpoint.\n */\n abstract putWrites(config: RunnableConfig, writes: PendingWrite[], taskId: string): Promise<void>;\n /**\n * Delete all checkpoints and writes associated with a specific thread ID.\n * @param threadId The thread ID whose checkpoints should be deleted.\n */\n abstract deleteThread(threadId: string): Promise<void>;\n /**\n * Generate the next version ID for a channel.\n *\n * Default is to use integer versions, incrementing by 1. If you override, you can use str/int/float versions,\n * as long as they are monotonically increasing.\n */\n getNextVersion(current: V | undefined): V;\n}\nexport declare function compareChannelVersions(a: ChannelVersion, b: ChannelVersion): number;\nexport declare function maxChannelVersion(...versions: ChannelVersion[]): ChannelVersion;\n/**\n * Mapping from error type to error index.\n * Regular writes just map to their index in the list of writes being saved.\n * Special writes (e.g. errors) map to negative indices, to avoid those writes from\n * conflicting with regular writes.\n * Each Checkpointer implementation should use this mapping in put_writes.\n */\nexport declare const WRITES_IDX_MAP: Record<string, number>;\nexport declare function getCheckpointId(config: RunnableConfig): string;\nexport {};\n"],"mappings":";;;;;;KAIKK,cAAAA;AAAAA,KACOC,eAAAA,GAAkBC,MADX,CAAA,MAAA,EAC0BF,cAD1B,CAAA;AACPC,UACKE,UADU,CAAA,UAAA,MAAA,GAAA,MAAA,EAAA,UAAA,MAAA,GAAA,MAAA,CAAA,CAAA;EAAA;;;;EACVA;;;MAgBG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P,MAAA,EAAQ,cAAA,GACP,OAAA,CAAQ,eAAA;EAAA,SAEF,IAAA,CACP,MAAA,EAAQ,cAAA,EACR,OAAA,GAAU,qBAAA,GACT,cAAA,CAAe,eAAA;EAAA,SAET,GAAA,CACP,MAAA,EAAQ,cAAA,EACR,UAAA,EAAY,UAAA,EACZ,QAAA,EAAU,kBAAA,EACV,WAAA,EAAa,eAAA,GACZ,OAAA,CAAQ,cAAA;EAvFM;;;EAAA,SA4FR,SAAA,CACP,MAAA,EAAQ,cAAA,EACR,MAAA,EAAQ,YAAA,IACR,MAAA,WACC,OAAA;EApG+C;;;;EAAA,SA0GzC,YAAA,CAAa,QAAA,WAAmB,OAAA;EAzGhB;;;;;;EAiHzB,cAAA,CAAe,OAAA,EAAS,CAAA,eAAgB,CAAA;AAAA;AAAA,iBAU1B,sBAAA,CACd,CAAA,EAAG,cAAA,EACH,CAAA,EAAG,cAAA;AAAA,iBASW,iBAAA,CAAA,GACX,QAAA,EAAU,cAAA,KACZ,cAAA;;;;;AAjIH;;;cA+Ia,cAAA,EAAgB,MAAA;AAAA,iBAOb,eAAA,CAAgB,MAAA,EAAQ,cAAA"}

@@ -55,3 +55,2 @@ import { SerializerProtocol } from "./serde/base.js";

before?: RunnableConfig;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
filter?: Record<string, any>;

@@ -58,0 +57,0 @@ };

@@ -1,1 +0,1 @@

{"version":3,"file":"base.d.ts","names":["RunnableConfig","SerializerProtocol","PendingWrite","CheckpointPendingWrite","CheckpointMetadata","ChannelVersion","ChannelVersions","Record","Checkpoint","C","N","ReadonlyCheckpoint","Readonly","deepCopy","T","emptyCheckpoint","copyCheckpoint","CheckpointTuple","CheckpointListOptions","BaseCheckpointSaver","Promise","AsyncGenerator","V","compareChannelVersions","maxChannelVersion","WRITES_IDX_MAP","getCheckpointId"],"sources":["../src/base.d.ts"],"sourcesContent":["import type { RunnableConfig } from \"@langchain/core/runnables\";\nimport { SerializerProtocol } from \"./serde/base.js\";\nimport type { PendingWrite, CheckpointPendingWrite, CheckpointMetadata } from \"./types.js\";\n/** @inline */\ntype ChannelVersion = number | string;\nexport type ChannelVersions = Record<string, ChannelVersion>;\nexport interface Checkpoint<N extends string = string, C extends string = string> {\n /**\n * The version of the checkpoint format. Currently 4\n */\n v: number;\n /**\n * Checkpoint ID {uuid6}\n */\n id: string;\n /**\n * Timestamp {new Date().toISOString()}\n */\n ts: string;\n /**\n * @default {}\n */\n channel_values: Record<C, unknown>;\n /**\n * @default {}\n */\n channel_versions: Record<C, ChannelVersion>;\n /**\n * @default {}\n */\n versions_seen: Record<N, Record<C, ChannelVersion>>;\n}\nexport interface ReadonlyCheckpoint extends Readonly<Checkpoint> {\n readonly channel_values: Readonly<Record<string, unknown>>;\n readonly channel_versions: Readonly<Record<string, ChannelVersion>>;\n readonly versions_seen: Readonly<Record<string, Readonly<Record<string, ChannelVersion>>>>;\n}\nexport declare function deepCopy<T>(obj: T): T;\n/** @hidden */\nexport declare function emptyCheckpoint(): Checkpoint;\n/** @hidden */\nexport declare function copyCheckpoint(checkpoint: ReadonlyCheckpoint): Checkpoint;\nexport interface CheckpointTuple {\n config: RunnableConfig;\n checkpoint: Checkpoint;\n metadata?: CheckpointMetadata;\n parentConfig?: RunnableConfig;\n pendingWrites?: CheckpointPendingWrite[];\n}\nexport type CheckpointListOptions = {\n limit?: number;\n before?: RunnableConfig;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n filter?: Record<string, any>;\n};\nexport declare abstract class BaseCheckpointSaver<V extends string | number = number> {\n serde: SerializerProtocol;\n constructor(serde?: SerializerProtocol);\n get(config: RunnableConfig): Promise<Checkpoint | undefined>;\n abstract getTuple(config: RunnableConfig): Promise<CheckpointTuple | undefined>;\n abstract list(config: RunnableConfig, options?: CheckpointListOptions): AsyncGenerator<CheckpointTuple>;\n abstract put(config: RunnableConfig, checkpoint: Checkpoint, metadata: CheckpointMetadata, newVersions: ChannelVersions): Promise<RunnableConfig>;\n /**\n * Store intermediate writes linked to a checkpoint.\n */\n abstract putWrites(config: RunnableConfig, writes: PendingWrite[], taskId: string): Promise<void>;\n /**\n * Delete all checkpoints and writes associated with a specific thread ID.\n * @param threadId The thread ID whose checkpoints should be deleted.\n */\n abstract deleteThread(threadId: string): Promise<void>;\n /**\n * Generate the next version ID for a channel.\n *\n * Default is to use integer versions, incrementing by 1. If you override, you can use str/int/float versions,\n * as long as they are monotonically increasing.\n */\n getNextVersion(current: V | undefined): V;\n}\nexport declare function compareChannelVersions(a: ChannelVersion, b: ChannelVersion): number;\nexport declare function maxChannelVersion(...versions: ChannelVersion[]): ChannelVersion;\n/**\n * Mapping from error type to error index.\n * Regular writes just map to their index in the list of writes being saved.\n * Special writes (e.g. errors) map to negative indices, to avoid those writes from\n * conflicting with regular writes.\n * Each Checkpointer implementation should use this mapping in put_writes.\n */\nexport declare const WRITES_IDX_MAP: Record<string, number>;\nexport declare function getCheckpointId(config: RunnableConfig): string;\nexport {};\n"],"mappings":";;;;;;KAIKK,cAAAA;AAAAA,KACOC,eAAAA,GAAkBC,MADX,CAAA,MAAA,EAC0BF,cAD1B,CAAA;AACPC,UACKE,UADU,CAAA,UAAA,MAAA,GAAA,MAAA,EAAA,UAAA,MAAA,GAAA,MAAA,CAAA,CAAA;EAAA;;;;EACVA;;;MAgBGD,MAAAA;;;;MAQMG,MAAAA;;;;gBAAPH,EARCA,MAQDA,CARQE,CAQRF,EAAAA,OAAAA,CAAAA;;AAEnB;;kBAAqDC,EAN/BD,MAM+BC,CANxBC,CAMwBD,EANrBH,cAMqBG,CAAAA;;;;eAEbD,EAJrBA,MAIqBA,CAJdG,CAIcH,EAJXA,MAIWA,CAJJE,CAIIF,EAJDF,cAICE,CAAAA,CAAAA;;AACoCF,UAH3DM,kBAAAA,SAA2BC,QAGgCP,CAHvBG,UAGuBH,CAAAA,CAAAA;WAAfE,cAAAA,EAFhCK,QAEgCL,CAFvBA,MAEuBA,CAAAA,MAAAA,EAAAA,OAAAA,CAAAA,CAAAA;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;EAzGhB;;;;;;EAiHzB,cAAA,CAAe,OAAA,EAAS,CAAA,eAAgB,CAAA;AAAA;AAAA,iBAU1B,sBAAA,CACd,CAAA,EAAG,cAAA,EACH,CAAA,EAAG,cAAA;AAAA,iBASW,iBAAA,CAAA,GACX,QAAA,EAAU,cAAA,KACZ,cAAA;;;;;AAjIH;;;cA+Ia,cAAA,EAAgB,MAAA;AAAA,iBAOb,eAAA,CAAgB,MAAA,EAAQ,cAAA"}
import { uuid6 } from "./id.js";
import { ERROR, INTERRUPT, RESUME, SCHEDULED } from "./serde/types.js";
import { JsonPlusSerializer } from "./serde/jsonplus.js";
//#region src/base.ts

@@ -80,5 +79,5 @@ function deepCopy(obj) {

}
//#endregion
export { BaseCheckpointSaver, WRITES_IDX_MAP, compareChannelVersions, copyCheckpoint, deepCopy, emptyCheckpoint, getCheckpointId, maxChannelVersion };
//# sourceMappingURL=base.js.map

@@ -1,1 +0,1 @@

{"version":3,"file":"base.js","names":["WRITES_IDX_MAP: Record<string, number>"],"sources":["../src/base.ts"],"sourcesContent":["import type { RunnableConfig } from \"@langchain/core/runnables\";\nimport { SerializerProtocol } from \"./serde/base.js\";\nimport { uuid6 } from \"./id.js\";\nimport type {\n PendingWrite,\n CheckpointPendingWrite,\n CheckpointMetadata,\n} from \"./types.js\";\nimport { ERROR, INTERRUPT, RESUME, SCHEDULED } from \"./serde/types.js\";\nimport { JsonPlusSerializer } from \"./serde/jsonplus.js\";\n\n/** @inline */\ntype ChannelVersion = number | string;\n\nexport type ChannelVersions = Record<string, ChannelVersion>;\n\nexport interface Checkpoint<\n N extends string = string,\n C extends string = string\n> {\n /**\n * The version of the checkpoint format. Currently 4\n */\n v: number;\n /**\n * Checkpoint ID {uuid6}\n */\n id: string;\n /**\n * Timestamp {new Date().toISOString()}\n */\n ts: string;\n /**\n * @default {}\n */\n channel_values: Record<C, unknown>;\n /**\n * @default {}\n */\n channel_versions: Record<C, ChannelVersion>;\n /**\n * @default {}\n */\n versions_seen: Record<N, Record<C, ChannelVersion>>;\n}\n\nexport interface ReadonlyCheckpoint extends Readonly<Checkpoint> {\n readonly channel_values: Readonly<Record<string, unknown>>;\n readonly channel_versions: Readonly<Record<string, ChannelVersion>>;\n readonly versions_seen: Readonly<\n Record<string, Readonly<Record<string, ChannelVersion>>>\n >;\n}\n\nexport function deepCopy<T>(obj: T): T {\n if (typeof obj !== \"object\" || obj === null) {\n return obj;\n }\n\n const newObj = Array.isArray(obj) ? [] : {};\n\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n (newObj as Record<PropertyKey, unknown>)[key] = deepCopy(\n (obj as Record<string, unknown>)[key]\n );\n }\n }\n\n return newObj as T;\n}\n\n/** @hidden */\nexport function emptyCheckpoint(): Checkpoint {\n return {\n v: 4,\n id: uuid6(-2),\n ts: new Date().toISOString(),\n channel_values: {},\n channel_versions: {},\n versions_seen: {},\n };\n}\n\n/** @hidden */\nexport function copyCheckpoint(checkpoint: ReadonlyCheckpoint): Checkpoint {\n return {\n v: checkpoint.v,\n id: checkpoint.id,\n ts: checkpoint.ts,\n channel_values: { ...checkpoint.channel_values },\n channel_versions: { ...checkpoint.channel_versions },\n versions_seen: deepCopy(checkpoint.versions_seen),\n };\n}\n\nexport interface CheckpointTuple {\n config: RunnableConfig;\n checkpoint: Checkpoint;\n metadata?: CheckpointMetadata;\n parentConfig?: RunnableConfig;\n pendingWrites?: CheckpointPendingWrite[];\n}\n\nexport type CheckpointListOptions = {\n limit?: number;\n before?: RunnableConfig;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n filter?: Record<string, any>;\n};\n\nexport abstract class BaseCheckpointSaver<V extends string | number = number> {\n serde: SerializerProtocol = new JsonPlusSerializer();\n\n constructor(serde?: SerializerProtocol) {\n this.serde = serde || this.serde;\n }\n\n async get(config: RunnableConfig): Promise<Checkpoint | undefined> {\n const value = await this.getTuple(config);\n return value ? value.checkpoint : undefined;\n }\n\n abstract getTuple(\n config: RunnableConfig\n ): Promise<CheckpointTuple | undefined>;\n\n abstract list(\n config: RunnableConfig,\n options?: CheckpointListOptions\n ): AsyncGenerator<CheckpointTuple>;\n\n abstract put(\n config: RunnableConfig,\n checkpoint: Checkpoint,\n metadata: CheckpointMetadata,\n newVersions: ChannelVersions\n ): Promise<RunnableConfig>;\n\n /**\n * Store intermediate writes linked to a checkpoint.\n */\n abstract putWrites(\n config: RunnableConfig,\n writes: PendingWrite[],\n taskId: string\n ): Promise<void>;\n\n /**\n * Delete all checkpoints and writes associated with a specific thread ID.\n * @param threadId The thread ID whose checkpoints should be deleted.\n */\n abstract deleteThread(threadId: string): Promise<void>;\n\n /**\n * Generate the next version ID for a channel.\n *\n * Default is to use integer versions, incrementing by 1. If you override, you can use str/int/float versions,\n * as long as they are monotonically increasing.\n */\n getNextVersion(current: V | undefined): V {\n if (typeof current === \"string\") {\n throw new Error(\"Please override this method to use string versions.\");\n }\n return (\n current !== undefined && typeof current === \"number\" ? current + 1 : 1\n ) as V;\n }\n}\n\nexport function compareChannelVersions(\n a: ChannelVersion,\n b: ChannelVersion\n): number {\n if (typeof a === \"number\" && typeof b === \"number\") {\n return Math.sign(a - b);\n }\n\n return String(a).localeCompare(String(b));\n}\n\nexport function maxChannelVersion(\n ...versions: ChannelVersion[]\n): ChannelVersion {\n return versions.reduce((max, version, idx) => {\n if (idx === 0) return version;\n return compareChannelVersions(max, version) >= 0 ? max : version;\n });\n}\n\n/**\n * Mapping from error type to error index.\n * Regular writes just map to their index in the list of writes being saved.\n * Special writes (e.g. errors) map to negative indices, to avoid those writes from\n * conflicting with regular writes.\n * Each Checkpointer implementation should use this mapping in put_writes.\n */\nexport const WRITES_IDX_MAP: Record<string, number> = {\n [ERROR]: -1,\n [SCHEDULED]: -2,\n [INTERRUPT]: -3,\n [RESUME]: -4,\n};\n\nexport function getCheckpointId(config: RunnableConfig): string {\n return (\n config.configurable?.checkpoint_id || config.configurable?.thread_ts || \"\"\n );\n}\n"],"mappings":";;;;;AAsDA,SAAgB,SAAY,K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Z,SAAS;;AAGZ,SAAgB,gBAAgB,QAAgC;AAC9D,QACE,OAAO,cAAc,iBAAiB,OAAO,cAAc,aAAa"}
{"version":3,"file":"base.js","names":[],"sources":["../src/base.ts"],"sourcesContent":["import type { RunnableConfig } from \"@langchain/core/runnables\";\nimport { SerializerProtocol } from \"./serde/base.js\";\nimport { uuid6 } from \"./id.js\";\nimport type {\n PendingWrite,\n CheckpointPendingWrite,\n CheckpointMetadata,\n} from \"./types.js\";\nimport { ERROR, INTERRUPT, RESUME, SCHEDULED } from \"./serde/types.js\";\nimport { JsonPlusSerializer } from \"./serde/jsonplus.js\";\n\n/** @inline */\ntype ChannelVersion = number | string;\n\nexport type ChannelVersions = Record<string, ChannelVersion>;\n\nexport interface Checkpoint<\n N extends string = string,\n C extends string = string\n> {\n /**\n * The version of the checkpoint format. Currently 4\n */\n v: number;\n /**\n * Checkpoint ID {uuid6}\n */\n id: string;\n /**\n * Timestamp {new Date().toISOString()}\n */\n ts: string;\n /**\n * @default {}\n */\n channel_values: Record<C, unknown>;\n /**\n * @default {}\n */\n channel_versions: Record<C, ChannelVersion>;\n /**\n * @default {}\n */\n versions_seen: Record<N, Record<C, ChannelVersion>>;\n}\n\nexport interface ReadonlyCheckpoint extends Readonly<Checkpoint> {\n readonly channel_values: Readonly<Record<string, unknown>>;\n readonly channel_versions: Readonly<Record<string, ChannelVersion>>;\n readonly versions_seen: Readonly<\n Record<string, Readonly<Record<string, ChannelVersion>>>\n >;\n}\n\nexport function deepCopy<T>(obj: T): T {\n if (typeof obj !== \"object\" || obj === null) {\n return obj;\n }\n\n const newObj = Array.isArray(obj) ? [] : {};\n\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n (newObj as Record<PropertyKey, unknown>)[key] = deepCopy(\n (obj as Record<string, unknown>)[key]\n );\n }\n }\n\n return newObj as T;\n}\n\n/** @hidden */\nexport function emptyCheckpoint(): Checkpoint {\n return {\n v: 4,\n id: uuid6(-2),\n ts: new Date().toISOString(),\n channel_values: {},\n channel_versions: {},\n versions_seen: {},\n };\n}\n\n/** @hidden */\nexport function copyCheckpoint(checkpoint: ReadonlyCheckpoint): Checkpoint {\n return {\n v: checkpoint.v,\n id: checkpoint.id,\n ts: checkpoint.ts,\n channel_values: { ...checkpoint.channel_values },\n channel_versions: { ...checkpoint.channel_versions },\n versions_seen: deepCopy(checkpoint.versions_seen),\n };\n}\n\nexport interface CheckpointTuple {\n config: RunnableConfig;\n checkpoint: Checkpoint;\n metadata?: CheckpointMetadata;\n parentConfig?: RunnableConfig;\n pendingWrites?: CheckpointPendingWrite[];\n}\n\nexport type CheckpointListOptions = {\n limit?: number;\n before?: RunnableConfig;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n filter?: Record<string, any>;\n};\n\nexport abstract class BaseCheckpointSaver<V extends string | number = number> {\n serde: SerializerProtocol = new JsonPlusSerializer();\n\n constructor(serde?: SerializerProtocol) {\n this.serde = serde || this.serde;\n }\n\n async get(config: RunnableConfig): Promise<Checkpoint | undefined> {\n const value = await this.getTuple(config);\n return value ? value.checkpoint : undefined;\n }\n\n abstract getTuple(\n config: RunnableConfig\n ): Promise<CheckpointTuple | undefined>;\n\n abstract list(\n config: RunnableConfig,\n options?: CheckpointListOptions\n ): AsyncGenerator<CheckpointTuple>;\n\n abstract put(\n config: RunnableConfig,\n checkpoint: Checkpoint,\n metadata: CheckpointMetadata,\n newVersions: ChannelVersions\n ): Promise<RunnableConfig>;\n\n /**\n * Store intermediate writes linked to a checkpoint.\n */\n abstract putWrites(\n config: RunnableConfig,\n writes: PendingWrite[],\n taskId: string\n ): Promise<void>;\n\n /**\n * Delete all checkpoints and writes associated with a specific thread ID.\n * @param threadId The thread ID whose checkpoints should be deleted.\n */\n abstract deleteThread(threadId: string): Promise<void>;\n\n /**\n * Generate the next version ID for a channel.\n *\n * Default is to use integer versions, incrementing by 1. If you override, you can use str/int/float versions,\n * as long as they are monotonically increasing.\n */\n getNextVersion(current: V | undefined): V {\n if (typeof current === \"string\") {\n throw new Error(\"Please override this method to use string versions.\");\n }\n return (\n current !== undefined && typeof current === \"number\" ? current + 1 : 1\n ) as V;\n }\n}\n\nexport function compareChannelVersions(\n a: ChannelVersion,\n b: ChannelVersion\n): number {\n if (typeof a === \"number\" && typeof b === \"number\") {\n return Math.sign(a - b);\n }\n\n return String(a).localeCompare(String(b));\n}\n\nexport function maxChannelVersion(\n ...versions: ChannelVersion[]\n): ChannelVersion {\n return versions.reduce((max, version, idx) => {\n if (idx === 0) return version;\n return compareChannelVersions(max, version) >= 0 ? max : version;\n });\n}\n\n/**\n * Mapping from error type to error index.\n * Regular writes just map to their index in the list of writes being saved.\n * Special writes (e.g. errors) map to negative indices, to avoid those writes from\n * conflicting with regular writes.\n * Each Checkpointer implementation should use this mapping in put_writes.\n */\nexport const WRITES_IDX_MAP: Record<string, number> = {\n [ERROR]: -1,\n [SCHEDULED]: -2,\n [INTERRUPT]: -3,\n [RESUME]: -4,\n};\n\nexport function getCheckpointId(config: RunnableConfig): string {\n return (\n config.configurable?.checkpoint_id || config.configurable?.thread_ts || \"\"\n );\n}\n"],"mappings":";;;;AAsDA,SAAgB,SAAY,KAAW;AACrC,KAAI,OAAO,QAAQ,YAAY,QAAQ,KACrC,QAAO;CAGT,MAAM,SAAS,MAAM,QAAQ,IAAI,GAAG,EAAE,GAAG,EAAE;AAE3C,MAAK,MAAM,OAAO,IAChB,KAAI,OAAO,UAAU,eAAe,KAAK,KAAK,IAAI,CAC/C,QAAwC,OAAO,SAC7C,IAAgC,KAClC;AAIL,QAAO;;;AAIT,SAAgB,kBAA8B;AAC5C,QAAO;EACL,GAAG;EACH,IAAI,MAAM,GAAG;EACb,qBAAI,IAAI,MAAM,EAAC,aAAa;EAC5B,gBAAgB,EAAE;EAClB,kBAAkB,EAAE;EACpB,eAAe,EAAE;EAClB;;;AAIH,SAAgB,eAAe,YAA4C;AACzE,QAAO;EACL,GAAG,WAAW;EACd,IAAI,WAAW;EACf,IAAI,WAAW;EACf,gBAAgB,EAAE,GAAG,WAAW,gBAAgB;EAChD,kBAAkB,EAAE,GAAG,WAAW,kBAAkB;EACpD,eAAe,SAAS,WAAW,cAAc;EAClD;;AAkBH,IAAsB,sBAAtB,MAA8E;CAC5E,QAA4B,IAAI,oBAAoB;CAEpD,YAAY,OAA4B;AACtC,OAAK,QAAQ,SAAS,KAAK;;CAG7B,MAAM,IAAI,QAAyD;EACjE,MAAM,QAAQ,MAAM,KAAK,SAAS,OAAO;AACzC,SAAO,QAAQ,MAAM,aAAa,KAAA;;;;;;;;CAwCpC,eAAe,SAA2B;AACxC,MAAI,OAAO,YAAY,SACrB,OAAM,IAAI,MAAM,sDAAsD;AAExE,SACE,YAAY,KAAA,KAAa,OAAO,YAAY,WAAW,UAAU,IAAI;;;AAK3E,SAAgB,uBACd,GACA,GACQ;AACR,KAAI,OAAO,MAAM,YAAY,OAAO,MAAM,SACxC,QAAO,KAAK,KAAK,IAAI,EAAE;AAGzB,QAAO,OAAO,EAAE,CAAC,cAAc,OAAO,EAAE,CAAC;;AAG3C,SAAgB,kBACd,GAAG,UACa;AAChB,QAAO,SAAS,QAAQ,KAAK,SAAS,QAAQ;AAC5C,MAAI,QAAQ,EAAG,QAAO;AACtB,SAAO,uBAAuB,KAAK,QAAQ,IAAI,IAAI,MAAM;GACzD;;;;;;;;;AAUJ,MAAa,iBAAyC;EACnD,QAAQ;EACR,YAAY;EACZ,YAAY;EACZ,SAAS;CACX;AAED,SAAgB,gBAAgB,QAAgC;AAC9D,QACE,OAAO,cAAc,iBAAiB,OAAO,cAAc,aAAa"}

@@ -1,3 +0,2 @@

const require_jsonplus = require('../serde/jsonplus.cjs');
const require_jsonplus = require("../serde/jsonplus.cjs");
//#region src/cache/base.ts

@@ -15,5 +14,5 @@ var BaseCache = class {

};
//#endregion
exports.BaseCache = BaseCache;
//# sourceMappingURL=base.cjs.map

@@ -1,1 +0,1 @@

{"version":3,"file":"base.cjs","names":["JsonPlusSerializer"],"sources":["../../src/cache/base.ts"],"sourcesContent":["import { SerializerProtocol } from \"../serde/base.js\";\nimport { JsonPlusSerializer } from \"../serde/jsonplus.js\";\n\nexport type CacheNamespace = string[];\nexport type CacheFullKey = [namespace: CacheNamespace, key: string];\n\nexport abstract class BaseCache<V = unknown> {\n serde: SerializerProtocol = new JsonPlusSerializer();\n\n /**\n * Initialize the cache with a serializer.\n *\n * @param serde - The serializer to use.\n */\n constructor(serde?: SerializerProtocol) {\n this.serde = serde || this.serde;\n }\n\n /**\n * Get the cached values for the given keys.\n *\n * @param keys - The keys to get.\n */\n abstract get(\n keys: CacheFullKey[]\n ): Promise<{ key: CacheFullKey; value: V }[]>;\n\n /**\n * Set the cached values for the given keys and TTLs.\n *\n * @param pairs - The pairs to set.\n */\n abstract set(\n pairs: { key: CacheFullKey; value: V; ttl?: number }[]\n ): Promise<void>;\n\n /**\n * Delete the cached values for the given namespaces.\n * If no namespaces are provided, clear all cached values.\n *\n * @param namespaces - The namespaces to clear.\n */\n abstract clear(namespaces: CacheNamespace[]): Promise<void>;\n}\n"],"mappings":";;;AAMA,IAAsB,YAAtB,MAA6C;CAC3C,QAA4B,IAAIA;;;;;;CAOhC,YAAY,OAA4B;AACtC,OAAK,QAAQ,SAAS,KAAK"}
{"version":3,"file":"base.cjs","names":["JsonPlusSerializer"],"sources":["../../src/cache/base.ts"],"sourcesContent":["import { SerializerProtocol } from \"../serde/base.js\";\nimport { JsonPlusSerializer } from \"../serde/jsonplus.js\";\n\nexport type CacheNamespace = string[];\nexport type CacheFullKey = [namespace: CacheNamespace, key: string];\n\nexport abstract class BaseCache<V = unknown> {\n serde: SerializerProtocol = new JsonPlusSerializer();\n\n /**\n * Initialize the cache with a serializer.\n *\n * @param serde - The serializer to use.\n */\n constructor(serde?: SerializerProtocol) {\n this.serde = serde || this.serde;\n }\n\n /**\n * Get the cached values for the given keys.\n *\n * @param keys - The keys to get.\n */\n abstract get(\n keys: CacheFullKey[]\n ): Promise<{ key: CacheFullKey; value: V }[]>;\n\n /**\n * Set the cached values for the given keys and TTLs.\n *\n * @param pairs - The pairs to set.\n */\n abstract set(\n pairs: { key: CacheFullKey; value: V; ttl?: number }[]\n ): Promise<void>;\n\n /**\n * Delete the cached values for the given namespaces.\n * If no namespaces are provided, clear all cached values.\n *\n * @param namespaces - The namespaces to clear.\n */\n abstract clear(namespaces: CacheNamespace[]): Promise<void>;\n}\n"],"mappings":";;AAMA,IAAsB,YAAtB,MAA6C;CAC3C,QAA4B,IAAIA,iBAAAA,oBAAoB;;;;;;CAOpD,YAAY,OAA4B;AACtC,OAAK,QAAQ,SAAS,KAAK"}

@@ -1,1 +0,1 @@

{"version":3,"file":"base.d.cts","names":["SerializerProtocol","CacheNamespace","CacheFullKey","BaseCache","V","Promise"],"sources":["../../src/cache/base.d.ts"],"sourcesContent":["import { SerializerProtocol } from \"../serde/base.js\";\nexport type CacheNamespace = string[];\nexport type CacheFullKey = [namespace: CacheNamespace, key: string];\nexport declare abstract class BaseCache<V = unknown> {\n serde: SerializerProtocol;\n /**\n * Initialize the cache with a serializer.\n *\n * @param serde - The serializer to use.\n */\n constructor(serde?: SerializerProtocol);\n /**\n * Get the cached values for the given keys.\n *\n * @param keys - The keys to get.\n */\n abstract get(keys: CacheFullKey[]): Promise<{\n key: CacheFullKey;\n value: V;\n }[]>;\n /**\n * Set the cached values for the given keys and TTLs.\n *\n * @param pairs - The pairs to set.\n */\n abstract set(pairs: {\n key: CacheFullKey;\n value: V;\n ttl?: number;\n }[]): Promise<void>;\n /**\n * Delete the cached values for the given namespaces.\n * If no namespaces are provided, clear all cached values.\n *\n * @param namespaces - The namespaces to clear.\n */\n abstract clear(namespaces: CacheNamespace[]): Promise<void>;\n}\n"],"mappings":";;;KACYC,cAAAA;KACAC,YAAAA,eAA2BD;AAD3BA,uBAEkBE,SAFJ,CAAA,IAAA,OAAA,CAAA,CAAA;EACdD,KAAAA,EAEDF,kBAFa;EACMG;;;;;aAcjBD,CAAAA,KAAAA,CAAAA,EAPWF,kBAOXE;;;;;;WAmBkBD,GAAAA,CAAAA,IAAAA,EApBRC,YAoBQD,EAAAA,CAAAA,EApBSI,OAoBTJ,CAAAA;IAAmBI,GAAAA,EAnBrCH,YAmBqCG;WAlBnCD;;;;;;;;SAQFF;WACEE;;QAELC;;;;;;;6BAOqBJ,mBAAmBI"}
{"version":3,"file":"base.d.cts","names":[],"sources":["../../src/cache/base.ts"],"mappings":";;;KAGY,cAAA;AAAA,KACA,YAAA,IAAgB,SAAA,EAAW,cAAA,EAAgB,GAAA;AAAA,uBAEjC,SAAA;EACpB,KAAA,EAAO,kBAAA;;;;AAHT;;EAUE,WAAA,CAAY,KAAA,GAAQ,kBAAA;EAV+B;;;;;EAAA,SAmB1C,GAAA,CACP,IAAA,EAAM,YAAA,KACL,OAAA;IAAU,GAAA,EAAK,YAAA;IAAc,KAAA,EAAO,CAAA;EAAA;EAlBhC;;;;;EAAA,SAyBE,GAAA,CACP,KAAA;IAAS,GAAA,EAAK,YAAA;IAAc,KAAA,EAAO,CAAA;IAAG,GAAA;EAAA,MACrC,OAAA;EAQ2C;;;;;;EAAA,SAArC,KAAA,CAAM,UAAA,EAAY,cAAA,KAAmB,OAAA;AAAA"}

@@ -1,1 +0,1 @@

{"version":3,"file":"base.d.ts","names":["SerializerProtocol","CacheNamespace","CacheFullKey","BaseCache","V","Promise"],"sources":["../../src/cache/base.d.ts"],"sourcesContent":["import { SerializerProtocol } from \"../serde/base.js\";\nexport type CacheNamespace = string[];\nexport type CacheFullKey = [namespace: CacheNamespace, key: string];\nexport declare abstract class BaseCache<V = unknown> {\n serde: SerializerProtocol;\n /**\n * Initialize the cache with a serializer.\n *\n * @param serde - The serializer to use.\n */\n constructor(serde?: SerializerProtocol);\n /**\n * Get the cached values for the given keys.\n *\n * @param keys - The keys to get.\n */\n abstract get(keys: CacheFullKey[]): Promise<{\n key: CacheFullKey;\n value: V;\n }[]>;\n /**\n * Set the cached values for the given keys and TTLs.\n *\n * @param pairs - The pairs to set.\n */\n abstract set(pairs: {\n key: CacheFullKey;\n value: V;\n ttl?: number;\n }[]): Promise<void>;\n /**\n * Delete the cached values for the given namespaces.\n * If no namespaces are provided, clear all cached values.\n *\n * @param namespaces - The namespaces to clear.\n */\n abstract clear(namespaces: CacheNamespace[]): Promise<void>;\n}\n"],"mappings":";;;KACYC,cAAAA;KACAC,YAAAA,eAA2BD;AAD3BA,uBAEkBE,SAFJ,CAAA,IAAA,OAAA,CAAA,CAAA;EACdD,KAAAA,EAEDF,kBAFa;EACMG;;;;;aAcjBD,CAAAA,KAAAA,CAAAA,EAPWF,kBAOXE;;;;;;WAmBkBD,GAAAA,CAAAA,IAAAA,EApBRC,YAoBQD,EAAAA,CAAAA,EApBSI,OAoBTJ,CAAAA;IAAmBI,GAAAA,EAnBrCH,YAmBqCG;WAlBnCD;;;;;;;;SAQFF;WACEE;;QAELC;;;;;;;6BAOqBJ,mBAAmBI"}
{"version":3,"file":"base.d.ts","names":[],"sources":["../../src/cache/base.ts"],"mappings":";;;KAGY,cAAA;AAAA,KACA,YAAA,IAAgB,SAAA,EAAW,cAAA,EAAgB,GAAA;AAAA,uBAEjC,SAAA;EACpB,KAAA,EAAO,kBAAA;;;;AAHT;;EAUE,WAAA,CAAY,KAAA,GAAQ,kBAAA;EAV+B;;;;;EAAA,SAmB1C,GAAA,CACP,IAAA,EAAM,YAAA,KACL,OAAA;IAAU,GAAA,EAAK,YAAA;IAAc,KAAA,EAAO,CAAA;EAAA;EAlBhC;;;;;EAAA,SAyBE,GAAA,CACP,KAAA;IAAS,GAAA,EAAK,YAAA;IAAc,KAAA,EAAO,CAAA;IAAG,GAAA;EAAA,MACrC,OAAA;EAQ2C;;;;;;EAAA,SAArC,KAAA,CAAM,UAAA,EAAY,cAAA,KAAmB,OAAA;AAAA"}
import { JsonPlusSerializer } from "../serde/jsonplus.js";
//#region src/cache/base.ts

@@ -15,5 +14,5 @@ var BaseCache = class {

};
//#endregion
export { BaseCache };
//# sourceMappingURL=base.js.map

@@ -1,1 +0,1 @@

{"version":3,"file":"base.js","names":[],"sources":["../../src/cache/base.ts"],"sourcesContent":["import { SerializerProtocol } from \"../serde/base.js\";\nimport { JsonPlusSerializer } from \"../serde/jsonplus.js\";\n\nexport type CacheNamespace = string[];\nexport type CacheFullKey = [namespace: CacheNamespace, key: string];\n\nexport abstract class BaseCache<V = unknown> {\n serde: SerializerProtocol = new JsonPlusSerializer();\n\n /**\n * Initialize the cache with a serializer.\n *\n * @param serde - The serializer to use.\n */\n constructor(serde?: SerializerProtocol) {\n this.serde = serde || this.serde;\n }\n\n /**\n * Get the cached values for the given keys.\n *\n * @param keys - The keys to get.\n */\n abstract get(\n keys: CacheFullKey[]\n ): Promise<{ key: CacheFullKey; value: V }[]>;\n\n /**\n * Set the cached values for the given keys and TTLs.\n *\n * @param pairs - The pairs to set.\n */\n abstract set(\n pairs: { key: CacheFullKey; value: V; ttl?: number }[]\n ): Promise<void>;\n\n /**\n * Delete the cached values for the given namespaces.\n * If no namespaces are provided, clear all cached values.\n *\n * @param namespaces - The namespaces to clear.\n */\n abstract clear(namespaces: CacheNamespace[]): Promise<void>;\n}\n"],"mappings":";;;AAMA,IAAsB,YAAtB,MAA6C;CAC3C,QAA4B,IAAI;;;;;;CAOhC,YAAY,OAA4B;AACtC,OAAK,QAAQ,SAAS,KAAK"}
{"version":3,"file":"base.js","names":[],"sources":["../../src/cache/base.ts"],"sourcesContent":["import { SerializerProtocol } from \"../serde/base.js\";\nimport { JsonPlusSerializer } from \"../serde/jsonplus.js\";\n\nexport type CacheNamespace = string[];\nexport type CacheFullKey = [namespace: CacheNamespace, key: string];\n\nexport abstract class BaseCache<V = unknown> {\n serde: SerializerProtocol = new JsonPlusSerializer();\n\n /**\n * Initialize the cache with a serializer.\n *\n * @param serde - The serializer to use.\n */\n constructor(serde?: SerializerProtocol) {\n this.serde = serde || this.serde;\n }\n\n /**\n * Get the cached values for the given keys.\n *\n * @param keys - The keys to get.\n */\n abstract get(\n keys: CacheFullKey[]\n ): Promise<{ key: CacheFullKey; value: V }[]>;\n\n /**\n * Set the cached values for the given keys and TTLs.\n *\n * @param pairs - The pairs to set.\n */\n abstract set(\n pairs: { key: CacheFullKey; value: V; ttl?: number }[]\n ): Promise<void>;\n\n /**\n * Delete the cached values for the given namespaces.\n * If no namespaces are provided, clear all cached values.\n *\n * @param namespaces - The namespaces to clear.\n */\n abstract clear(namespaces: CacheNamespace[]): Promise<void>;\n}\n"],"mappings":";;AAMA,IAAsB,YAAtB,MAA6C;CAC3C,QAA4B,IAAI,oBAAoB;;;;;;CAOpD,YAAY,OAA4B;AACtC,OAAK,QAAQ,SAAS,KAAK"}

@@ -1,2 +0,2 @@

const require_base = require('./base.cjs');
const require_memory = require('./memory.cjs');
require("./base.cjs");
require("./memory.cjs");

@@ -1,4 +0,3 @@

import { BaseCache } from "./base.js";
import { InMemoryCache } from "./memory.js";
export { };
import "./base.js";
import "./memory.js";
export {};

@@ -1,3 +0,2 @@

const require_base = require('./base.cjs');
const require_base = require("./base.cjs");
//#region src/cache/memory.ts

@@ -14,9 +13,7 @@ var InMemoryCache = class extends require_base.BaseCache {

const cached = this.cache[strNamespace][key];
if (cached.exp == null || now < cached.exp) {
const value = await this.serde.loadsTyped(cached.enc, cached.val);
return [{
key: fullKey,
value
}];
} else delete this.cache[strNamespace][key];
if (cached.exp == null || now < cached.exp) return [{
key: fullKey,
value: await this.serde.loadsTyped(cached.enc, cached.val)
}];
else delete this.cache[strNamespace][key];
}

@@ -52,5 +49,5 @@ return [];

};
//#endregion
exports.InMemoryCache = InMemoryCache;
//# sourceMappingURL=memory.cjs.map

@@ -1,1 +0,1 @@

{"version":3,"file":"memory.cjs","names":["BaseCache"],"sources":["../../src/cache/memory.ts"],"sourcesContent":["import { BaseCache, type CacheFullKey, type CacheNamespace } from \"./base.js\";\n\nexport class InMemoryCache<V = unknown> extends BaseCache<V> {\n private cache: {\n [namespace: string]: {\n [key: string]: {\n enc: string;\n val: Uint8Array | string;\n exp: number | null;\n };\n };\n } = {};\n\n async get(keys: CacheFullKey[]): Promise<{ key: CacheFullKey; value: V }[]> {\n if (!keys.length) return [];\n const now = Date.now();\n return (\n await Promise.all(\n keys.map(\n async (fullKey): Promise<{ key: CacheFullKey; value: V }[]> => {\n const [namespace, key] = fullKey;\n const strNamespace = namespace.join(\",\");\n\n if (strNamespace in this.cache && key in this.cache[strNamespace]) {\n const cached = this.cache[strNamespace][key];\n if (cached.exp == null || now < cached.exp) {\n const value = await this.serde.loadsTyped(\n cached.enc,\n cached.val\n );\n return [{ key: fullKey, value }];\n } else {\n delete this.cache[strNamespace][key];\n }\n }\n\n return [];\n }\n )\n )\n ).flat();\n }\n\n async set(\n pairs: { key: CacheFullKey; value: V; ttl?: number }[]\n ): Promise<void> {\n const now = Date.now();\n for (const { key: fullKey, value, ttl } of pairs) {\n const [namespace, key] = fullKey;\n const strNamespace = namespace.join(\",\");\n const [enc, val] = await this.serde.dumpsTyped(value);\n const exp = ttl != null ? ttl * 1000 + now : null;\n\n this.cache[strNamespace] ??= {};\n this.cache[strNamespace][key] = { enc, val, exp };\n }\n }\n\n async clear(namespaces: CacheNamespace[]): Promise<void> {\n if (!namespaces.length) {\n this.cache = {};\n return;\n }\n\n for (const namespace of namespaces) {\n const strNamespace = namespace.join(\",\");\n if (strNamespace in this.cache) delete this.cache[strNamespace];\n }\n }\n}\n"],"mappings":";;;AAEA,IAAa,gBAAb,cAAgDA,uBAAa;CAC3D,AAAQ,QAQJ;CAEJ,MAAM,IAAI,MAAkE;AAC1E,MAAI,CAAC,KAAK,OAAQ,QAAO;EACzB,MAAM,MAAM,KAAK;AACjB,UACE,MAAM,QAAQ,IACZ,KAAK,IACH,OAAO,YAAwD;GAC7D,MAAM,CAAC,WAAW,OAAO;GACzB,MAAM,eAAe,UAAU,KAAK;AAEpC,OAAI,gBAAgB,KAAK,SAAS,OAAO,KAAK,MAAM,eAAe;IACjE,MAAM,SAAS,KAAK,MAAM,cAAc;AACxC,QAAI,OAAO,OAAO,QAAQ,MAAM,OAAO,KAAK;KAC1C,MAAM,QAAQ,MAAM,KAAK,MAAM,WAC7B,OAAO,KACP,OAAO;AAET,YAAO,CAAC;MAAE,KAAK;MAAS;;UAExB,QAAO,KAAK,MAAM,cAAc;;AAIpC,UAAO;OAIb;;CAGJ,MAAM,IACJ,OACe;EACf,MAAM,MAAM,KAAK;AACjB,OAAK,MAAM,EAAE,KAAK,SAAS,OAAO,SAAS,OAAO;GAChD,MAAM,CAAC,WAAW,OAAO;GACzB,MAAM,eAAe,UAAU,KAAK;GACpC,MAAM,CAAC,KAAK,OAAO,MAAM,KAAK,MAAM,WAAW;GAC/C,MAAM,MAAM,OAAO,OAAO,MAAM,MAAO,MAAM;AAE7C,QAAK,MAAM,kBAAkB;AAC7B,QAAK,MAAM,cAAc,OAAO;IAAE;IAAK;IAAK;;;;CAIhD,MAAM,MAAM,YAA6C;AACvD,MAAI,CAAC,WAAW,QAAQ;AACtB,QAAK,QAAQ;AACb;;AAGF,OAAK,MAAM,aAAa,YAAY;GAClC,MAAM,eAAe,UAAU,KAAK;AACpC,OAAI,gBAAgB,KAAK,MAAO,QAAO,KAAK,MAAM"}
{"version":3,"file":"memory.cjs","names":["BaseCache"],"sources":["../../src/cache/memory.ts"],"sourcesContent":["import { BaseCache, type CacheFullKey, type CacheNamespace } from \"./base.js\";\n\nexport class InMemoryCache<V = unknown> extends BaseCache<V> {\n private cache: {\n [namespace: string]: {\n [key: string]: {\n enc: string;\n val: Uint8Array | string;\n exp: number | null;\n };\n };\n } = {};\n\n async get(keys: CacheFullKey[]): Promise<{ key: CacheFullKey; value: V }[]> {\n if (!keys.length) return [];\n const now = Date.now();\n return (\n await Promise.all(\n keys.map(\n async (fullKey): Promise<{ key: CacheFullKey; value: V }[]> => {\n const [namespace, key] = fullKey;\n const strNamespace = namespace.join(\",\");\n\n if (strNamespace in this.cache && key in this.cache[strNamespace]) {\n const cached = this.cache[strNamespace][key];\n if (cached.exp == null || now < cached.exp) {\n const value = await this.serde.loadsTyped(\n cached.enc,\n cached.val\n );\n return [{ key: fullKey, value }];\n } else {\n delete this.cache[strNamespace][key];\n }\n }\n\n return [];\n }\n )\n )\n ).flat();\n }\n\n async set(\n pairs: { key: CacheFullKey; value: V; ttl?: number }[]\n ): Promise<void> {\n const now = Date.now();\n for (const { key: fullKey, value, ttl } of pairs) {\n const [namespace, key] = fullKey;\n const strNamespace = namespace.join(\",\");\n const [enc, val] = await this.serde.dumpsTyped(value);\n const exp = ttl != null ? ttl * 1000 + now : null;\n\n this.cache[strNamespace] ??= {};\n this.cache[strNamespace][key] = { enc, val, exp };\n }\n }\n\n async clear(namespaces: CacheNamespace[]): Promise<void> {\n if (!namespaces.length) {\n this.cache = {};\n return;\n }\n\n for (const namespace of namespaces) {\n const strNamespace = namespace.join(\",\");\n if (strNamespace in this.cache) delete this.cache[strNamespace];\n }\n }\n}\n"],"mappings":";;AAEA,IAAa,gBAAb,cAAgDA,aAAAA,UAAa;CAC3D,QAQI,EAAE;CAEN,MAAM,IAAI,MAAkE;AAC1E,MAAI,CAAC,KAAK,OAAQ,QAAO,EAAE;EAC3B,MAAM,MAAM,KAAK,KAAK;AACtB,UACE,MAAM,QAAQ,IACZ,KAAK,IACH,OAAO,YAAwD;GAC7D,MAAM,CAAC,WAAW,OAAO;GACzB,MAAM,eAAe,UAAU,KAAK,IAAI;AAExC,OAAI,gBAAgB,KAAK,SAAS,OAAO,KAAK,MAAM,eAAe;IACjE,MAAM,SAAS,KAAK,MAAM,cAAc;AACxC,QAAI,OAAO,OAAO,QAAQ,MAAM,OAAO,IAKrC,QAAO,CAAC;KAAE,KAAK;KAAS,OAJV,MAAM,KAAK,MAAM,WAC7B,OAAO,KACP,OAAO,IACR;KAC8B,CAAC;QAEhC,QAAO,KAAK,MAAM,cAAc;;AAIpC,UAAO,EAAE;IAEZ,CACF,EACD,MAAM;;CAGV,MAAM,IACJ,OACe;EACf,MAAM,MAAM,KAAK,KAAK;AACtB,OAAK,MAAM,EAAE,KAAK,SAAS,OAAO,SAAS,OAAO;GAChD,MAAM,CAAC,WAAW,OAAO;GACzB,MAAM,eAAe,UAAU,KAAK,IAAI;GACxC,MAAM,CAAC,KAAK,OAAO,MAAM,KAAK,MAAM,WAAW,MAAM;GACrD,MAAM,MAAM,OAAO,OAAO,MAAM,MAAO,MAAM;AAE7C,QAAK,MAAM,kBAAkB,EAAE;AAC/B,QAAK,MAAM,cAAc,OAAO;IAAE;IAAK;IAAK;IAAK;;;CAIrD,MAAM,MAAM,YAA6C;AACvD,MAAI,CAAC,WAAW,QAAQ;AACtB,QAAK,QAAQ,EAAE;AACf;;AAGF,OAAK,MAAM,aAAa,YAAY;GAClC,MAAM,eAAe,UAAU,KAAK,IAAI;AACxC,OAAI,gBAAgB,KAAK,MAAO,QAAO,KAAK,MAAM"}

@@ -1,1 +0,1 @@

{"version":3,"file":"memory.d.cts","names":["BaseCache","CacheFullKey","CacheNamespace","InMemoryCache","V","Promise"],"sources":["../../src/cache/memory.d.ts"],"sourcesContent":["import { BaseCache, type CacheFullKey, type CacheNamespace } from \"./base.js\";\nexport declare class InMemoryCache<V = unknown> extends BaseCache<V> {\n private cache;\n get(keys: CacheFullKey[]): Promise<{\n key: CacheFullKey;\n value: V;\n }[]>;\n set(pairs: {\n key: CacheFullKey;\n value: V;\n ttl?: number;\n }[]): Promise<void>;\n clear(namespaces: CacheNamespace[]): Promise<void>;\n}\n"],"mappings":";;;cACqBG,mCAAmCH,UAAUI;;EAA7CD,GAAAA,CAAAA,IAAAA,EAEPF,YAFoB,EAAA,CAAA,EAEHI,OAFG,CAAA;IAAA,GAAA,EAGrBJ,YAHqB;IAAgCG,KAAAA,EAInDA,CAJmDA;KAEpDH,CAAAA;KACDA,CAAAA,KAAAA,EAAAA;IACEG,GAAAA,EAGFH,YAHEG;IAFgBC,KAAAA,EAMhBD,CANgBC;IAKlBJ,GAAAA,CAAAA,EAAAA,MAAAA;KACEG,CAAAA,EAELC,OAFKD,CAAAA,IAAAA,CAAAA;OAELC,CAAAA,UAAAA,EACYH,cADZG,EAAAA,CAAAA,EAC+BA,OAD/BA,CAAAA,IAAAA,CAAAA"}
{"version":3,"file":"memory.d.cts","names":[],"sources":["../../src/cache/memory.ts"],"mappings":";;;cAEa,aAAA,sBAAmC,SAAA,CAAU,CAAA;EAAA,QAChD,KAAA;EAUF,GAAA,CAAI,IAAA,EAAM,YAAA,KAAiB,OAAA;IAAU,GAAA,EAAK,YAAA;IAAc,KAAA,EAAO,CAAA;EAAA;EA8B/D,GAAA,CACJ,KAAA;IAAS,GAAA,EAAK,YAAA;IAAc,KAAA,EAAO,CAAA;IAAG,GAAA;EAAA,MACrC,OAAA;EAaG,KAAA,CAAM,UAAA,EAAY,cAAA,KAAmB,OAAA;AAAA"}

@@ -1,1 +0,1 @@

{"version":3,"file":"memory.d.ts","names":["BaseCache","CacheFullKey","CacheNamespace","InMemoryCache","V","Promise"],"sources":["../../src/cache/memory.d.ts"],"sourcesContent":["import { BaseCache, type CacheFullKey, type CacheNamespace } from \"./base.js\";\nexport declare class InMemoryCache<V = unknown> extends BaseCache<V> {\n private cache;\n get(keys: CacheFullKey[]): Promise<{\n key: CacheFullKey;\n value: V;\n }[]>;\n set(pairs: {\n key: CacheFullKey;\n value: V;\n ttl?: number;\n }[]): Promise<void>;\n clear(namespaces: CacheNamespace[]): Promise<void>;\n}\n"],"mappings":";;;cACqBG,mCAAmCH,UAAUI;;EAA7CD,GAAAA,CAAAA,IAAAA,EAEPF,YAFoB,EAAA,CAAA,EAEHI,OAFG,CAAA;IAAA,GAAA,EAGrBJ,YAHqB;IAAgCG,KAAAA,EAInDA,CAJmDA;KAEpDH,CAAAA;KACDA,CAAAA,KAAAA,EAAAA;IACEG,GAAAA,EAGFH,YAHEG;IAFgBC,KAAAA,EAMhBD,CANgBC;IAKlBJ,GAAAA,CAAAA,EAAAA,MAAAA;KACEG,CAAAA,EAELC,OAFKD,CAAAA,IAAAA,CAAAA;OAELC,CAAAA,UAAAA,EACYH,cADZG,EAAAA,CAAAA,EAC+BA,OAD/BA,CAAAA,IAAAA,CAAAA"}
{"version":3,"file":"memory.d.ts","names":[],"sources":["../../src/cache/memory.ts"],"mappings":";;;cAEa,aAAA,sBAAmC,SAAA,CAAU,CAAA;EAAA,QAChD,KAAA;EAUF,GAAA,CAAI,IAAA,EAAM,YAAA,KAAiB,OAAA;IAAU,GAAA,EAAK,YAAA;IAAc,KAAA,EAAO,CAAA;EAAA;EA8B/D,GAAA,CACJ,KAAA;IAAS,GAAA,EAAK,YAAA;IAAc,KAAA,EAAO,CAAA;IAAG,GAAA;EAAA,MACrC,OAAA;EAaG,KAAA,CAAM,UAAA,EAAY,cAAA,KAAmB,OAAA;AAAA"}
import { BaseCache } from "./base.js";
//#region src/cache/memory.ts

@@ -14,9 +13,7 @@ var InMemoryCache = class extends BaseCache {

const cached = this.cache[strNamespace][key];
if (cached.exp == null || now < cached.exp) {
const value = await this.serde.loadsTyped(cached.enc, cached.val);
return [{
key: fullKey,
value
}];
} else delete this.cache[strNamespace][key];
if (cached.exp == null || now < cached.exp) return [{
key: fullKey,
value: await this.serde.loadsTyped(cached.enc, cached.val)
}];
else delete this.cache[strNamespace][key];
}

@@ -52,5 +49,5 @@ return [];

};
//#endregion
export { InMemoryCache };
//# sourceMappingURL=memory.js.map

@@ -1,1 +0,1 @@

{"version":3,"file":"memory.js","names":[],"sources":["../../src/cache/memory.ts"],"sourcesContent":["import { BaseCache, type CacheFullKey, type CacheNamespace } from \"./base.js\";\n\nexport class InMemoryCache<V = unknown> extends BaseCache<V> {\n private cache: {\n [namespace: string]: {\n [key: string]: {\n enc: string;\n val: Uint8Array | string;\n exp: number | null;\n };\n };\n } = {};\n\n async get(keys: CacheFullKey[]): Promise<{ key: CacheFullKey; value: V }[]> {\n if (!keys.length) return [];\n const now = Date.now();\n return (\n await Promise.all(\n keys.map(\n async (fullKey): Promise<{ key: CacheFullKey; value: V }[]> => {\n const [namespace, key] = fullKey;\n const strNamespace = namespace.join(\",\");\n\n if (strNamespace in this.cache && key in this.cache[strNamespace]) {\n const cached = this.cache[strNamespace][key];\n if (cached.exp == null || now < cached.exp) {\n const value = await this.serde.loadsTyped(\n cached.enc,\n cached.val\n );\n return [{ key: fullKey, value }];\n } else {\n delete this.cache[strNamespace][key];\n }\n }\n\n return [];\n }\n )\n )\n ).flat();\n }\n\n async set(\n pairs: { key: CacheFullKey; value: V; ttl?: number }[]\n ): Promise<void> {\n const now = Date.now();\n for (const { key: fullKey, value, ttl } of pairs) {\n const [namespace, key] = fullKey;\n const strNamespace = namespace.join(\",\");\n const [enc, val] = await this.serde.dumpsTyped(value);\n const exp = ttl != null ? ttl * 1000 + now : null;\n\n this.cache[strNamespace] ??= {};\n this.cache[strNamespace][key] = { enc, val, exp };\n }\n }\n\n async clear(namespaces: CacheNamespace[]): Promise<void> {\n if (!namespaces.length) {\n this.cache = {};\n return;\n }\n\n for (const namespace of namespaces) {\n const strNamespace = namespace.join(\",\");\n if (strNamespace in this.cache) delete this.cache[strNamespace];\n }\n }\n}\n"],"mappings":";;;AAEA,IAAa,gBAAb,cAAgD,UAAa;CAC3D,AAAQ,QAQJ;CAEJ,MAAM,IAAI,MAAkE;AAC1E,MAAI,CAAC,KAAK,OAAQ,QAAO;EACzB,MAAM,MAAM,KAAK;AACjB,UACE,MAAM,QAAQ,IACZ,KAAK,IACH,OAAO,YAAwD;GAC7D,MAAM,CAAC,WAAW,OAAO;GACzB,MAAM,eAAe,UAAU,KAAK;AAEpC,OAAI,gBAAgB,KAAK,SAAS,OAAO,KAAK,MAAM,eAAe;IACjE,MAAM,SAAS,KAAK,MAAM,cAAc;AACxC,QAAI,OAAO,OAAO,QAAQ,MAAM,OAAO,KAAK;KAC1C,MAAM,QAAQ,MAAM,KAAK,MAAM,WAC7B,OAAO,KACP,OAAO;AAET,YAAO,CAAC;MAAE,KAAK;MAAS;;UAExB,QAAO,KAAK,MAAM,cAAc;;AAIpC,UAAO;OAIb;;CAGJ,MAAM,IACJ,OACe;EACf,MAAM,MAAM,KAAK;AACjB,OAAK,MAAM,EAAE,KAAK,SAAS,OAAO,SAAS,OAAO;GAChD,MAAM,CAAC,WAAW,OAAO;GACzB,MAAM,eAAe,UAAU,KAAK;GACpC,MAAM,CAAC,KAAK,OAAO,MAAM,KAAK,MAAM,WAAW;GAC/C,MAAM,MAAM,OAAO,OAAO,MAAM,MAAO,MAAM;AAE7C,QAAK,MAAM,kBAAkB;AAC7B,QAAK,MAAM,cAAc,OAAO;IAAE;IAAK;IAAK;;;;CAIhD,MAAM,MAAM,YAA6C;AACvD,MAAI,CAAC,WAAW,QAAQ;AACtB,QAAK,QAAQ;AACb;;AAGF,OAAK,MAAM,aAAa,YAAY;GAClC,MAAM,eAAe,UAAU,KAAK;AACpC,OAAI,gBAAgB,KAAK,MAAO,QAAO,KAAK,MAAM"}
{"version":3,"file":"memory.js","names":[],"sources":["../../src/cache/memory.ts"],"sourcesContent":["import { BaseCache, type CacheFullKey, type CacheNamespace } from \"./base.js\";\n\nexport class InMemoryCache<V = unknown> extends BaseCache<V> {\n private cache: {\n [namespace: string]: {\n [key: string]: {\n enc: string;\n val: Uint8Array | string;\n exp: number | null;\n };\n };\n } = {};\n\n async get(keys: CacheFullKey[]): Promise<{ key: CacheFullKey; value: V }[]> {\n if (!keys.length) return [];\n const now = Date.now();\n return (\n await Promise.all(\n keys.map(\n async (fullKey): Promise<{ key: CacheFullKey; value: V }[]> => {\n const [namespace, key] = fullKey;\n const strNamespace = namespace.join(\",\");\n\n if (strNamespace in this.cache && key in this.cache[strNamespace]) {\n const cached = this.cache[strNamespace][key];\n if (cached.exp == null || now < cached.exp) {\n const value = await this.serde.loadsTyped(\n cached.enc,\n cached.val\n );\n return [{ key: fullKey, value }];\n } else {\n delete this.cache[strNamespace][key];\n }\n }\n\n return [];\n }\n )\n )\n ).flat();\n }\n\n async set(\n pairs: { key: CacheFullKey; value: V; ttl?: number }[]\n ): Promise<void> {\n const now = Date.now();\n for (const { key: fullKey, value, ttl } of pairs) {\n const [namespace, key] = fullKey;\n const strNamespace = namespace.join(\",\");\n const [enc, val] = await this.serde.dumpsTyped(value);\n const exp = ttl != null ? ttl * 1000 + now : null;\n\n this.cache[strNamespace] ??= {};\n this.cache[strNamespace][key] = { enc, val, exp };\n }\n }\n\n async clear(namespaces: CacheNamespace[]): Promise<void> {\n if (!namespaces.length) {\n this.cache = {};\n return;\n }\n\n for (const namespace of namespaces) {\n const strNamespace = namespace.join(\",\");\n if (strNamespace in this.cache) delete this.cache[strNamespace];\n }\n }\n}\n"],"mappings":";;AAEA,IAAa,gBAAb,cAAgD,UAAa;CAC3D,QAQI,EAAE;CAEN,MAAM,IAAI,MAAkE;AAC1E,MAAI,CAAC,KAAK,OAAQ,QAAO,EAAE;EAC3B,MAAM,MAAM,KAAK,KAAK;AACtB,UACE,MAAM,QAAQ,IACZ,KAAK,IACH,OAAO,YAAwD;GAC7D,MAAM,CAAC,WAAW,OAAO;GACzB,MAAM,eAAe,UAAU,KAAK,IAAI;AAExC,OAAI,gBAAgB,KAAK,SAAS,OAAO,KAAK,MAAM,eAAe;IACjE,MAAM,SAAS,KAAK,MAAM,cAAc;AACxC,QAAI,OAAO,OAAO,QAAQ,MAAM,OAAO,IAKrC,QAAO,CAAC;KAAE,KAAK;KAAS,OAJV,MAAM,KAAK,MAAM,WAC7B,OAAO,KACP,OAAO,IACR;KAC8B,CAAC;QAEhC,QAAO,KAAK,MAAM,cAAc;;AAIpC,UAAO,EAAE;IAEZ,CACF,EACD,MAAM;;CAGV,MAAM,IACJ,OACe;EACf,MAAM,MAAM,KAAK,KAAK;AACtB,OAAK,MAAM,EAAE,KAAK,SAAS,OAAO,SAAS,OAAO;GAChD,MAAM,CAAC,WAAW,OAAO;GACzB,MAAM,eAAe,UAAU,KAAK,IAAI;GACxC,MAAM,CAAC,KAAK,OAAO,MAAM,KAAK,MAAM,WAAW,MAAM;GACrD,MAAM,MAAM,OAAO,OAAO,MAAM,MAAO,MAAM;AAE7C,QAAK,MAAM,kBAAkB,EAAE;AAC/B,QAAK,MAAM,cAAc,OAAO;IAAE;IAAK;IAAK;IAAK;;;CAIrD,MAAM,MAAM,YAA6C;AACvD,MAAI,CAAC,WAAW,QAAQ;AACtB,QAAK,QAAQ,EAAE;AACf;;AAGF,OAAK,MAAM,aAAa,YAAY;GAClC,MAAM,eAAe,UAAU,KAAK,IAAI;AACxC,OAAI,gBAAgB,KAAK,MAAO,QAAO,KAAK,MAAM"}

@@ -1,4 +0,2 @@

const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
const uuid = require_rolldown_runtime.__toESM(require("uuid"));
let uuid = require("uuid");
//#region src/id.ts

@@ -12,6 +10,6 @@ function uuid6(clockseq) {

}
//#endregion
exports.uuid5 = uuid5;
exports.uuid6 = uuid6;
//# sourceMappingURL=id.cjs.map

@@ -1,1 +0,1 @@

{"version":3,"file":"id.cjs","names":[],"sources":["../src/id.ts"],"sourcesContent":["import { v5, v6 } from \"uuid\";\n\nexport function uuid6(clockseq: number): string {\n return v6({ clockseq });\n}\n\n// Skip UUID validation check, since UUID6s\n// generated with negative clockseq are not\n// technically compliant, but still work.\n// See: https://github.com/uuidjs/uuid/issues/511\nexport function uuid5(name: string, namespace: string): string {\n const namespaceBytes = namespace\n .replace(/-/g, \"\")\n .match(/.{2}/g)!\n .map((byte) => parseInt(byte, 16));\n return v5(name, new Uint8Array(namespaceBytes));\n}\n"],"mappings":";;;;AAEA,SAAgB,MAAM,UAA0B;AAC9C,qBAAU,EAAE;;AAOd,SAAgB,MAAM,MAAc,WAA2B;CAC7D,MAAM,iBAAiB,UACpB,QAAQ,MAAM,IACd,MAAM,SACN,KAAK,SAAS,SAAS,MAAM;AAChC,qBAAU,MAAM,IAAI,WAAW"}
{"version":3,"file":"id.cjs","names":[],"sources":["../src/id.ts"],"sourcesContent":["import { v5, v6 } from \"uuid\";\n\nexport function uuid6(clockseq: number): string {\n return v6({ clockseq });\n}\n\n// Skip UUID validation check, since UUID6s\n// generated with negative clockseq are not\n// technically compliant, but still work.\n// See: https://github.com/uuidjs/uuid/issues/511\nexport function uuid5(name: string, namespace: string): string {\n const namespaceBytes = namespace\n .replace(/-/g, \"\")\n .match(/.{2}/g)!\n .map((byte) => parseInt(byte, 16));\n return v5(name, new Uint8Array(namespaceBytes));\n}\n"],"mappings":";;AAEA,SAAgB,MAAM,UAA0B;AAC9C,SAAA,GAAA,KAAA,IAAU,EAAE,UAAU,CAAC;;AAOzB,SAAgB,MAAM,MAAc,WAA2B;CAC7D,MAAM,iBAAiB,UACpB,QAAQ,MAAM,GAAG,CACjB,MAAM,QAAQ,CACd,KAAK,SAAS,SAAS,MAAM,GAAG,CAAC;AACpC,SAAA,GAAA,KAAA,IAAU,MAAM,IAAI,WAAW,eAAe,CAAC"}
//#region src/id.d.ts
declare function uuid6(clockseq: number): string;
// Skip UUID validation check, since UUID6s
// generated with negative clockseq are not
// technically compliant, but still work.
// See: https://github.com/uuidjs/uuid/issues/511
declare function uuid5(name: string, namespace: string): string;

@@ -8,0 +4,0 @@ //#endregion

@@ -1,1 +0,1 @@

{"version":3,"file":"id.d.cts","names":["uuid6","uuid5"],"sources":["../src/id.d.ts"],"sourcesContent":["export declare function uuid6(clockseq: number): string;\n// Skip UUID validation check, since UUID6s\n// generated with negative clockseq are not\n// technically compliant, but still work.\n// See: https://github.com/uuidjs/uuid/issues/511\nexport declare function uuid5(name: string, namespace: string): string;\n"],"mappings":";iBAAwBA,KAAAA;AAAxB;AAKA;;;iBAAwBC,KAAAA"}
{"version":3,"file":"id.d.cts","names":[],"sources":["../src/id.ts"],"mappings":";iBAEgB,KAAA,CAAM,QAAA;AAAA,iBAQN,KAAA,CAAM,IAAA,UAAc,SAAA"}
//#region src/id.d.ts
declare function uuid6(clockseq: number): string;
// Skip UUID validation check, since UUID6s
// generated with negative clockseq are not
// technically compliant, but still work.
// See: https://github.com/uuidjs/uuid/issues/511
declare function uuid5(name: string, namespace: string): string;

@@ -8,0 +4,0 @@ //#endregion

@@ -1,1 +0,1 @@

{"version":3,"file":"id.d.ts","names":["uuid6","uuid5"],"sources":["../src/id.d.ts"],"sourcesContent":["export declare function uuid6(clockseq: number): string;\n// Skip UUID validation check, since UUID6s\n// generated with negative clockseq are not\n// technically compliant, but still work.\n// See: https://github.com/uuidjs/uuid/issues/511\nexport declare function uuid5(name: string, namespace: string): string;\n"],"mappings":";iBAAwBA,KAAAA;AAAxB;AAKA;;;iBAAwBC,KAAAA"}
{"version":3,"file":"id.d.ts","names":[],"sources":["../src/id.ts"],"mappings":";iBAEgB,KAAA,CAAM,QAAA;AAAA,iBAQN,KAAA,CAAM,IAAA,UAAc,SAAA"}
import { v5, v6 } from "uuid";
//#region src/id.ts

@@ -11,5 +10,5 @@ function uuid6(clockseq) {

}
//#endregion
export { uuid5, uuid6 };
//# sourceMappingURL=id.js.map

@@ -1,1 +0,1 @@

{"version":3,"file":"id.js","names":[],"sources":["../src/id.ts"],"sourcesContent":["import { v5, v6 } from \"uuid\";\n\nexport function uuid6(clockseq: number): string {\n return v6({ clockseq });\n}\n\n// Skip UUID validation check, since UUID6s\n// generated with negative clockseq are not\n// technically compliant, but still work.\n// See: https://github.com/uuidjs/uuid/issues/511\nexport function uuid5(name: string, namespace: string): string {\n const namespaceBytes = namespace\n .replace(/-/g, \"\")\n .match(/.{2}/g)!\n .map((byte) => parseInt(byte, 16));\n return v5(name, new Uint8Array(namespaceBytes));\n}\n"],"mappings":";;;AAEA,SAAgB,MAAM,UAA0B;AAC9C,QAAO,GAAG,EAAE;;AAOd,SAAgB,MAAM,MAAc,WAA2B;CAC7D,MAAM,iBAAiB,UACpB,QAAQ,MAAM,IACd,MAAM,SACN,KAAK,SAAS,SAAS,MAAM;AAChC,QAAO,GAAG,MAAM,IAAI,WAAW"}
{"version":3,"file":"id.js","names":[],"sources":["../src/id.ts"],"sourcesContent":["import { v5, v6 } from \"uuid\";\n\nexport function uuid6(clockseq: number): string {\n return v6({ clockseq });\n}\n\n// Skip UUID validation check, since UUID6s\n// generated with negative clockseq are not\n// technically compliant, but still work.\n// See: https://github.com/uuidjs/uuid/issues/511\nexport function uuid5(name: string, namespace: string): string {\n const namespaceBytes = namespace\n .replace(/-/g, \"\")\n .match(/.{2}/g)!\n .map((byte) => parseInt(byte, 16));\n return v5(name, new Uint8Array(namespaceBytes));\n}\n"],"mappings":";;AAEA,SAAgB,MAAM,UAA0B;AAC9C,QAAO,GAAG,EAAE,UAAU,CAAC;;AAOzB,SAAgB,MAAM,MAAc,WAA2B;CAC7D,MAAM,iBAAiB,UACpB,QAAQ,MAAM,GAAG,CACjB,MAAM,QAAQ,CACd,KAAK,SAAS,SAAS,MAAM,GAAG,CAAC;AACpC,QAAO,GAAG,MAAM,IAAI,WAAW,eAAe,CAAC"}

@@ -1,12 +0,12 @@

const require_id = require('./id.cjs');
const require_types = require('./serde/types.cjs');
const require_base = require('./base.cjs');
const require_memory = require('./memory.cjs');
const require_base$1 = require('./store/base.cjs');
const require_batch = require('./store/batch.cjs');
const require_memory$1 = require('./store/memory.cjs');
const require_base$2 = require('./cache/base.cjs');
const require_memory$2 = require('./cache/memory.cjs');
require('./cache/index.cjs');
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_id = require("./id.cjs");
const require_types = require("./serde/types.cjs");
const require_base = require("./base.cjs");
const require_memory = require("./memory.cjs");
const require_base$1 = require("./store/base.cjs");
const require_batch = require("./store/batch.cjs");
const require_memory$1 = require("./store/memory.cjs");
const require_base$2 = require("./cache/base.cjs");
const require_memory$2 = require("./cache/memory.cjs");
require("./cache/index.cjs");
exports.AsyncBatchedStore = require_batch.AsyncBatchedStore;

@@ -36,2 +36,2 @@ exports.BaseCache = require_base$2.BaseCache;

exports.uuid5 = require_id.uuid5;
exports.uuid6 = require_id.uuid6;
exports.uuid6 = require_id.uuid6;

@@ -11,3 +11,2 @@ import { uuid5, uuid6 } from "./id.js";

import "./cache/index.js";
export { AsyncBatchedStore, BaseCache, BaseCheckpointSaver, BaseStore, ERROR, INTERRUPT, InMemoryCache, InMemoryStore, InvalidNamespaceError, MemorySaver, MemoryStore, RESUME, SCHEDULED, TASKS, WRITES_IDX_MAP, compareChannelVersions, copyCheckpoint, deepCopy, emptyCheckpoint, getCheckpointId, getTextAtPath, maxChannelVersion, tokenizePath, uuid5, uuid6 };
export { AsyncBatchedStore, BaseCache, BaseCheckpointSaver, BaseStore, ERROR, INTERRUPT, InMemoryCache, InMemoryStore, InvalidNamespaceError, MemorySaver, MemoryStore, RESUME, SCHEDULED, TASKS, WRITES_IDX_MAP, compareChannelVersions, copyCheckpoint, deepCopy, emptyCheckpoint, getCheckpointId, getTextAtPath, maxChannelVersion, tokenizePath, uuid5, uuid6 };

@@ -1,4 +0,3 @@

const require_types = require('./serde/types.cjs');
const require_base = require('./base.cjs');
const require_types = require("./serde/types.cjs");
const require_base = require("./base.cjs");
//#region src/memory.ts

@@ -71,4 +70,3 @@ function _generateKey(threadId, checkpointNamespace, checkpointId) {

checkpoint_id = Object.keys(checkpoints).sort((a, b) => b.localeCompare(a))[0];
const saved = checkpoints[checkpoint_id];
const [checkpoint, metadata, parentCheckpointId] = saved;
const [checkpoint, metadata, parentCheckpointId] = checkpoints[checkpoint_id];
const key = _generateKey(thread_id, checkpoint_ns, checkpoint_id);

@@ -102,3 +100,2 @@ const deserializedCheckpoint = await this.serde.loadsTyped("json", checkpoint);

}
return void 0;
}

@@ -118,3 +115,3 @@ async *list(config, options) {

const metadata = await this.serde.loadsTyped("json", metadataStr);
if (filter && !Object.entries(filter).every(([key$1, value]) => metadata[key$1] === value)) continue;
if (filter && !Object.entries(filter).every(([key, value]) => metadata[key] === value)) continue;
if (limit !== void 0) {

@@ -199,5 +196,5 @@ if (limit <= 0) break;

};
//#endregion
exports.MemorySaver = MemorySaver;
//# sourceMappingURL=memory.cjs.map

@@ -1,1 +0,1 @@

{"version":3,"file":"memory.cjs","names":["BaseCheckpointSaver","TASKS","maxChannelVersion","getCheckpointId","deserializedCheckpoint: Checkpoint","pendingWrites: CheckpointPendingWrite[]","checkpointTuple: CheckpointTuple","key","preparedCheckpoint: Partial<Checkpoint>","copyCheckpoint","innerKey: [string, number]","WRITES_IDX_MAP"],"sources":["../src/memory.ts"],"sourcesContent":["import type { RunnableConfig } from \"@langchain/core/runnables\";\nimport {\n BaseCheckpointSaver,\n Checkpoint,\n CheckpointListOptions,\n CheckpointTuple,\n copyCheckpoint,\n getCheckpointId,\n maxChannelVersion,\n WRITES_IDX_MAP,\n} from \"./base.js\";\nimport { SerializerProtocol } from \"./serde/base.js\";\nimport {\n CheckpointMetadata,\n CheckpointPendingWrite,\n PendingWrite,\n} from \"./types.js\";\nimport { TASKS } from \"./serde/types.js\";\n\nfunction _generateKey(\n threadId: string,\n checkpointNamespace: string,\n checkpointId: string\n) {\n return JSON.stringify([threadId, checkpointNamespace, checkpointId]);\n}\n\nfunction _parseKey(key: string) {\n const [threadId, checkpointNamespace, checkpointId] = JSON.parse(key);\n return { threadId, checkpointNamespace, checkpointId };\n}\n\nexport class MemorySaver extends BaseCheckpointSaver {\n // thread ID -> checkpoint namespace -> checkpoint ID -> checkpoint mapping\n storage: Record<\n string,\n Record<string, Record<string, [Uint8Array, Uint8Array, string | undefined]>>\n > = {};\n\n writes: Record<string, Record<string, [string, string, Uint8Array]>> = {};\n\n constructor(serde?: SerializerProtocol) {\n super(serde);\n }\n\n /** @internal */\n async _migratePendingSends(\n mutableCheckpoint: Checkpoint,\n threadId: string,\n checkpointNs: string,\n parentCheckpointId: string\n ) {\n const deseriablizableCheckpoint = mutableCheckpoint;\n const parentKey = _generateKey(threadId, checkpointNs, parentCheckpointId);\n\n const pendingSends = await Promise.all(\n Object.values(this.writes[parentKey] ?? {})\n .filter(([_taskId, channel]) => channel === TASKS)\n .map(\n async ([_taskId, _channel, writes]) =>\n await this.serde.loadsTyped(\"json\", writes)\n )\n );\n\n deseriablizableCheckpoint.channel_values ??= {};\n deseriablizableCheckpoint.channel_values[TASKS] = pendingSends;\n\n deseriablizableCheckpoint.channel_versions ??= {};\n deseriablizableCheckpoint.channel_versions[TASKS] =\n Object.keys(deseriablizableCheckpoint.channel_versions).length > 0\n ? maxChannelVersion(\n ...Object.values(deseriablizableCheckpoint.channel_versions)\n )\n : this.getNextVersion(undefined);\n }\n\n async getTuple(config: RunnableConfig): Promise<CheckpointTuple | undefined> {\n const thread_id = config.configurable?.thread_id;\n const checkpoint_ns = config.configurable?.checkpoint_ns ?? \"\";\n let checkpoint_id = getCheckpointId(config);\n\n if (checkpoint_id) {\n const saved = this.storage[thread_id]?.[checkpoint_ns]?.[checkpoint_id];\n if (saved !== undefined) {\n const [checkpoint, metadata, parentCheckpointId] = saved;\n const key = _generateKey(thread_id, checkpoint_ns, checkpoint_id);\n const deserializedCheckpoint: Checkpoint = await this.serde.loadsTyped(\n \"json\",\n checkpoint\n );\n\n if (deserializedCheckpoint.v < 4 && parentCheckpointId !== undefined) {\n await this._migratePendingSends(\n deserializedCheckpoint,\n thread_id,\n checkpoint_ns,\n parentCheckpointId\n );\n }\n\n const pendingWrites: CheckpointPendingWrite[] = await Promise.all(\n Object.values(this.writes[key] || {}).map(\n async ([taskId, channel, value]) => {\n return [\n taskId,\n channel,\n await this.serde.loadsTyped(\"json\", value),\n ];\n }\n )\n );\n const checkpointTuple: CheckpointTuple = {\n config,\n checkpoint: deserializedCheckpoint,\n metadata: (await this.serde.loadsTyped(\n \"json\",\n metadata\n )) as CheckpointMetadata,\n pendingWrites,\n };\n if (parentCheckpointId !== undefined) {\n checkpointTuple.parentConfig = {\n configurable: {\n thread_id,\n checkpoint_ns,\n checkpoint_id: parentCheckpointId,\n },\n };\n }\n return checkpointTuple;\n }\n } else {\n const checkpoints = this.storage[thread_id]?.[checkpoint_ns];\n if (checkpoints !== undefined) {\n // eslint-disable-next-line prefer-destructuring\n checkpoint_id = Object.keys(checkpoints).sort((a, b) =>\n b.localeCompare(a)\n )[0];\n const saved = checkpoints[checkpoint_id];\n const [checkpoint, metadata, parentCheckpointId] = saved;\n const key = _generateKey(thread_id, checkpoint_ns, checkpoint_id);\n const deserializedCheckpoint: Checkpoint = await this.serde.loadsTyped(\n \"json\",\n checkpoint\n );\n\n if (deserializedCheckpoint.v < 4 && parentCheckpointId !== undefined) {\n await this._migratePendingSends(\n deserializedCheckpoint,\n thread_id,\n checkpoint_ns,\n parentCheckpointId\n );\n }\n\n const pendingWrites: CheckpointPendingWrite[] = await Promise.all(\n Object.values(this.writes[key] || {}).map(\n async ([taskId, channel, value]) => {\n return [\n taskId,\n channel,\n await this.serde.loadsTyped(\"json\", value),\n ];\n }\n )\n );\n const checkpointTuple: CheckpointTuple = {\n config: {\n configurable: {\n thread_id,\n checkpoint_id,\n checkpoint_ns,\n },\n },\n checkpoint: deserializedCheckpoint,\n metadata: (await this.serde.loadsTyped(\n \"json\",\n metadata\n )) as CheckpointMetadata,\n pendingWrites,\n };\n if (parentCheckpointId !== undefined) {\n checkpointTuple.parentConfig = {\n configurable: {\n thread_id,\n checkpoint_ns,\n checkpoint_id: parentCheckpointId,\n },\n };\n }\n return checkpointTuple;\n }\n }\n\n return undefined;\n }\n\n async *list(\n config: RunnableConfig,\n options?: CheckpointListOptions\n ): AsyncGenerator<CheckpointTuple> {\n // eslint-disable-next-line prefer-const\n let { before, limit, filter } = options ?? {};\n const threadIds = config.configurable?.thread_id\n ? [config.configurable?.thread_id]\n : Object.keys(this.storage);\n const configCheckpointNamespace = config.configurable?.checkpoint_ns;\n const configCheckpointId = config.configurable?.checkpoint_id;\n\n for (const threadId of threadIds) {\n for (const checkpointNamespace of Object.keys(\n this.storage[threadId] ?? {}\n )) {\n if (\n configCheckpointNamespace !== undefined &&\n checkpointNamespace !== configCheckpointNamespace\n ) {\n continue;\n }\n const checkpoints = this.storage[threadId]?.[checkpointNamespace] ?? {};\n const sortedCheckpoints = Object.entries(checkpoints).sort((a, b) =>\n b[0].localeCompare(a[0])\n );\n\n for (const [\n checkpointId,\n [checkpoint, metadataStr, parentCheckpointId],\n ] of sortedCheckpoints) {\n // Filter by checkpoint ID from config\n if (configCheckpointId && checkpointId !== configCheckpointId) {\n continue;\n }\n\n // Filter by checkpoint ID from before config\n if (\n before &&\n before.configurable?.checkpoint_id &&\n checkpointId >= before.configurable.checkpoint_id\n ) {\n continue;\n }\n\n // Parse metadata\n const metadata = (await this.serde.loadsTyped(\n \"json\",\n metadataStr\n )) as CheckpointMetadata;\n\n if (\n filter &&\n !Object.entries(filter).every(\n ([key, value]) =>\n (metadata as unknown as Record<string, unknown>)[key] === value\n )\n ) {\n continue;\n }\n\n // Limit search results\n if (limit !== undefined) {\n if (limit <= 0) break;\n limit -= 1;\n }\n\n const key = _generateKey(threadId, checkpointNamespace, checkpointId);\n const writes = Object.values(this.writes[key] || {});\n\n const pendingWrites: CheckpointPendingWrite[] = await Promise.all(\n writes.map(async ([taskId, channel, value]) => {\n return [\n taskId,\n channel,\n await this.serde.loadsTyped(\"json\", value),\n ];\n })\n );\n\n const deserializedCheckpoint = await this.serde.loadsTyped(\n \"json\",\n checkpoint\n );\n\n if (\n deserializedCheckpoint.v < 4 &&\n parentCheckpointId !== undefined\n ) {\n await this._migratePendingSends(\n deserializedCheckpoint,\n threadId,\n checkpointNamespace,\n parentCheckpointId\n );\n }\n\n const checkpointTuple: CheckpointTuple = {\n config: {\n configurable: {\n thread_id: threadId,\n checkpoint_ns: checkpointNamespace,\n checkpoint_id: checkpointId,\n },\n },\n checkpoint: deserializedCheckpoint,\n metadata,\n pendingWrites,\n };\n if (parentCheckpointId !== undefined) {\n checkpointTuple.parentConfig = {\n configurable: {\n thread_id: threadId,\n checkpoint_ns: checkpointNamespace,\n checkpoint_id: parentCheckpointId,\n },\n };\n }\n yield checkpointTuple;\n }\n }\n }\n }\n\n async put(\n config: RunnableConfig,\n checkpoint: Checkpoint,\n metadata: CheckpointMetadata\n ): Promise<RunnableConfig> {\n const preparedCheckpoint: Partial<Checkpoint> = copyCheckpoint(checkpoint);\n const threadId = config.configurable?.thread_id;\n const checkpointNamespace = config.configurable?.checkpoint_ns ?? \"\";\n if (threadId === undefined) {\n throw new Error(\n `Failed to put checkpoint. The passed RunnableConfig is missing a required \"thread_id\" field in its \"configurable\" property.`\n );\n }\n\n if (!this.storage[threadId]) {\n this.storage[threadId] = {};\n }\n if (!this.storage[threadId][checkpointNamespace]) {\n this.storage[threadId][checkpointNamespace] = {};\n }\n\n const [[, serializedCheckpoint], [, serializedMetadata]] =\n await Promise.all([\n this.serde.dumpsTyped(preparedCheckpoint),\n this.serde.dumpsTyped(metadata),\n ]);\n\n this.storage[threadId][checkpointNamespace][checkpoint.id] = [\n serializedCheckpoint,\n serializedMetadata,\n config.configurable?.checkpoint_id, // parent\n ];\n\n return {\n configurable: {\n thread_id: threadId,\n checkpoint_ns: checkpointNamespace,\n checkpoint_id: checkpoint.id,\n },\n };\n }\n\n async putWrites(\n config: RunnableConfig,\n writes: PendingWrite[],\n taskId: string\n ): Promise<void> {\n const threadId = config.configurable?.thread_id;\n const checkpointNamespace = config.configurable?.checkpoint_ns;\n const checkpointId = config.configurable?.checkpoint_id;\n if (threadId === undefined) {\n throw new Error(\n `Failed to put writes. The passed RunnableConfig is missing a required \"thread_id\" field in its \"configurable\" property`\n );\n }\n if (checkpointId === undefined) {\n throw new Error(\n `Failed to put writes. The passed RunnableConfig is missing a required \"checkpoint_id\" field in its \"configurable\" property.`\n );\n }\n const outerKey = _generateKey(threadId, checkpointNamespace, checkpointId);\n const outerWrites_ = this.writes[outerKey];\n if (this.writes[outerKey] === undefined) {\n this.writes[outerKey] = {};\n }\n\n await Promise.all(\n writes.map(async ([channel, value], idx) => {\n const [, serializedValue] = await this.serde.dumpsTyped(value);\n const innerKey: [string, number] = [\n taskId,\n WRITES_IDX_MAP[channel] || idx,\n ];\n const innerKeyStr = `${innerKey[0]},${innerKey[1]}`;\n if (innerKey[1] >= 0 && outerWrites_ && innerKeyStr in outerWrites_) {\n return;\n }\n this.writes[outerKey][innerKeyStr] = [taskId, channel, serializedValue];\n })\n );\n }\n\n async deleteThread(threadId: string): Promise<void> {\n delete this.storage[threadId];\n for (const key of Object.keys(this.writes)) {\n if (_parseKey(key).threadId === threadId)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AI,SAAS,MAAM,KAAK,gBAAgB,eAAe,aACrD;AAEF,QAAK,OAAO,UAAU,eAAe;IAAC;IAAQ;IAAS;;;;CAK7D,MAAM,aAAa,UAAiC;AAClD,SAAO,KAAK,QAAQ;AACpB,OAAK,MAAM,OAAO,OAAO,KAAK,KAAK,QACjC,KAAI,UAAU,KAAK,aAAa,SAAU,QAAO,KAAK,OAAO"}
{"version":3,"file":"memory.cjs","names":["BaseCheckpointSaver","TASKS","maxChannelVersion","getCheckpointId","copyCheckpoint","WRITES_IDX_MAP"],"sources":["../src/memory.ts"],"sourcesContent":["import type { RunnableConfig } from \"@langchain/core/runnables\";\nimport {\n BaseCheckpointSaver,\n Checkpoint,\n CheckpointListOptions,\n CheckpointTuple,\n copyCheckpoint,\n getCheckpointId,\n maxChannelVersion,\n WRITES_IDX_MAP,\n} from \"./base.js\";\nimport { SerializerProtocol } from \"./serde/base.js\";\nimport {\n CheckpointMetadata,\n CheckpointPendingWrite,\n PendingWrite,\n} from \"./types.js\";\nimport { TASKS } from \"./serde/types.js\";\n\nfunction _generateKey(\n threadId: string,\n checkpointNamespace: string,\n checkpointId: string\n) {\n return JSON.stringify([threadId, checkpointNamespace, checkpointId]);\n}\n\nfunction _parseKey(key: string) {\n const [threadId, checkpointNamespace, checkpointId] = JSON.parse(key);\n return { threadId, checkpointNamespace, checkpointId };\n}\n\nexport class MemorySaver extends BaseCheckpointSaver {\n // thread ID -> checkpoint namespace -> checkpoint ID -> checkpoint mapping\n storage: Record<\n string,\n Record<string, Record<string, [Uint8Array, Uint8Array, string | undefined]>>\n > = {};\n\n writes: Record<string, Record<string, [string, string, Uint8Array]>> = {};\n\n constructor(serde?: SerializerProtocol) {\n super(serde);\n }\n\n /** @internal */\n async _migratePendingSends(\n mutableCheckpoint: Checkpoint,\n threadId: string,\n checkpointNs: string,\n parentCheckpointId: string\n ) {\n const deseriablizableCheckpoint = mutableCheckpoint;\n const parentKey = _generateKey(threadId, checkpointNs, parentCheckpointId);\n\n const pendingSends = await Promise.all(\n Object.values(this.writes[parentKey] ?? {})\n .filter(([_taskId, channel]) => channel === TASKS)\n .map(\n async ([_taskId, _channel, writes]) =>\n await this.serde.loadsTyped(\"json\", writes)\n )\n );\n\n deseriablizableCheckpoint.channel_values ??= {};\n deseriablizableCheckpoint.channel_values[TASKS] = pendingSends;\n\n deseriablizableCheckpoint.channel_versions ??= {};\n deseriablizableCheckpoint.channel_versions[TASKS] =\n Object.keys(deseriablizableCheckpoint.channel_versions).length > 0\n ? maxChannelVersion(\n ...Object.values(deseriablizableCheckpoint.channel_versions)\n )\n : this.getNextVersion(undefined);\n }\n\n async getTuple(config: RunnableConfig): Promise<CheckpointTuple | undefined> {\n const thread_id = config.configurable?.thread_id;\n const checkpoint_ns = config.configurable?.checkpoint_ns ?? \"\";\n let checkpoint_id = getCheckpointId(config);\n\n if (checkpoint_id) {\n const saved = this.storage[thread_id]?.[checkpoint_ns]?.[checkpoint_id];\n if (saved !== undefined) {\n const [checkpoint, metadata, parentCheckpointId] = saved;\n const key = _generateKey(thread_id, checkpoint_ns, checkpoint_id);\n const deserializedCheckpoint: Checkpoint = await this.serde.loadsTyped(\n \"json\",\n checkpoint\n );\n\n if (deserializedCheckpoint.v < 4 && parentCheckpointId !== undefined) {\n await this._migratePendingSends(\n deserializedCheckpoint,\n thread_id,\n checkpoint_ns,\n parentCheckpointId\n );\n }\n\n const pendingWrites: CheckpointPendingWrite[] = await Promise.all(\n Object.values(this.writes[key] || {}).map(\n async ([taskId, channel, value]) => {\n return [\n taskId,\n channel,\n await this.serde.loadsTyped(\"json\", value),\n ];\n }\n )\n );\n const checkpointTuple: CheckpointTuple = {\n config,\n checkpoint: deserializedCheckpoint,\n metadata: (await this.serde.loadsTyped(\n \"json\",\n metadata\n )) as CheckpointMetadata,\n pendingWrites,\n };\n if (parentCheckpointId !== undefined) {\n checkpointTuple.parentConfig = {\n configurable: {\n thread_id,\n checkpoint_ns,\n checkpoint_id: parentCheckpointId,\n },\n };\n }\n return checkpointTuple;\n }\n } else {\n const checkpoints = this.storage[thread_id]?.[checkpoint_ns];\n if (checkpoints !== undefined) {\n // eslint-disable-next-line prefer-destructuring\n checkpoint_id = Object.keys(checkpoints).sort((a, b) =>\n b.localeCompare(a)\n )[0];\n const saved = checkpoints[checkpoint_id];\n const [checkpoint, metadata, parentCheckpointId] = saved;\n const key = _generateKey(thread_id, checkpoint_ns, checkpoint_id);\n const deserializedCheckpoint: Checkpoint = await this.serde.loadsTyped(\n \"json\",\n checkpoint\n );\n\n if (deserializedCheckpoint.v < 4 && parentCheckpointId !== undefined) {\n await this._migratePendingSends(\n deserializedCheckpoint,\n thread_id,\n checkpoint_ns,\n parentCheckpointId\n );\n }\n\n const pendingWrites: CheckpointPendingWrite[] = await Promise.all(\n Object.values(this.writes[key] || {}).map(\n async ([taskId, channel, value]) => {\n return [\n taskId,\n channel,\n await this.serde.loadsTyped(\"json\", value),\n ];\n }\n )\n );\n const checkpointTuple: CheckpointTuple = {\n config: {\n configurable: {\n thread_id,\n checkpoint_id,\n checkpoint_ns,\n },\n },\n checkpoint: deserializedCheckpoint,\n metadata: (await this.serde.loadsTyped(\n \"json\",\n metadata\n )) as CheckpointMetadata,\n pendingWrites,\n };\n if (parentCheckpointId !== undefined) {\n checkpointTuple.parentConfig = {\n configurable: {\n thread_id,\n checkpoint_ns,\n checkpoint_id: parentCheckpointId,\n },\n };\n }\n return checkpointTuple;\n }\n }\n\n return undefined;\n }\n\n async *list(\n config: RunnableConfig,\n options?: CheckpointListOptions\n ): AsyncGenerator<CheckpointTuple> {\n // eslint-disable-next-line prefer-const\n let { before, limit, filter } = options ?? {};\n const threadIds = config.configurable?.thread_id\n ? [config.configurable?.thread_id]\n : Object.keys(this.storage);\n const configCheckpointNamespace = config.configurable?.checkpoint_ns;\n const configCheckpointId = config.configurable?.checkpoint_id;\n\n for (const threadId of threadIds) {\n for (const checkpointNamespace of Object.keys(\n this.storage[threadId] ?? {}\n )) {\n if (\n configCheckpointNamespace !== undefined &&\n checkpointNamespace !== configCheckpointNamespace\n ) {\n continue;\n }\n const checkpoints = this.storage[threadId]?.[checkpointNamespace] ?? {};\n const sortedCheckpoints = Object.entries(checkpoints).sort((a, b) =>\n b[0].localeCompare(a[0])\n );\n\n for (const [\n checkpointId,\n [checkpoint, metadataStr, parentCheckpointId],\n ] of sortedCheckpoints) {\n // Filter by checkpoint ID from config\n if (configCheckpointId && checkpointId !== configCheckpointId) {\n continue;\n }\n\n // Filter by checkpoint ID from before config\n if (\n before &&\n before.configurable?.checkpoint_id &&\n checkpointId >= before.configurable.checkpoint_id\n ) {\n continue;\n }\n\n // Parse metadata\n const metadata = (await this.serde.loadsTyped(\n \"json\",\n metadataStr\n )) as CheckpointMetadata;\n\n if (\n filter &&\n !Object.entries(filter).every(\n ([key, value]) =>\n (metadata as unknown as Record<string, unknown>)[key] === value\n )\n ) {\n continue;\n }\n\n // Limit search results\n if (limit !== undefined) {\n if (limit <= 0) break;\n limit -= 1;\n }\n\n const key = _generateKey(threadId, checkpointNamespace, checkpointId);\n const writes = Object.values(this.writes[key] || {});\n\n const pendingWrites: CheckpointPendingWrite[] = await Promise.all(\n writes.map(async ([taskId, channel, value]) => {\n return [\n taskId,\n channel,\n await this.serde.loadsTyped(\"json\", value),\n ];\n })\n );\n\n const deserializedCheckpoint = await this.serde.loadsTyped(\n \"json\",\n checkpoint\n );\n\n if (\n deserializedCheckpoint.v < 4 &&\n parentCheckpointId !== undefined\n ) {\n await this._migratePendingSends(\n deserializedCheckpoint,\n threadId,\n checkpointNamespace,\n parentCheckpointId\n );\n }\n\n const checkpointTuple: CheckpointTuple = {\n config: {\n configurable: {\n thread_id: threadId,\n checkpoint_ns: checkpointNamespace,\n checkpoint_id: checkpointId,\n },\n },\n checkpoint: deserializedCheckpoint,\n metadata,\n pendingWrites,\n };\n if (parentCheckpointId !== undefined) {\n checkpointTuple.parentConfig = {\n configurable: {\n thread_id: threadId,\n checkpoint_ns: checkpointNamespace,\n checkpoint_id: parentCheckpointId,\n },\n };\n }\n yield checkpointTuple;\n }\n }\n }\n }\n\n async put(\n config: RunnableConfig,\n checkpoint: Checkpoint,\n metadata: CheckpointMetadata\n ): Promise<RunnableConfig> {\n const preparedCheckpoint: Partial<Checkpoint> = copyCheckpoint(checkpoint);\n const threadId = config.configurable?.thread_id;\n const checkpointNamespace = config.configurable?.checkpoint_ns ?? \"\";\n if (threadId === undefined) {\n throw new Error(\n `Failed to put checkpoint. The passed RunnableConfig is missing a required \"thread_id\" field in its \"configurable\" property.`\n );\n }\n\n if (!this.storage[threadId]) {\n this.storage[threadId] = {};\n }\n if (!this.storage[threadId][checkpointNamespace]) {\n this.storage[threadId][checkpointNamespace] = {};\n }\n\n const [[, serializedCheckpoint], [, serializedMetadata]] =\n await Promise.all([\n this.serde.dumpsTyped(preparedCheckpoint),\n this.serde.dumpsTyped(metadata),\n ]);\n\n this.storage[threadId][checkpointNamespace][checkpoint.id] = [\n serializedCheckpoint,\n serializedMetadata,\n config.configurable?.checkpoint_id, // parent\n ];\n\n return {\n configurable: {\n thread_id: threadId,\n checkpoint_ns: checkpointNamespace,\n checkpoint_id: checkpoint.id,\n },\n };\n }\n\n async putWrites(\n config: RunnableConfig,\n writes: PendingWrite[],\n taskId: string\n ): Promise<void> {\n const threadId = config.configurable?.thread_id;\n const checkpointNamespace = config.configurable?.checkpoint_ns;\n const checkpointId = config.configurable?.checkpoint_id;\n if (threadId === undefined) {\n throw new Error(\n `Failed to put writes. The passed RunnableConfig is missing a required \"thread_id\" field in its \"configurable\" property`\n );\n }\n if (checkpointId === undefined) {\n throw new Error(\n `Failed to put writes. The passed RunnableConfig is missing a required \"checkpoint_id\" field in its \"configurable\" property.`\n );\n }\n const outerKey = _generateKey(threadId, checkpointNamespace, checkpointId);\n const outerWrites_ = this.writes[outerKey];\n if (this.writes[outerKey] === undefined) {\n this.writes[outerKey] = {};\n }\n\n await Promise.all(\n writes.map(async ([channel, value], idx) => {\n const [, serializedValue] = await this.serde.dumpsTyped(value);\n const innerKey: [string, number] = [\n taskId,\n WRITES_IDX_MAP[channel] || idx,\n ];\n const innerKeyStr = `${innerKey[0]},${innerKey[1]}`;\n if (innerKey[1] >= 0 && outerWrites_ && innerKeyStr in outerWrites_) {\n return;\n }\n this.writes[outerKey][innerKeyStr] = [taskId, channel, serializedValue];\n })\n );\n }\n\n async deleteThread(threadId: string): Promise<void> {\n delete this.storage[threadId];\n for (const key of Object.keys(this.writes)) {\n if (_parseKey(key).threadId === threadId) delete this.writes[key];\n }\n }\n}\n"],"mappings":";;;AAmBA,SAAS,aACP,UACA,qBACA,cACA;AACA,QAAO,KAAK,UAAU;EAAC;EAAU;EAAqB;EAAa,CAAC;;AAGtE,SAAS,UAAU,KAAa;CAC9B,MAAM,CAAC,UAAU,qBAAqB,gBAAgB,KAAK,MAAM,IAAI;AACrE,QAAO;EAAE;EAAU;EAAqB;EAAc;;AAGxD,IAAa,cAAb,cAAiCA,aAAAA,oBAAoB;CAEnD,UAGI,EAAE;CAEN,SAAuE,EAAE;CAEzE,YAAY,OAA4B;AACtC,QAAM,MAAM;;;CAId,MAAM,qBACJ,mBACA,UACA,cACA,oBACA;EACA,MAAM,4BAA4B;EAClC,MAAM,YAAY,aAAa,UAAU,cAAc,mBAAmB;EAE1E,MAAM,eAAe,MAAM,QAAQ,IACjC,OAAO,OAAO,KAAK,OAAO,cAAc,EAAE,CAAC,CACxC,QAAQ,CAAC,SAAS,aAAa,YAAYC,cAAAA,MAAM,CACjD,IACC,OAAO,CAAC,SAAS,UAAU,YACzB,MAAM,KAAK,MAAM,WAAW,QAAQ,OAAO,CAC9C,CACJ;AAED,4BAA0B,mBAAmB,EAAE;AAC/C,4BAA0B,eAAeA,cAAAA,SAAS;AAElD,4BAA0B,qBAAqB,EAAE;AACjD,4BAA0B,iBAAiBA,cAAAA,SACzC,OAAO,KAAK,0BAA0B,iBAAiB,CAAC,SAAS,IAC7DC,aAAAA,kBACE,GAAG,OAAO,OAAO,0BAA0B,iBAAiB,CAC7D,GACD,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thread ID -> checkpoint namespace -> checkpoint ID -> checkpoint mapping
storage: Record<string, Record<string, Record<string, [Uint8Array, Uint8Array, string | undefined]>>>;

@@ -11,0 +10,0 @@ writes: Record<string, Record<string, [string, string, Uint8Array]>>;

@@ -1,1 +0,1 @@

{"version":3,"file":"memory.d.cts","names":["RunnableConfig","BaseCheckpointSaver","Checkpoint","CheckpointListOptions","CheckpointTuple","SerializerProtocol","CheckpointMetadata","PendingWrite","MemorySaver","Uint8Array","Record","Promise","AsyncGenerator"],"sources":["../src/memory.d.ts"],"sourcesContent":["import type { RunnableConfig } from \"@langchain/core/runnables\";\nimport { BaseCheckpointSaver, Checkpoint, CheckpointListOptions, CheckpointTuple } from \"./base.js\";\nimport { SerializerProtocol } from \"./serde/base.js\";\nimport { CheckpointMetadata, PendingWrite } from \"./types.js\";\nexport declare class MemorySaver extends BaseCheckpointSaver {\n // thread ID -> checkpoint namespace -> checkpoint ID -> checkpoint mapping\n storage: Record<string, Record<string, Record<string, [Uint8Array, Uint8Array, string | undefined]>>>;\n writes: Record<string, Record<string, [string, string, Uint8Array]>>;\n constructor(serde?: SerializerProtocol);\n /** @internal */\n _migratePendingSends(mutableCheckpoint: Checkpoint, threadId: string, checkpointNs: string, parentCheckpointId: string): Promise<void>;\n getTuple(config: RunnableConfig): Promise<CheckpointTuple | undefined>;\n list(config: RunnableConfig, options?: CheckpointListOptions): AsyncGenerator<CheckpointTuple>;\n put(config: RunnableConfig, checkpoint: Checkpoint, metadata: CheckpointMetadata): Promise<RunnableConfig>;\n putWrites(config: RunnableConfig, writes: PendingWrite[], taskId: string): Promise<void>;\n deleteThread(threadId: string): Promise<void>;\n}\n"],"mappings":";;;;;;cAIqBQ,WAAAA,SAAoBP,mBAAAA;;EAApBO,OAAAA,EAERE,MAFmB,CAAA,MAAA,EAEJA,MAFI,CAAA,MAAA,EAEWA,MAFX,CAAA,MAAA,EAAA,CAE2BD,UAF3B,EAEuCA,UAFvC,EAAA,MAAA,GAAA,SAAA,CAAA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,iBAAA,EAAmB,UAAA,EACnB,QAAA,UACA,YAAA,UACA,kBAAA,WAA0B,OAAA;EA0BtB,QAAA,CAAS,MAAA,EAAQ,cAAA,GAAiB,OAAA,CAAQ,eAAA;EAyHzC,IAAA,CACL,MAAA,EAAQ,cAAA,EACR,OAAA,GAAU,qBAAA,GACT,cAAA,CAAe,eAAA;EAyHZ,GAAA,CACJ,MAAA,EAAQ,cAAA,EACR,UAAA,EAAY,UAAA,EACZ,QAAA,EAAU,kBAAA,GACT,OAAA,CAAQ,cAAA;EAsCL,SAAA,CACJ,MAAA,EAAQ,cAAA,EACR,MAAA,EAAQ,YAAA,IACR,MAAA,WACC,OAAA;EAoCG,YAAA,CAAa,QAAA,WAAmB,OAAA;AAAA"}

@@ -8,3 +8,2 @@ import { SerializerProtocol } from "./serde/base.js";

declare class MemorySaver extends BaseCheckpointSaver {
// thread ID -> checkpoint namespace -> checkpoint ID -> checkpoint mapping
storage: Record<string, Record<string, Record<string, [Uint8Array, Uint8Array, string | undefined]>>>;

@@ -11,0 +10,0 @@ writes: Record<string, Record<string, [string, string, Uint8Array]>>;

@@ -1,1 +0,1 @@

{"version":3,"file":"memory.d.ts","names":["RunnableConfig","BaseCheckpointSaver","Checkpoint","CheckpointListOptions","CheckpointTuple","SerializerProtocol","CheckpointMetadata","PendingWrite","MemorySaver","Uint8Array","Record","Promise","AsyncGenerator"],"sources":["../src/memory.d.ts"],"sourcesContent":["import type { RunnableConfig } from \"@langchain/core/runnables\";\nimport { BaseCheckpointSaver, Checkpoint, CheckpointListOptions, CheckpointTuple } from \"./base.js\";\nimport { SerializerProtocol } from \"./serde/base.js\";\nimport { CheckpointMetadata, PendingWrite } from \"./types.js\";\nexport declare class MemorySaver extends BaseCheckpointSaver {\n // thread ID -> checkpoint namespace -> checkpoint ID -> checkpoint mapping\n storage: Record<string, Record<string, Record<string, [Uint8Array, Uint8Array, string | undefined]>>>;\n writes: Record<string, Record<string, [string, string, Uint8Array]>>;\n constructor(serde?: SerializerProtocol);\n /** @internal */\n _migratePendingSends(mutableCheckpoint: Checkpoint, threadId: string, checkpointNs: string, parentCheckpointId: string): Promise<void>;\n getTuple(config: RunnableConfig): Promise<CheckpointTuple | undefined>;\n list(config: RunnableConfig, options?: CheckpointListOptions): AsyncGenerator<CheckpointTuple>;\n put(config: RunnableConfig, checkpoint: Checkpoint, metadata: CheckpointMetadata): Promise<RunnableConfig>;\n putWrites(config: RunnableConfig, writes: PendingWrite[], taskId: string): Promise<void>;\n deleteThread(threadId: string): Promise<void>;\n}\n"],"mappings":";;;;;;cAIqBQ,WAAAA,SAAoBP,mBAAAA;;EAApBO,OAAAA,EAERE,MAFmB,CAAA,MAAA,EAEJA,MAFI,CAAA,MAAA,EAEWA,MAFX,CAAA,MAAA,EAAA,CAE2BD,UAF3B,EAEuCA,UAFvC,EAAA,MAAA,GAAA,SAAA,CAAA,CAAA,CAAA,CAAA;EAAA,MAAA,EAGpBC,MAHoB,CAAA,MAAA,EAGLA,MAHK,CAAA,MAAA,EAAA,CAAA,MAAA,EAAA,MAAA,EAG2BD,UAH3B,CAAA,CAAA,CAAA;aAE2BA,CAAAA,KAAAA,CAAAA,EAEnCJ,kBAFmCI;;sBAAhBC,CAAAA,iBAAAA,EAICR,UAJDQ,EAAAA,QAAAA,EAAAA,MAAAA,EAAAA,YAAAA,EAAAA,MAAAA,EAAAA,kBAAAA,EAAAA,MAAAA,CAAAA,EAIkFC,OAJlFD,CAAAA,IAAAA,CAAAA;UAAfA,CAAAA,MAAAA,EAKPV,cALOU,CAAAA,EAKUC,OALVD,CAKkBN,eALlBM,GAAAA,SAAAA,CAAAA;MAAfA,CAAAA,MAAAA,EAMIV,cANJU,EAAAA,OAAAA,CAAAA,EAM8BP,qBAN9BO,CAAAA,EAMsDE,cANtDF,CAMqEN,eANrEM,CAAAA;KAC8CD,CAAAA,MAAAA,EAM3CT,cAN2CS,EAAAA,UAAAA,EAMfP,UANeO,EAAAA,QAAAA,EAMOH,kBANPG,CAAAA,EAM4BE,OAN5BF,CAMoCT,cANpCS,CAAAA;WAAhCC,CAAAA,MAAAA,EAOLV,cAPKU,EAAAA,MAAAA,EAOmBH,YAPnBG,EAAAA,EAAAA,MAAAA,EAAAA,MAAAA,CAAAA,EAOoDC,OAPpDD,CAAAA,IAAAA,CAAAA;cAAfA,CAAAA,QAAAA,EAAAA,MAAAA,CAAAA,EAQwBC,OARxBD,CAAAA,IAAAA,CAAAA"}
{"version":3,"file":"memory.d.ts","names":[],"sources":["../src/memory.ts"],"mappings":";;;;;;cAgCa,WAAA,SAAoB,mBAAA;EAE/B,OAAA,EAAS,MAAA,SAEP,MAAA,SAAe,MAAA,UAAgB,UAAA,EAAY,UAAA;EAG7C,MAAA,EAAQ,MAAA,SAAe,MAAA,0BAAgC,UAAA;EAEvD,WAAA,CAAY,KAAA,GAAQ,kBAAA;;EAKd,oBAAA,CACJ,iBAAA,EAAmB,UAAA,EACnB,QAAA,UACA,YAAA,UACA,kBAAA,WAA0B,OAAA;EA0BtB,QAAA,CAAS,MAAA,EAAQ,cAAA,GAAiB,OAAA,CAAQ,eAAA;EAyHzC,IAAA,CACL,MAAA,EAAQ,cAAA,EACR,OAAA,GAAU,qBAAA,GACT,cAAA,CAAe,eAAA;EAyHZ,GAAA,CACJ,MAAA,EAAQ,cAAA,EACR,UAAA,EAAY,UAAA,EACZ,QAAA,EAAU,kBAAA,GACT,OAAA,CAAQ,cAAA;EAsCL,SAAA,CACJ,MAAA,EAAQ,cAAA,EACR,MAAA,EAAQ,YAAA,IACR,MAAA,WACC,OAAA;EAoCG,YAAA,CAAa,QAAA,WAAmB,OAAA;AAAA"}
import { TASKS } from "./serde/types.js";
import { BaseCheckpointSaver, WRITES_IDX_MAP, copyCheckpoint, getCheckpointId, maxChannelVersion } from "./base.js";
//#region src/memory.ts

@@ -71,4 +70,3 @@ function _generateKey(threadId, checkpointNamespace, checkpointId) {

checkpoint_id = Object.keys(checkpoints).sort((a, b) => b.localeCompare(a))[0];
const saved = checkpoints[checkpoint_id];
const [checkpoint, metadata, parentCheckpointId] = saved;
const [checkpoint, metadata, parentCheckpointId] = checkpoints[checkpoint_id];
const key = _generateKey(thread_id, checkpoint_ns, checkpoint_id);

@@ -102,3 +100,2 @@ const deserializedCheckpoint = await this.serde.loadsTyped("json", checkpoint);

}
return void 0;
}

@@ -118,3 +115,3 @@ async *list(config, options) {

const metadata = await this.serde.loadsTyped("json", metadataStr);
if (filter && !Object.entries(filter).every(([key$1, value]) => metadata[key$1] === value)) continue;
if (filter && !Object.entries(filter).every(([key, value]) => metadata[key] === value)) continue;
if (limit !== void 0) {

@@ -199,5 +196,5 @@ if (limit <= 0) break;

};
//#endregion
export { MemorySaver };
//# sourceMappingURL=memory.js.map

@@ -1,1 +0,1 @@

{"version":3,"file":"memory.js","names":["deserializedCheckpoint: Checkpoint","pendingWrites: CheckpointPendingWrite[]","checkpointTuple: CheckpointTuple","key","preparedCheckpoint: Partial<Checkpoint>","innerKey: [string, number]"],"sources":["../src/memory.ts"],"sourcesContent":["import type { RunnableConfig } from \"@langchain/core/runnables\";\nimport {\n BaseCheckpointSaver,\n Checkpoint,\n CheckpointListOptions,\n CheckpointTuple,\n copyCheckpoint,\n getCheckpointId,\n maxChannelVersion,\n WRITES_IDX_MAP,\n} from \"./base.js\";\nimport { SerializerProtocol } from \"./serde/base.js\";\nimport {\n CheckpointMetadata,\n CheckpointPendingWrite,\n PendingWrite,\n} from \"./types.js\";\nimport { TASKS } from \"./serde/types.js\";\n\nfunction _generateKey(\n threadId: string,\n checkpointNamespace: string,\n checkpointId: string\n) {\n return JSON.stringify([threadId, checkpointNamespace, checkpointId]);\n}\n\nfunction _parseKey(key: string) {\n const [threadId, checkpointNamespace, checkpointId] = JSON.parse(key);\n return { threadId, checkpointNamespace, checkpointId };\n}\n\nexport class MemorySaver extends BaseCheckpointSaver {\n // thread ID -> checkpoint namespace -> checkpoint ID -> checkpoint mapping\n storage: Record<\n string,\n Record<string, Record<string, [Uint8Array, Uint8Array, string | undefined]>>\n > = {};\n\n writes: Record<string, Record<string, [string, string, Uint8Array]>> = {};\n\n constructor(serde?: SerializerProtocol) {\n super(serde);\n }\n\n /** @internal */\n async _migratePendingSends(\n mutableCheckpoint: Checkpoint,\n threadId: string,\n checkpointNs: string,\n parentCheckpointId: string\n ) {\n const deseriablizableCheckpoint = mutableCheckpoint;\n const parentKey = _generateKey(threadId, checkpointNs, parentCheckpointId);\n\n const pendingSends = await Promise.all(\n Object.values(this.writes[parentKey] ?? {})\n .filter(([_taskId, channel]) => channel === TASKS)\n .map(\n async ([_taskId, _channel, writes]) =>\n await this.serde.loadsTyped(\"json\", writes)\n )\n );\n\n deseriablizableCheckpoint.channel_values ??= {};\n deseriablizableCheckpoint.channel_values[TASKS] = pendingSends;\n\n deseriablizableCheckpoint.channel_versions ??= {};\n deseriablizableCheckpoint.channel_versions[TASKS] =\n Object.keys(deseriablizableCheckpoint.channel_versions).length > 0\n ? maxChannelVersion(\n ...Object.values(deseriablizableCheckpoint.channel_versions)\n )\n : this.getNextVersion(undefined);\n }\n\n async getTuple(config: RunnableConfig): Promise<CheckpointTuple | undefined> {\n const thread_id = config.configurable?.thread_id;\n const checkpoint_ns = config.configurable?.checkpoint_ns ?? \"\";\n let checkpoint_id = getCheckpointId(config);\n\n if (checkpoint_id) {\n const saved = this.storage[thread_id]?.[checkpoint_ns]?.[checkpoint_id];\n if (saved !== undefined) {\n const [checkpoint, metadata, parentCheckpointId] = saved;\n const key = _generateKey(thread_id, checkpoint_ns, checkpoint_id);\n const deserializedCheckpoint: Checkpoint = await this.serde.loadsTyped(\n \"json\",\n checkpoint\n );\n\n if (deserializedCheckpoint.v < 4 && parentCheckpointId !== undefined) {\n await this._migratePendingSends(\n deserializedCheckpoint,\n thread_id,\n checkpoint_ns,\n parentCheckpointId\n );\n }\n\n const pendingWrites: CheckpointPendingWrite[] = await Promise.all(\n Object.values(this.writes[key] || {}).map(\n async ([taskId, channel, value]) => {\n return [\n taskId,\n channel,\n await this.serde.loadsTyped(\"json\", value),\n ];\n }\n )\n );\n const checkpointTuple: CheckpointTuple = {\n config,\n checkpoint: deserializedCheckpoint,\n metadata: (await this.serde.loadsTyped(\n \"json\",\n metadata\n )) as CheckpointMetadata,\n pendingWrites,\n };\n if (parentCheckpointId !== undefined) {\n checkpointTuple.parentConfig = {\n configurable: {\n thread_id,\n checkpoint_ns,\n checkpoint_id: parentCheckpointId,\n },\n };\n }\n return checkpointTuple;\n }\n } else {\n const checkpoints = this.storage[thread_id]?.[checkpoint_ns];\n if (checkpoints !== undefined) {\n // eslint-disable-next-line prefer-destructuring\n checkpoint_id = Object.keys(checkpoints).sort((a, b) =>\n b.localeCompare(a)\n )[0];\n const saved = checkpoints[checkpoint_id];\n const [checkpoint, metadata, parentCheckpointId] = saved;\n const key = _generateKey(thread_id, checkpoint_ns, checkpoint_id);\n const deserializedCheckpoint: Checkpoint = await this.serde.loadsTyped(\n \"json\",\n checkpoint\n );\n\n if (deserializedCheckpoint.v < 4 && parentCheckpointId !== undefined) {\n await this._migratePendingSends(\n deserializedCheckpoint,\n thread_id,\n checkpoint_ns,\n parentCheckpointId\n );\n }\n\n const pendingWrites: CheckpointPendingWrite[] = await Promise.all(\n Object.values(this.writes[key] || {}).map(\n async ([taskId, channel, value]) => {\n return [\n taskId,\n channel,\n await this.serde.loadsTyped(\"json\", value),\n ];\n }\n )\n );\n const checkpointTuple: CheckpointTuple = {\n config: {\n configurable: {\n thread_id,\n checkpoint_id,\n checkpoint_ns,\n },\n },\n checkpoint: deserializedCheckpoint,\n metadata: (await this.serde.loadsTyped(\n \"json\",\n metadata\n )) as CheckpointMetadata,\n pendingWrites,\n };\n if (parentCheckpointId !== undefined) {\n checkpointTuple.parentConfig = {\n configurable: {\n thread_id,\n checkpoint_ns,\n checkpoint_id: parentCheckpointId,\n },\n };\n }\n return checkpointTuple;\n }\n }\n\n return undefined;\n }\n\n async *list(\n config: RunnableConfig,\n options?: CheckpointListOptions\n ): AsyncGenerator<CheckpointTuple> {\n // eslint-disable-next-line prefer-const\n let { before, limit, filter } = options ?? {};\n const threadIds = config.configurable?.thread_id\n ? [config.configurable?.thread_id]\n : Object.keys(this.storage);\n const configCheckpointNamespace = config.configurable?.checkpoint_ns;\n const configCheckpointId = config.configurable?.checkpoint_id;\n\n for (const threadId of threadIds) {\n for (const checkpointNamespace of Object.keys(\n this.storage[threadId] ?? {}\n )) {\n if (\n configCheckpointNamespace !== undefined &&\n checkpointNamespace !== configCheckpointNamespace\n ) {\n continue;\n }\n const checkpoints = this.storage[threadId]?.[checkpointNamespace] ?? {};\n const sortedCheckpoints = Object.entries(checkpoints).sort((a, b) =>\n b[0].localeCompare(a[0])\n );\n\n for (const [\n checkpointId,\n [checkpoint, metadataStr, parentCheckpointId],\n ] of sortedCheckpoints) {\n // Filter by checkpoint ID from config\n if (configCheckpointId && checkpointId !== configCheckpointId) {\n continue;\n }\n\n // Filter by checkpoint ID from before config\n if (\n before &&\n before.configurable?.checkpoint_id &&\n checkpointId >= before.configurable.checkpoint_id\n ) {\n continue;\n }\n\n // Parse metadata\n const metadata = (await this.serde.loadsTyped(\n \"json\",\n metadataStr\n )) as CheckpointMetadata;\n\n if (\n filter &&\n !Object.entries(filter).every(\n ([key, value]) =>\n (metadata as unknown as Record<string, unknown>)[key] === value\n )\n ) {\n continue;\n }\n\n // Limit search results\n if (limit !== undefined) {\n if (limit <= 0) break;\n limit -= 1;\n }\n\n const key = _generateKey(threadId, checkpointNamespace, checkpointId);\n const writes = Object.values(this.writes[key] || {});\n\n const pendingWrites: CheckpointPendingWrite[] = await Promise.all(\n writes.map(async ([taskId, channel, value]) => {\n return [\n taskId,\n channel,\n await this.serde.loadsTyped(\"json\", value),\n ];\n })\n );\n\n const deserializedCheckpoint = await this.serde.loadsTyped(\n \"json\",\n checkpoint\n );\n\n if (\n deserializedCheckpoint.v < 4 &&\n parentCheckpointId !== undefined\n ) {\n await this._migratePendingSends(\n deserializedCheckpoint,\n threadId,\n checkpointNamespace,\n parentCheckpointId\n );\n }\n\n const checkpointTuple: CheckpointTuple = {\n config: {\n configurable: {\n thread_id: threadId,\n checkpoint_ns: checkpointNamespace,\n checkpoint_id: checkpointId,\n },\n },\n checkpoint: deserializedCheckpoint,\n metadata,\n pendingWrites,\n };\n if (parentCheckpointId !== undefined) {\n checkpointTuple.parentConfig = {\n configurable: {\n thread_id: threadId,\n checkpoint_ns: checkpointNamespace,\n checkpoint_id: parentCheckpointId,\n },\n };\n }\n yield checkpointTuple;\n }\n }\n }\n }\n\n async put(\n config: RunnableConfig,\n checkpoint: Checkpoint,\n metadata: CheckpointMetadata\n ): Promise<RunnableConfig> {\n const preparedCheckpoint: Partial<Checkpoint> = copyCheckpoint(checkpoint);\n const threadId = config.configurable?.thread_id;\n const checkpointNamespace = config.configurable?.checkpoint_ns ?? \"\";\n if (threadId === undefined) {\n throw new Error(\n `Failed to put checkpoint. The passed RunnableConfig is missing a required \"thread_id\" field in its \"configurable\" property.`\n );\n }\n\n if (!this.storage[threadId]) {\n this.storage[threadId] = {};\n }\n if (!this.storage[threadId][checkpointNamespace]) {\n this.storage[threadId][checkpointNamespace] = {};\n }\n\n const [[, serializedCheckpoint], [, serializedMetadata]] =\n await Promise.all([\n this.serde.dumpsTyped(preparedCheckpoint),\n this.serde.dumpsTyped(metadata),\n ]);\n\n this.storage[threadId][checkpointNamespace][checkpoint.id] = [\n serializedCheckpoint,\n serializedMetadata,\n config.configurable?.checkpoint_id, // parent\n ];\n\n return {\n configurable: {\n thread_id: threadId,\n checkpoint_ns: checkpointNamespace,\n checkpoint_id: checkpoint.id,\n },\n };\n }\n\n async putWrites(\n config: RunnableConfig,\n writes: PendingWrite[],\n taskId: string\n ): Promise<void> {\n const threadId = config.configurable?.thread_id;\n const checkpointNamespace = config.configurable?.checkpoint_ns;\n const checkpointId = config.configurable?.checkpoint_id;\n if (threadId === undefined) {\n throw new Error(\n `Failed to put writes. The passed RunnableConfig is missing a required \"thread_id\" field in its \"configurable\" property`\n );\n }\n if (checkpointId === undefined) {\n throw new Error(\n `Failed to put writes. The passed RunnableConfig is missing a required \"checkpoint_id\" field in its \"configurable\" property.`\n );\n }\n const outerKey = _generateKey(threadId, checkpointNamespace, checkpointId);\n const outerWrites_ = this.writes[outerKey];\n if (this.writes[outerKey] === undefined) {\n this.writes[outerKey] = {};\n }\n\n await Promise.all(\n writes.map(async ([channel, value], idx) => {\n const [, serializedValue] = await this.serde.dumpsTyped(value);\n const innerKey: [string, number] = [\n taskId,\n WRITES_IDX_MAP[channel] || idx,\n ];\n const innerKeyStr = `${innerKey[0]},${innerKey[1]}`;\n if (innerKey[1] >= 0 && outerWrites_ && innerKeyStr in outerWrites_) {\n return;\n }\n this.writes[outerKey][innerKeyStr] = [taskId, channel, serializedValue];\n })\n );\n }\n\n async deleteThread(threadId: string): Promise<void> {\n delete this.storage[threadId];\n for (const key of Object.keys(this.writes)) {\n if (_parseKey(key).threadId === threadId) delete this.writes[key];\n }\n }\n}\n"],"mappings":";;;;AAmBA,SAAS,aACP,UACA,qBACA,cACA;AACA,QAAO,KAAK,UAAU;EAAC;EAAU;EAAqB;;;AAGxD,SAAS,UAAU,KAAa;CAC9B,MAAM,CAAC,UAAU,qBAAqB,gBAAgB,KAAK,MAAM;AACjE,QAAO;EAAE;EAAU;EAAqB;;;AAG1C,IAAa,cAAb,cAAiC,oBAAoB;CAEnD,UAGI;CAEJ,SAAuE;CAEvE,YAAY,OAA4B;AACtC,QAAM;;;CAIR,MAAM,qBACJ,mBACA,UACA,cACA,oBACA;EACA,MAAM,4BAA4B;EAClC,MAAM,YAAY,aAAa,UAAU,cAAc;EAEvD,MAAM,eAAe,MAAM,QAAQ,IACjC,OAAO,OAAO,KAAK,OAAO,cAAc,IACrC,QAAQ,CAAC,SAAS,aAAa,YAAY,OAC3C,IACC,OAAO,CAAC,SAAS,UAAU,YACzB,MAAM,KAAK,MAAM,WAAW,QAAQ;AAI5C,4BAA0B,mBAAmB;AAC7C,4BAA0B,eAAe,SAAS;AAElD,4BAA0B,qBAAqB;A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,QACA,QACe;EACf,MAAM,WAAW,OAAO,cAAc;EACtC,MAAM,sBAAsB,OAAO,cAAc;EACjD,MAAM,eAAe,OAAO,cAAc;AAC1C,MAAI,aAAa,OACf,OAAM,IAAI,MACR;AAGJ,MAAI,iBAAiB,OACnB,OAAM,IAAI,MACR;EAGJ,MAAM,WAAW,aAAa,UAAU,qBAAqB;EAC7D,MAAM,eAAe,KAAK,OAAO;AACjC,MAAI,KAAK,OAAO,cAAc,OAC5B,MAAK,OAAO,YAAY;AAG1B,QAAM,QAAQ,IACZ,OAAO,IAAI,OAAO,CAAC,SAAS,QAAQ,QAAQ;GAC1C,MAAM,GAAG,mBAAmB,MAAM,KAAK,MAAM,WAAW;GACxD,MAAMC,WAA6B,CACjC,QACA,eAAe,YAAY;GAE7B,MAAM,cAAc,GAAG,SAAS,GAAG,GAAG,SAAS;AAC/C,OAAI,SAAS,MAAM,KAAK,gBAAgB,eAAe,aACrD;AAEF,QAAK,OAAO,UAAU,eAAe;IAAC;IAAQ;IAAS;;;;CAK7D,MAAM,aAAa,UAAiC;AAClD,SAAO,KAAK,QAAQ;AACpB,OAAK,MAAM,OAAO,OAAO,KAAK,KAAK,QACjC,KAAI,UAAU,KAAK,aAAa,SAAU,QAAO,KAAK,OAAO"}
{"version":3,"file":"memory.js","names":[],"sources":["../src/memory.ts"],"sourcesContent":["import type { RunnableConfig } from \"@langchain/core/runnables\";\nimport {\n BaseCheckpointSaver,\n Checkpoint,\n CheckpointListOptions,\n CheckpointTuple,\n copyCheckpoint,\n getCheckpointId,\n maxChannelVersion,\n WRITES_IDX_MAP,\n} from \"./base.js\";\nimport { SerializerProtocol } from \"./serde/base.js\";\nimport {\n CheckpointMetadata,\n CheckpointPendingWrite,\n PendingWrite,\n} from \"./types.js\";\nimport { TASKS } from \"./serde/types.js\";\n\nfunction _generateKey(\n threadId: string,\n checkpointNamespace: string,\n checkpointId: string\n) {\n return JSON.stringify([threadId, checkpointNamespace, checkpointId]);\n}\n\nfunction _parseKey(key: string) {\n const [threadId, checkpointNamespace, checkpointId] = JSON.parse(key);\n return { threadId, checkpointNamespace, checkpointId };\n}\n\nexport class MemorySaver extends BaseCheckpointSaver {\n // thread ID -> checkpoint namespace -> checkpoint ID -> checkpoint mapping\n storage: Record<\n string,\n Record<string, Record<string, [Uint8Array, Uint8Array, string | undefined]>>\n > = {};\n\n writes: Record<string, Record<string, [string, string, Uint8Array]>> = {};\n\n constructor(serde?: SerializerProtocol) {\n super(serde);\n }\n\n /** @internal */\n async _migratePendingSends(\n mutableCheckpoint: Checkpoint,\n threadId: string,\n checkpointNs: string,\n parentCheckpointId: string\n ) {\n const deseriablizableCheckpoint = mutableCheckpoint;\n const parentKey = _generateKey(threadId, checkpointNs, parentCheckpointId);\n\n const pendingSends = await Promise.all(\n Object.values(this.writes[parentKey] ?? {})\n .filter(([_taskId, channel]) => channel === TASKS)\n .map(\n async ([_taskId, _channel, writes]) =>\n await this.serde.loadsTyped(\"json\", writes)\n )\n );\n\n deseriablizableCheckpoint.channel_values ??= {};\n deseriablizableCheckpoint.channel_values[TASKS] = pendingSends;\n\n deseriablizableCheckpoint.channel_versions ??= {};\n deseriablizableCheckpoint.channel_versions[TASKS] =\n Object.keys(deseriablizableCheckpoint.channel_versions).length > 0\n ? maxChannelVersion(\n ...Object.values(deseriablizableCheckpoint.channel_versions)\n )\n : this.getNextVersion(undefined);\n }\n\n async getTuple(config: RunnableConfig): Promise<CheckpointTuple | undefined> {\n const thread_id = config.configurable?.thread_id;\n const checkpoint_ns = config.configurable?.checkpoint_ns ?? \"\";\n let checkpoint_id = getCheckpointId(config);\n\n if (checkpoint_id) {\n const saved = this.storage[thread_id]?.[checkpoint_ns]?.[checkpoint_id];\n if (saved !== undefined) {\n const [checkpoint, metadata, parentCheckpointId] = saved;\n const key = _generateKey(thread_id, checkpoint_ns, checkpoint_id);\n const deserializedCheckpoint: Checkpoint = await this.serde.loadsTyped(\n \"json\",\n checkpoint\n );\n\n if (deserializedCheckpoint.v < 4 && parentCheckpointId !== undefined) {\n await this._migratePendingSends(\n deserializedCheckpoint,\n thread_id,\n checkpoint_ns,\n parentCheckpointId\n );\n }\n\n const pendingWrites: CheckpointPendingWrite[] = await Promise.all(\n Object.values(this.writes[key] || {}).map(\n async ([taskId, channel, value]) => {\n return [\n taskId,\n channel,\n await this.serde.loadsTyped(\"json\", value),\n ];\n }\n )\n );\n const checkpointTuple: CheckpointTuple = {\n config,\n checkpoint: deserializedCheckpoint,\n metadata: (await this.serde.loadsTyped(\n \"json\",\n metadata\n )) as CheckpointMetadata,\n pendingWrites,\n };\n if (parentCheckpointId !== undefined) {\n checkpointTuple.parentConfig = {\n configurable: {\n thread_id,\n checkpoint_ns,\n checkpoint_id: parentCheckpointId,\n },\n };\n }\n return checkpointTuple;\n }\n } else {\n const checkpoints = this.storage[thread_id]?.[checkpoint_ns];\n if (checkpoints !== undefined) {\n // eslint-disable-next-line prefer-destructuring\n checkpoint_id = Object.keys(checkpoints).sort((a, b) =>\n b.localeCompare(a)\n )[0];\n const saved = checkpoints[checkpoint_id];\n const [checkpoint, metadata, parentCheckpointId] = saved;\n const key = _generateKey(thread_id, checkpoint_ns, checkpoint_id);\n const deserializedCheckpoint: Checkpoint = await this.serde.loadsTyped(\n \"json\",\n checkpoint\n );\n\n if (deserializedCheckpoint.v < 4 && parentCheckpointId !== undefined) {\n await this._migratePendingSends(\n deserializedCheckpoint,\n thread_id,\n checkpoint_ns,\n parentCheckpointId\n );\n }\n\n const pendingWrites: CheckpointPendingWrite[] = await Promise.all(\n Object.values(this.writes[key] || {}).map(\n async ([taskId, channel, value]) => {\n return [\n taskId,\n channel,\n await this.serde.loadsTyped(\"json\", value),\n ];\n }\n )\n );\n const checkpointTuple: CheckpointTuple = {\n config: {\n configurable: {\n thread_id,\n checkpoint_id,\n checkpoint_ns,\n },\n },\n checkpoint: deserializedCheckpoint,\n metadata: (await this.serde.loadsTyped(\n \"json\",\n metadata\n )) as CheckpointMetadata,\n pendingWrites,\n };\n if (parentCheckpointId !== undefined) {\n checkpointTuple.parentConfig = {\n configurable: {\n thread_id,\n checkpoint_ns,\n checkpoint_id: parentCheckpointId,\n },\n };\n }\n return checkpointTuple;\n }\n }\n\n return undefined;\n }\n\n async *list(\n config: RunnableConfig,\n options?: CheckpointListOptions\n ): AsyncGenerator<CheckpointTuple> {\n // eslint-disable-next-line prefer-const\n let { before, limit, filter } = options ?? {};\n const threadIds = config.configurable?.thread_id\n ? [config.configurable?.thread_id]\n : Object.keys(this.storage);\n const configCheckpointNamespace = config.configurable?.checkpoint_ns;\n const configCheckpointId = config.configurable?.checkpoint_id;\n\n for (const threadId of threadIds) {\n for (const checkpointNamespace of Object.keys(\n this.storage[threadId] ?? {}\n )) {\n if (\n configCheckpointNamespace !== undefined &&\n checkpointNamespace !== configCheckpointNamespace\n ) {\n continue;\n }\n const checkpoints = this.storage[threadId]?.[checkpointNamespace] ?? {};\n const sortedCheckpoints = Object.entries(checkpoints).sort((a, b) =>\n b[0].localeCompare(a[0])\n );\n\n for (const [\n checkpointId,\n [checkpoint, metadataStr, parentCheckpointId],\n ] of sortedCheckpoints) {\n // Filter by checkpoint ID from config\n if (configCheckpointId && checkpointId !== configCheckpointId) {\n continue;\n }\n\n // Filter by checkpoint ID from before config\n if (\n before &&\n before.configurable?.checkpoint_id &&\n checkpointId >= before.configurable.checkpoint_id\n ) {\n continue;\n }\n\n // Parse metadata\n const metadata = (await this.serde.loadsTyped(\n \"json\",\n metadataStr\n )) as CheckpointMetadata;\n\n if (\n filter &&\n !Object.entries(filter).every(\n ([key, value]) =>\n (metadata as unknown as Record<string, unknown>)[key] === value\n )\n ) {\n continue;\n }\n\n // Limit search results\n if (limit !== undefined) {\n if (limit <= 0) break;\n limit -= 1;\n }\n\n const key = _generateKey(threadId, checkpointNamespace, checkpointId);\n const writes = Object.values(this.writes[key] || {});\n\n const pendingWrites: CheckpointPendingWrite[] = await Promise.all(\n writes.map(async ([taskId, channel, value]) => {\n return [\n taskId,\n channel,\n await this.serde.loadsTyped(\"json\", value),\n ];\n })\n );\n\n const deserializedCheckpoint = await this.serde.loadsTyped(\n \"json\",\n checkpoint\n );\n\n if (\n deserializedCheckpoint.v < 4 &&\n parentCheckpointId !== undefined\n ) {\n await this._migratePendingSends(\n deserializedCheckpoint,\n threadId,\n checkpointNamespace,\n parentCheckpointId\n );\n }\n\n const checkpointTuple: CheckpointTuple = {\n config: {\n configurable: {\n thread_id: threadId,\n checkpoint_ns: checkpointNamespace,\n checkpoint_id: checkpointId,\n },\n },\n checkpoint: deserializedCheckpoint,\n metadata,\n pendingWrites,\n };\n if (parentCheckpointId !== undefined) {\n checkpointTuple.parentConfig = {\n configurable: {\n thread_id: threadId,\n checkpoint_ns: checkpointNamespace,\n checkpoint_id: parentCheckpointId,\n },\n };\n }\n yield checkpointTuple;\n }\n }\n }\n }\n\n async put(\n config: RunnableConfig,\n checkpoint: Checkpoint,\n metadata: CheckpointMetadata\n ): Promise<RunnableConfig> {\n const preparedCheckpoint: Partial<Checkpoint> = copyCheckpoint(checkpoint);\n const threadId = config.configurable?.thread_id;\n const checkpointNamespace = config.configurable?.checkpoint_ns ?? \"\";\n if (threadId === undefined) {\n throw new Error(\n `Failed to put checkpoint. The passed RunnableConfig is missing a required \"thread_id\" field in its \"configurable\" property.`\n );\n }\n\n if (!this.storage[threadId]) {\n this.storage[threadId] = {};\n }\n if (!this.storage[threadId][checkpointNamespace]) {\n this.storage[threadId][checkpointNamespace] = {};\n }\n\n const [[, serializedCheckpoint], [, serializedMetadata]] =\n await Promise.all([\n this.serde.dumpsTyped(preparedCheckpoint),\n this.serde.dumpsTyped(metadata),\n ]);\n\n this.storage[threadId][checkpointNamespace][checkpoint.id] = [\n serializedCheckpoint,\n serializedMetadata,\n config.configurable?.checkpoint_id, // parent\n ];\n\n return {\n configurable: {\n thread_id: threadId,\n checkpoint_ns: checkpointNamespace,\n checkpoint_id: checkpoint.id,\n },\n };\n }\n\n async putWrites(\n config: RunnableConfig,\n writes: PendingWrite[],\n taskId: string\n ): Promise<void> {\n const threadId = config.configurable?.thread_id;\n const checkpointNamespace = config.configurable?.checkpoint_ns;\n const checkpointId = config.configurable?.checkpoint_id;\n if (threadId === undefined) {\n throw new Error(\n `Failed to put writes. The passed RunnableConfig is missing a required \"thread_id\" field in its \"configurable\" property`\n );\n }\n if (checkpointId === undefined) {\n throw new Error(\n `Failed to put writes. The passed RunnableConfig is missing a required \"checkpoint_id\" field in its \"configurable\" property.`\n );\n }\n const outerKey = _generateKey(threadId, checkpointNamespace, checkpointId);\n const outerWrites_ = this.writes[outerKey];\n if (this.writes[outerKey] === undefined) {\n this.writes[outerKey] = {};\n }\n\n await Promise.all(\n writes.map(async ([channel, value], idx) => {\n const [, serializedValue] = await this.serde.dumpsTyped(value);\n const innerKey: [string, number] = [\n taskId,\n WRITES_IDX_MAP[channel] || idx,\n ];\n const innerKeyStr = `${innerKey[0]},${innerKey[1]}`;\n if (innerKey[1] >= 0 && outerWrites_ && innerKeyStr in outerWrites_) {\n return;\n }\n this.writes[outerKey][innerKeyStr] = [taskId, channel, serializedValue];\n })\n );\n }\n\n async deleteThread(threadId: string): Promise<void> {\n delete this.storage[threadId];\n for (const key of Object.keys(this.writes)) {\n if (_parseKey(key).threadId === threadId) delete this.writes[key];\n }\n }\n}\n"],"mappings":";;;AAmBA,SAAS,aACP,UACA,qBACA,cACA;AACA,QAAO,KAAK,UAAU;EAAC;EAAU;EAAqB;EAAa,CAAC;;AAGtE,SAAS,UAAU,KAAa;CAC9B,MAAM,CAAC,UAAU,qBAAqB,gBAAgB,KAAK,MAAM,IAAI;AACrE,QAAO;EAAE;EAAU;EAAqB;EAAc;;AAGxD,IAAa,cAAb,cAAiC,oBAAoB;CAEnD,UAGI,EAAE;CAEN,SAAuE,EAAE;CAEzE,YAAY,OAA4B;AACtC,QAAM,MAAM;;;CAId,MAAM,qBACJ,mBACA,UACA,cACA,oBACA;EACA,MAAM,4BAA4B;EAClC,MAAM,YAAY,aAAa,UAAU,cAAc,mBAAmB;EA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MAAM,cAAc,GAAG,SAAS,GAAG,GAAG,SAAS;AAC/C,OAAI,SAAS,MAAM,KAAK,gBAAgB,eAAe,aACrD;AAEF,QAAK,OAAO,UAAU,eAAe;IAAC;IAAQ;IAAS;IAAgB;IACvE,CACH;;CAGH,MAAM,aAAa,UAAiC;AAClD,SAAO,KAAK,QAAQ;AACpB,OAAK,MAAM,OAAO,OAAO,KAAK,KAAK,OAAO,CACxC,KAAI,UAAU,IAAI,CAAC,aAAa,SAAU,QAAO,KAAK,OAAO"}
//#region src/serde/base.d.ts
interface SerializerProtocol {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
dumpsTyped(data: any): Promise<[string, Uint8Array]>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
loadsTyped(type: string, data: Uint8Array | string): Promise<any>;

@@ -7,0 +5,0 @@ }

@@ -1,1 +0,1 @@

{"version":3,"file":"base.d.cts","names":["SerializerProtocol","Uint8Array","Promise"],"sources":["../../src/serde/base.d.ts"],"sourcesContent":["export interface SerializerProtocol {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n dumpsTyped(data: any): Promise<[string, Uint8Array]>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n loadsTyped(type: string, data: Uint8Array | string): Promise<any>;\n}\n"],"mappings":";UAAiBA,kBAAAA;EAAAA;EAAkB,UAAA,CAAA,IAAA,EAAA,GAAA,CAAA,EAERE,OAFQ,CAAA,CAAA,MAAA,EAESD,UAFT,CAAA,CAAA;;YAERC,CAAAA,IAAAA,EAAAA,MAAAA,EAAAA,IAAAA,EAEQD,UAFRC,GAAAA,MAAAA,CAAAA,EAE8BA,OAF9BA,CAAAA,GAAAA,CAAAA"}
{"version":3,"file":"base.d.cts","names":[],"sources":["../../src/serde/base.ts"],"mappings":";UAAiB,kBAAA;EAEf,UAAA,CAAW,IAAA,QAAY,OAAA,UAAiB,UAAA;EAExC,UAAA,CAAW,IAAA,UAAc,IAAA,EAAM,UAAA,YAAsB,OAAA;AAAA"}
//#region src/serde/base.d.ts
interface SerializerProtocol {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
dumpsTyped(data: any): Promise<[string, Uint8Array]>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
loadsTyped(type: string, data: Uint8Array | string): Promise<any>;

@@ -7,0 +5,0 @@ }

@@ -1,1 +0,1 @@

{"version":3,"file":"base.d.ts","names":["SerializerProtocol","Uint8Array","Promise"],"sources":["../../src/serde/base.d.ts"],"sourcesContent":["export interface SerializerProtocol {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n dumpsTyped(data: any): Promise<[string, Uint8Array]>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n loadsTyped(type: string, data: Uint8Array | string): Promise<any>;\n}\n"],"mappings":";UAAiBA,kBAAAA;EAAAA;EAAkB,UAAA,CAAA,IAAA,EAAA,GAAA,CAAA,EAERE,OAFQ,CAAA,CAAA,MAAA,EAESD,UAFT,CAAA,CAAA;;YAERC,CAAAA,IAAAA,EAAAA,MAAAA,EAAAA,IAAAA,EAEQD,UAFRC,GAAAA,MAAAA,CAAAA,EAE8BA,OAF9BA,CAAAA,GAAAA,CAAAA"}
{"version":3,"file":"base.d.ts","names":[],"sources":["../../src/serde/base.ts"],"mappings":";UAAiB,kBAAA;EAEf,UAAA,CAAW,IAAA,QAAY,OAAA,UAAiB,UAAA;EAExC,UAAA,CAAW,IAAA,UAAc,IAAA,EAAM,UAAA,YAAsB,OAAA;AAAA"}

@@ -1,5 +0,3 @@

const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
const require_index = require('./utils/fast-safe-stringify/index.cjs');
const __langchain_core_load = require_rolldown_runtime.__toESM(require("@langchain/core/load"));
const require_index = require("./utils/fast-safe-stringify/index.cjs");
let _langchain_core_load = require("@langchain/core/load");
//#region src/serde/jsonplus.ts

@@ -18,9 +16,7 @@ function isLangChainSerializedObject(value) {

async function _reviver(value) {
if (value && typeof value === "object") if (Array.isArray(value)) {
const revivedArray = await Promise.all(value.map((item) => _reviver(item)));
return revivedArray;
} else {
if (value && typeof value === "object") if (Array.isArray(value)) return await Promise.all(value.map((item) => _reviver(item)));
else {
const revivedObj = {};
for (const [k, v] of Object.entries(value)) revivedObj[k] = await _reviver(v);
if (revivedObj.lc === 2 && revivedObj.type === "undefined") return void 0;
if (revivedObj.lc === 2 && revivedObj.type === "undefined") return;
else if (revivedObj.lc === 2 && revivedObj.type === "constructor" && Array.isArray(revivedObj.id)) try {

@@ -42,2 +38,5 @@ const constructorName = revivedObj.id[revivedObj.id.length - 1];

break;
case "Uint8Array":
constructor = Uint8Array;
break;
default: return revivedObj;

@@ -50,3 +49,3 @@ }

}
else if (isLangChainSerializedObject(revivedObj)) return (0, __langchain_core_load.load)(JSON.stringify(revivedObj));
else if (isLangChainSerializedObject(revivedObj)) return (0, _langchain_core_load.load)(JSON.stringify(revivedObj));
return revivedObj;

@@ -78,2 +77,3 @@ }

};
else if (obj instanceof Uint8Array) return _encodeConstructorArgs(Uint8Array, "from", [Array.from(obj)]);
else return obj;

@@ -83,4 +83,3 @@ }

_dumps(obj) {
const encoder = new TextEncoder();
return encoder.encode(require_index.stringify(obj, (_, value) => {
return new TextEncoder().encode(require_index.stringify(obj, (_, value) => {
return _default(value);

@@ -94,4 +93,3 @@ }));

async _loads(data) {
const parsed = JSON.parse(data);
return _reviver(parsed);
return _reviver(JSON.parse(data));
}

@@ -104,5 +102,5 @@ async loadsTyped(type, data) {

};
//#endregion
exports.JsonPlusSerializer = JsonPlusSerializer;
//# sourceMappingURL=jsonplus.cjs.map

@@ -1,1 +0,1 @@

{"version":3,"file":"jsonplus.cjs","names":["revivedObj: any","constructor: any","stringify"],"sources":["../../src/serde/jsonplus.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable no-instanceof/no-instanceof */\nimport { load } from \"@langchain/core/load\";\nimport { SerializerProtocol } from \"./base.js\";\nimport { stringify } from \"./utils/fast-safe-stringify/index.js\";\n\nfunction isLangChainSerializedObject(value: Record<string, unknown>) {\n return (\n value !== null &&\n value.lc === 1 &&\n value.type === \"constructor\" &&\n Array.isArray(value.id)\n );\n}\n\n/**\n * The replacer in stringify does not allow delegation to built-in LangChain\n * serialization methods, and instead immediately calls `.toJSON()` and\n * continues to stringify subfields.\n *\n * We therefore must start from the most nested elements in the input and\n * deserialize upwards rather than top-down.\n */\nasync function _reviver(value: any): Promise<any> {\n if (value && typeof value === \"object\") {\n if (Array.isArray(value)) {\n const revivedArray = await Promise.all(\n value.map((item) => _reviver(item))\n );\n return revivedArray;\n } else {\n const revivedObj: any = {};\n for (const [k, v] of Object.entries(value)) {\n revivedObj[k] = await _reviver(v);\n }\n\n if (revivedObj.lc === 2 && revivedObj.type === \"undefined\") {\n return undefined;\n } else if (\n revivedObj.lc === 2 &&\n revivedObj.type === \"constructor\" &&\n Array.isArray(revivedObj.id)\n ) {\n try {\n const constructorName = revivedObj.id[revivedObj.id.length - 1];\n let constructor: any;\n\n switch (constructorName) {\n case \"Set\":\n constructor = Set;\n break;\n case \"Map\":\n constructor = Map;\n break;\n case \"RegExp\":\n constructor = RegExp;\n break;\n case \"Error\":\n constructor = Error;\n break;\n default:\n return revivedObj;\n }\n if (revivedObj.method) {\n return (constructor as any)[revivedObj.method](\n ...(revivedObj.args || [])\n );\n } else {\n return new (constructor as any)(...(revivedObj.args || []));\n }\n } catch (error) {\n return revivedObj;\n }\n } else if (isLangChainSerializedObject(revivedObj)) {\n return load(JSON.stringify(revivedObj));\n }\n\n return revivedObj;\n }\n }\n return value;\n}\n\nfunction _encodeConstructorArgs(\n // eslint-disable-next-line @typescript-eslint/ban-types\n constructor: Function,\n method?: string,\n args?: any[],\n kwargs?: Record<string, any>\n): object {\n return {\n lc: 2,\n type: \"constructor\",\n id: [constructor.name],\n method: method ?? null,\n args: args ?? [],\n kwargs: kwargs ?? {},\n };\n}\n\nfunction _default(obj: any): any {\n if (obj === undefined) {\n return {\n lc: 2,\n type: \"undefined\",\n };\n } else if (obj instanceof Set || obj instanceof Map) {\n return _encodeConstructorArgs(obj.constructor, undefined, [\n Array.from(obj),\n ]);\n } else if (obj instanceof RegExp) {\n return _encodeConstructorArgs(RegExp, undefined, [obj.source, obj.flags]);\n } else if (obj instanceof Error) {\n return _encodeConstructorArgs(obj.constructor, undefined, [obj.message]);\n // TODO: Remove special case\n } else if (obj?.lg_name === \"Send\") {\n return {\n node: obj.node,\n args: obj.args,\n };\n } else {\n return obj;\n }\n}\n\nexport class JsonPlusSerializer implements SerializerProtocol {\n protected _dumps(obj: any): Uint8Array {\n const encoder = new TextEncoder();\n return encoder.encode(\n stringify(obj, (_: string, value: any) => {\n return _default(value);\n })\n );\n }\n\n async dumpsTyped(obj: any): Promise<[string, Uint8Array]> {\n if (obj instanceof Uint8Array) {\n return [\"bytes\", obj];\n } else {\n return [\"json\", this._dumps(obj)];\n }\n }\n\n protected async _loads(data: string): Promise<any> {\n const parsed = JSON.parse(data);\n return _reviver(parsed);\n }\n\n async loadsTyped(type: string, data: Uint8Array | string): Promise<any> {\n if (type === \"bytes\") {\n return typeof data === \"string\" ? new TextEncoder().encode(data) : data;\n } else if (type === \"json\") {\n return this._loads(\n typeof data === \"string\" ? data : new TextDecoder().decode(data)\n );\n } else {\n throw new Error(`Unknown serialization type: ${type}`);\n }\n }\n}\n"],"mappings":";;;;;AAMA,SAAS,4BAA4B,OAAgC;AACnE,QACE,UAAU,QACV,MAAM,OAAO,KACb,MAAM,SAAS,iBACf,MAAM,QAAQ,MAAM;;;;;;;;;;AAYxB,eAAe,SAAS,OAA0B;AAChD,KAAI,SAAS,OAAO,UAAU,SAC5B,KAAI,MAAM,QAAQ,QAAQ;EACxB,MAAM,eAAe,MAAM,QAAQ,IACjC,MAAM,KAAK,SAAS,SAAS;AAE/B,SAAO;QACF;EACL,MAAMA,aAAkB;AACxB,OAAK,MAAM,CAAC,GAAG,MAAM,OAAO,QAAQ,OAClC,YAAW,KAAK,MAAM,SAAS;AAGjC,MAAI,WAAW,OAAO,KAAK,WAA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AI,eAAe,WACjB,QAAO,CAAC,SAAS;MAEjB,QAAO,CAAC,QAAQ,KAAK,OAAO;;CAIhC,MAAgB,OAAO,MAA4B;EACjD,MAAM,SAAS,KAAK,MAAM;AAC1B,SAAO,SAAS;;CAGlB,MAAM,WAAW,MAAc,MAAyC;AACtE,MAAI,SAAS,QACX,QAAO,OAAO,SAAS,WAAW,IAAI,cAAc,OAAO,QAAQ;WAC1D,SAAS,OAClB,QAAO,KAAK,OACV,OAAO,SAAS,WAAW,OAAO,IAAI,cAAc,OAAO;MAG7D,OAAM,IAAI,MAAM,+BAA+B"}
{"version":3,"file":"jsonplus.cjs","names":["stringify"],"sources":["../../src/serde/jsonplus.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable no-instanceof/no-instanceof */\nimport { load } from \"@langchain/core/load\";\nimport { SerializerProtocol } from \"./base.js\";\nimport { stringify } from \"./utils/fast-safe-stringify/index.js\";\n\nfunction isLangChainSerializedObject(value: Record<string, unknown>) {\n return (\n value !== null &&\n value.lc === 1 &&\n value.type === \"constructor\" &&\n Array.isArray(value.id)\n );\n}\n\n/**\n * The replacer in stringify does not allow delegation to built-in LangChain\n * serialization methods, and instead immediately calls `.toJSON()` and\n * continues to stringify subfields.\n *\n * We therefore must start from the most nested elements in the input and\n * deserialize upwards rather than top-down.\n */\nasync function _reviver(value: any): Promise<any> {\n if (value && typeof value === \"object\") {\n if (Array.isArray(value)) {\n const revivedArray = await Promise.all(\n value.map((item) => _reviver(item))\n );\n return revivedArray;\n } else {\n const revivedObj: any = {};\n for (const [k, v] of Object.entries(value)) {\n revivedObj[k] = await _reviver(v);\n }\n\n if (revivedObj.lc === 2 && revivedObj.type === \"undefined\") {\n return undefined;\n } else if (\n revivedObj.lc === 2 &&\n revivedObj.type === \"constructor\" &&\n Array.isArray(revivedObj.id)\n ) {\n try {\n const constructorName = revivedObj.id[revivedObj.id.length - 1];\n let constructor: any;\n\n switch (constructorName) {\n case \"Set\":\n constructor = Set;\n break;\n case \"Map\":\n constructor = Map;\n break;\n case \"RegExp\":\n constructor = RegExp;\n break;\n case \"Error\":\n constructor = Error;\n break;\n case \"Uint8Array\":\n constructor = Uint8Array;\n break;\n default:\n return revivedObj;\n }\n if (revivedObj.method) {\n return (constructor as any)[revivedObj.method](\n ...(revivedObj.args || [])\n );\n } else {\n return new (constructor as any)(...(revivedObj.args || []));\n }\n } catch (error) {\n return revivedObj;\n }\n } else if (isLangChainSerializedObject(revivedObj)) {\n return load(JSON.stringify(revivedObj));\n }\n\n return revivedObj;\n }\n }\n return value;\n}\n\nfunction _encodeConstructorArgs(\n // eslint-disable-next-line @typescript-eslint/ban-types\n constructor: Function,\n method?: string,\n args?: any[],\n kwargs?: Record<string, any>\n): object {\n return {\n lc: 2,\n type: \"constructor\",\n id: [constructor.name],\n method: method ?? null,\n args: args ?? [],\n kwargs: kwargs ?? {},\n };\n}\n\nfunction _default(obj: any): any {\n if (obj === undefined) {\n return {\n lc: 2,\n type: \"undefined\",\n };\n } else if (obj instanceof Set || obj instanceof Map) {\n return _encodeConstructorArgs(obj.constructor, undefined, [\n Array.from(obj),\n ]);\n } else if (obj instanceof RegExp) {\n return _encodeConstructorArgs(RegExp, undefined, [obj.source, obj.flags]);\n } else if (obj instanceof Error) {\n return _encodeConstructorArgs(obj.constructor, undefined, [obj.message]);\n // TODO: Remove special case\n } else if (obj?.lg_name === \"Send\") {\n return {\n node: obj.node,\n args: obj.args,\n };\n } else if (obj instanceof Uint8Array) {\n return _encodeConstructorArgs(Uint8Array, \"from\", [Array.from(obj)]);\n } else {\n return obj;\n }\n}\n\nexport class JsonPlusSerializer implements SerializerProtocol {\n protected _dumps(obj: any): Uint8Array {\n const encoder = new TextEncoder();\n return encoder.encode(\n stringify(obj, (_: string, value: any) => {\n return _default(value);\n })\n );\n }\n\n async dumpsTyped(obj: any): Promise<[string, Uint8Array]> {\n if (obj instanceof Uint8Array) {\n return [\"bytes\", obj];\n } else {\n return [\"json\", this._dumps(obj)];\n }\n }\n\n protected async _loads(data: string): Promise<any> {\n const parsed = JSON.parse(data);\n return _reviver(parsed);\n }\n\n async loadsTyped(type: string, data: Uint8Array | string): Promise<any> {\n if (type === \"bytes\") {\n return typeof data === \"string\" ? new TextEncoder().encode(data) : data;\n } else if (type === \"json\") {\n return this._loads(\n typeof data === \"string\" ? data : new TextDecoder().decode(data)\n );\n } else {\n throw new Error(`Unknown serialization type: ${type}`);\n }\n }\n}\n"],"mappings":";;;AAMA,SAAS,4BAA4B,OAAgC;AACnE,QACE,UAAU,QACV,MAAM,OAAO,KACb,MAAM,SAAS,iBACf,MAAM,QAAQ,MAAM,GAAG;;;;;;;;;;AAY3B,eAAe,SAAS,OAA0B;AAChD,KAAI,SAAS,OAAO,UAAU,SAC5B,KAAI,MAAM,QAAQ,MAAM,CAItB,QAHqB,MAAM,QAAQ,IACjC,MAAM,KAAK,SAAS,SAAS,KAAK,CAAC,CACpC;MAEI;EACL,MAAM,aAAkB,EAAE;AAC1B,OAAK,MAAM,CAAC,GAAG,MAAM,OAAO,QAAQ,MAAM,CACxC,YAAW,KAAK,MAAM,SAAS,EAAE;AAGnC,MAAI,WAAW,OAAO,KAAK,WAAW,SAAS,YAC7C;WAEA,WAAW,OAAO,KAClB,WAAW,SAAS,iBACpB,MAAM,QAAQ,WAAW,GAAG,CAE5B,KAAI;GACF,MAAM,kBAAkB,WAAW,GAAG,WAAW,GAAG,SAAS;GAC7D,IAAI;AAEJ,WAAQ,iBAAR;IACE,KAAK;AACH,mBAAc;AACd;IACF,KAAK;AACH,mBAAc;AACd;IACF,KAAK;AACH,mBAAc;AACd;IACF,KAAK;AACH,mBAAc;AACd;IACF,KAAK;AACH,mBAAc;AACd;IACF,QACE,QAAO;;AAEX,OAAI,WAAW,OACb,QAAQ,YAAoB,WAAW,QACrC,GAAI,WAAW,QAAQ,EAAE,CAC1B;OAED,QAAO,IAAK,YAAoB,GAAI,WAAW,QAAQ,EAAE,CAAE;WAEtD,OAAO;AACd,UA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,SAAS,WAAW,IAAI,aAAa,CAAC,OAAO,KAAK,GAAG;WAC1D,SAAS,OAClB,QAAO,KAAK,OACV,OAAO,SAAS,WAAW,OAAO,IAAI,aAAa,CAAC,OAAO,KAAK,CACjE;MAED,OAAM,IAAI,MAAM,+BAA+B,OAAO"}
import { stringify } from "./utils/fast-safe-stringify/index.js";
import { load } from "@langchain/core/load";
//#region src/serde/jsonplus.ts

@@ -17,9 +16,7 @@ function isLangChainSerializedObject(value) {

async function _reviver(value) {
if (value && typeof value === "object") if (Array.isArray(value)) {
const revivedArray = await Promise.all(value.map((item) => _reviver(item)));
return revivedArray;
} else {
if (value && typeof value === "object") if (Array.isArray(value)) return await Promise.all(value.map((item) => _reviver(item)));
else {
const revivedObj = {};
for (const [k, v] of Object.entries(value)) revivedObj[k] = await _reviver(v);
if (revivedObj.lc === 2 && revivedObj.type === "undefined") return void 0;
if (revivedObj.lc === 2 && revivedObj.type === "undefined") return;
else if (revivedObj.lc === 2 && revivedObj.type === "constructor" && Array.isArray(revivedObj.id)) try {

@@ -41,2 +38,5 @@ const constructorName = revivedObj.id[revivedObj.id.length - 1];

break;
case "Uint8Array":
constructor = Uint8Array;
break;
default: return revivedObj;

@@ -76,2 +76,3 @@ }

};
else if (obj instanceof Uint8Array) return _encodeConstructorArgs(Uint8Array, "from", [Array.from(obj)]);
else return obj;

@@ -81,4 +82,3 @@ }

_dumps(obj) {
const encoder = new TextEncoder();
return encoder.encode(stringify(obj, (_, value) => {
return new TextEncoder().encode(stringify(obj, (_, value) => {
return _default(value);

@@ -92,4 +92,3 @@ }));

async _loads(data) {
const parsed = JSON.parse(data);
return _reviver(parsed);
return _reviver(JSON.parse(data));
}

@@ -102,5 +101,5 @@ async loadsTyped(type, data) {

};
//#endregion
export { JsonPlusSerializer };
//# sourceMappingURL=jsonplus.js.map

@@ -1,1 +0,1 @@

{"version":3,"file":"jsonplus.js","names":["revivedObj: any","constructor: any"],"sources":["../../src/serde/jsonplus.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable no-instanceof/no-instanceof */\nimport { load } from \"@langchain/core/load\";\nimport { SerializerProtocol } from \"./base.js\";\nimport { stringify } from \"./utils/fast-safe-stringify/index.js\";\n\nfunction isLangChainSerializedObject(value: Record<string, unknown>) {\n return (\n value !== null &&\n value.lc === 1 &&\n value.type === \"constructor\" &&\n Array.isArray(value.id)\n );\n}\n\n/**\n * The replacer in stringify does not allow delegation to built-in LangChain\n * serialization methods, and instead immediately calls `.toJSON()` and\n * continues to stringify subfields.\n *\n * We therefore must start from the most nested elements in the input and\n * deserialize upwards rather than top-down.\n */\nasync function _reviver(value: any): Promise<any> {\n if (value && typeof value === \"object\") {\n if (Array.isArray(value)) {\n const revivedArray = await Promise.all(\n value.map((item) => _reviver(item))\n );\n return revivedArray;\n } else {\n const revivedObj: any = {};\n for (const [k, v] of Object.entries(value)) {\n revivedObj[k] = await _reviver(v);\n }\n\n if (revivedObj.lc === 2 && revivedObj.type === \"undefined\") {\n return undefined;\n } else if (\n revivedObj.lc === 2 &&\n revivedObj.type === \"constructor\" &&\n Array.isArray(revivedObj.id)\n ) {\n try {\n const constructorName = revivedObj.id[revivedObj.id.length - 1];\n let constructor: any;\n\n switch (constructorName) {\n case \"Set\":\n constructor = Set;\n break;\n case \"Map\":\n constructor = Map;\n break;\n case \"RegExp\":\n constructor = RegExp;\n break;\n case \"Error\":\n constructor = Error;\n break;\n default:\n return revivedObj;\n }\n if (revivedObj.method) {\n return (constructor as any)[revivedObj.method](\n ...(revivedObj.args || [])\n );\n } else {\n return new (constructor as any)(...(revivedObj.args || []));\n }\n } catch (error) {\n return revivedObj;\n }\n } else if (isLangChainSerializedObject(revivedObj)) {\n return load(JSON.stringify(revivedObj));\n }\n\n return revivedObj;\n }\n }\n return value;\n}\n\nfunction _encodeConstructorArgs(\n // eslint-disable-next-line @typescript-eslint/ban-types\n constructor: Function,\n method?: string,\n args?: any[],\n kwargs?: Record<string, any>\n): object {\n return {\n lc: 2,\n type: \"constructor\",\n id: [constructor.name],\n method: method ?? null,\n args: args ?? [],\n kwargs: kwargs ?? {},\n };\n}\n\nfunction _default(obj: any): any {\n if (obj === undefined) {\n return {\n lc: 2,\n type: \"undefined\",\n };\n } else if (obj instanceof Set || obj instanceof Map) {\n return _encodeConstructorArgs(obj.constructor, undefined, [\n Array.from(obj),\n ]);\n } else if (obj instanceof RegExp) {\n return _encodeConstructorArgs(RegExp, undefined, [obj.source, obj.flags]);\n } else if (obj instanceof Error) {\n return _encodeConstructorArgs(obj.constructor, undefined, [obj.message]);\n // TODO: Remove special case\n } else if (obj?.lg_name === \"Send\") {\n return {\n node: obj.node,\n args: obj.args,\n };\n } else {\n return obj;\n }\n}\n\nexport class JsonPlusSerializer implements SerializerProtocol {\n protected _dumps(obj: any): Uint8Array {\n const encoder = new TextEncoder();\n return encoder.encode(\n stringify(obj, (_: string, value: any) => {\n return _default(value);\n })\n );\n }\n\n async dumpsTyped(obj: any): Promise<[string, Uint8Array]> {\n if (obj instanceof Uint8Array) {\n return [\"bytes\", obj];\n } else {\n return [\"json\", this._dumps(obj)];\n }\n }\n\n protected async _loads(data: string): Promise<any> {\n const parsed = JSON.parse(data);\n return _reviver(parsed);\n }\n\n async loadsTyped(type: string, data: Uint8Array | string): Promise<any> {\n if (type === \"bytes\") {\n return typeof data === \"string\" ? new TextEncoder().encode(data) : data;\n } else if (type === \"json\") {\n return this._loads(\n typeof data === \"string\" ? data : new TextDecoder().decode(data)\n );\n } else {\n throw new Error(`Unknown serialization type: ${type}`);\n }\n }\n}\n"],"mappings":";;;;AAMA,SAAS,4BAA4B,OAAgC;AACnE,QACE,UAAU,QACV,MAAM,OAAO,KACb,MAAM,SAAS,iBACf,MAAM,QAAQ,MAAM;;;;;;;;;;AAYxB,eAAe,SAAS,OAA0B;AAChD,KAAI,SAAS,OAAO,UAAU,SAC5B,KAAI,MAAM,QAAQ,QAAQ;EACxB,MAAM,eAAe,MAAM,QAAQ,IACjC,MAAM,KAA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qBAAb,MAA8D;CAC5D,AAAU,OAAO,KAAsB;EACrC,MAAM,UAAU,IAAI;AACpB,SAAO,QAAQ,OACb,UAAU,MAAM,GAAW,UAAe;AACxC,UAAO,SAAS;;;CAKtB,MAAM,WAAW,KAAyC;AACxD,MAAI,eAAe,WACjB,QAAO,CAAC,SAAS;MAEjB,QAAO,CAAC,QAAQ,KAAK,OAAO;;CAIhC,MAAgB,OAAO,MAA4B;EACjD,MAAM,SAAS,KAAK,MAAM;AAC1B,SAAO,SAAS;;CAGlB,MAAM,WAAW,MAAc,MAAyC;AACtE,MAAI,SAAS,QACX,QAAO,OAAO,SAAS,WAAW,IAAI,cAAc,OAAO,QAAQ;WAC1D,SAAS,OAClB,QAAO,KAAK,OACV,OAAO,SAAS,WAAW,OAAO,IAAI,cAAc,OAAO;MAG7D,OAAM,IAAI,MAAM,+BAA+B"}
{"version":3,"file":"jsonplus.js","names":[],"sources":["../../src/serde/jsonplus.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable no-instanceof/no-instanceof */\nimport { load } from \"@langchain/core/load\";\nimport { SerializerProtocol } from \"./base.js\";\nimport { stringify } from \"./utils/fast-safe-stringify/index.js\";\n\nfunction isLangChainSerializedObject(value: Record<string, unknown>) {\n return (\n value !== null &&\n value.lc === 1 &&\n value.type === \"constructor\" &&\n Array.isArray(value.id)\n );\n}\n\n/**\n * The replacer in stringify does not allow delegation to built-in LangChain\n * serialization methods, and instead immediately calls `.toJSON()` and\n * continues to stringify subfields.\n *\n * We therefore must start from the most nested elements in the input and\n * deserialize upwards rather than top-down.\n */\nasync function _reviver(value: any): Promise<any> {\n if (value && typeof value === \"object\") {\n if (Array.isArray(value)) {\n const revivedArray = await Promise.all(\n value.map((item) => _reviver(item))\n );\n return revivedArray;\n } else {\n const revivedObj: any = {};\n for (const [k, v] of Object.entries(value)) {\n revivedObj[k] = await _reviver(v);\n }\n\n if (revivedObj.lc === 2 && revivedObj.type === \"undefined\") {\n return undefined;\n } else if (\n revivedObj.lc === 2 &&\n revivedObj.type === \"constructor\" &&\n Array.isArray(revivedObj.id)\n ) {\n try {\n const constructorName = revivedObj.id[revivedObj.id.length - 1];\n let constructor: any;\n\n switch (constructorName) {\n case \"Set\":\n constructor = Set;\n break;\n case \"Map\":\n constructor = Map;\n break;\n case \"RegExp\":\n constructor = RegExp;\n break;\n case \"Error\":\n constructor = Error;\n break;\n case \"Uint8Array\":\n constructor = Uint8Array;\n break;\n default:\n return revivedObj;\n }\n if (revivedObj.method) {\n return (constructor as any)[revivedObj.method](\n ...(revivedObj.args || [])\n );\n } else {\n return new (constructor as any)(...(revivedObj.args || []));\n }\n } catch (error) {\n return revivedObj;\n }\n } else if (isLangChainSerializedObject(revivedObj)) {\n return load(JSON.stringify(revivedObj));\n }\n\n return revivedObj;\n }\n }\n return value;\n}\n\nfunction _encodeConstructorArgs(\n // eslint-disable-next-line @typescript-eslint/ban-types\n constructor: Function,\n method?: string,\n args?: any[],\n kwargs?: Record<string, any>\n): object {\n return {\n lc: 2,\n type: \"constructor\",\n id: [constructor.name],\n method: method ?? null,\n args: args ?? [],\n kwargs: kwargs ?? {},\n };\n}\n\nfunction _default(obj: any): any {\n if (obj === undefined) {\n return {\n lc: 2,\n type: \"undefined\",\n };\n } else if (obj instanceof Set || obj instanceof Map) {\n return _encodeConstructorArgs(obj.constructor, undefined, [\n Array.from(obj),\n ]);\n } else if (obj instanceof RegExp) {\n return _encodeConstructorArgs(RegExp, undefined, [obj.source, obj.flags]);\n } else if (obj instanceof Error) {\n return _encodeConstructorArgs(obj.constructor, undefined, [obj.message]);\n // TODO: Remove special case\n } else if (obj?.lg_name === \"Send\") {\n return {\n node: obj.node,\n args: obj.args,\n };\n } else if (obj instanceof Uint8Array) {\n return _encodeConstructorArgs(Uint8Array, \"from\", [Array.from(obj)]);\n } else {\n return obj;\n }\n}\n\nexport class JsonPlusSerializer implements SerializerProtocol {\n protected _dumps(obj: any): Uint8Array {\n const encoder = new TextEncoder();\n return encoder.encode(\n stringify(obj, (_: string, value: any) => {\n return _default(value);\n })\n );\n }\n\n async dumpsTyped(obj: any): Promise<[string, Uint8Array]> {\n if (obj instanceof Uint8Array) {\n return [\"bytes\", obj];\n } else {\n return [\"json\", this._dumps(obj)];\n }\n }\n\n protected async _loads(data: string): Promise<any> {\n const parsed = JSON.parse(data);\n return _reviver(parsed);\n }\n\n async loadsTyped(type: string, data: Uint8Array | string): Promise<any> {\n if (type === \"bytes\") {\n return typeof data === \"string\" ? new TextEncoder().encode(data) : data;\n } else if (type === \"json\") {\n return this._loads(\n typeof data === \"string\" ? data : new TextDecoder().decode(data)\n );\n } else {\n throw new Error(`Unknown serialization type: ${type}`);\n }\n }\n}\n"],"mappings":";;;AAMA,SAAS,4BAA4B,OAAgC;AACnE,QACE,UAAU,QACV,MAAM,OAAO,KACb,MAAM,SAAS,iBACf,MAAM,QAAQ,MAAM,GAAG;;;;;;;;;;AAY3B,eAAe,SAAS,OAA0B;AAChD,KAAI,SAAS,OAAO,UAAU,SAC5B,KAAI,MAAM,QAAQ,MAAM,CAItB,QAHqB,MAAM,QAAQ,IACjC,MAAM,KAAK,SAAS,SAAS,KAAK,CAAC,CACpC;MAEI;EACL,MAAM,aAAkB,EAAE;AAC1B,OAAK,MAAM,CAAC,GAAG,MAAM,OAAO,QAAQ,MAAM,CACxC,YAAW,KAAK,MAAM,SAAS,EAAE;AAGnC,MAAI,WAAW,OAAO,KAAK,WAAW,SAAS,YAC7C;WAEA,WAAW,OAAO,KAClB,WAAW,SAAS,iBACpB,MAAM,QAAQ,WAAW,GAAG,CAE5B,KAAI;GACF,MAAM,kBAAkB,WAAW,GAAG,WAAW,GAAG,SAAS;GAC7D,IAAI;AAEJ,WAAQ,iBAAR;IACE,KAAK;AACH,mBAAc;AACd;IACF,KAAK;AACH,mBAAc;AACd;IACF,KAAK;AACH,mBAAc;AACd;IACF,KAAK;AACH,mBAAc;AACd;IACF,KAAK;AACH,mBAAc;AACd;IACF,QACE,QAA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;;CAIrC,MAAgB,OAAO,MAA4B;AAEjD,SAAO,SADQ,KAAK,MAAM,KAAK,CACR;;CAGzB,MAAM,WAAW,MAAc,MAAyC;AACtE,MAAI,SAAS,QACX,QAAO,OAAO,SAAS,WAAW,IAAI,aAAa,CAAC,OAAO,KAAK,GAAG;WAC1D,SAAS,OAClB,QAAO,KAAK,OACV,OAAO,SAAS,WAAW,OAAO,IAAI,aAAa,CAAC,OAAO,KAAK,CACjE;MAED,OAAM,IAAI,MAAM,+BAA+B,OAAO"}

@@ -1,2 +0,1 @@

//#region src/serde/types.ts

@@ -8,3 +7,2 @@ const TASKS = "__pregel_tasks";

const RESUME = "__resume__";
//#endregion

@@ -16,2 +14,3 @@ exports.ERROR = ERROR;

exports.TASKS = TASKS;
//# sourceMappingURL=types.cjs.map

@@ -1,1 +0,1 @@

{"version":3,"file":"types.cjs","names":[],"sources":["../../src/serde/types.ts"],"sourcesContent":["export const TASKS = \"__pregel_tasks\";\nexport const ERROR = \"__error__\";\nexport const SCHEDULED = \"__scheduled__\";\nexport const INTERRUPT = \"__interrupt__\";\nexport const RESUME = \"__resume__\";\n\n// Mirrors BaseChannel in \"@langchain/langgraph\"\nexport interface ChannelProtocol<\n ValueType = unknown,\n UpdateType = unknown,\n CheckpointType = unknown\n> {\n ValueType: ValueType;\n\n UpdateType: UpdateType;\n\n /**\n * The name of the channel.\n */\n lc_graph_name: string;\n\n /**\n * Return a new identical channel, optionally initialized from a checkpoint.\n * Can be thought of as a \"restoration\" from a checkpoint which is a \"snapshot\" of the channel's state.\n *\n * @param {CheckpointType | undefined} checkpoint\n * @returns {this}\n */\n fromCheckpoint(checkpoint?: CheckpointType): this;\n\n /**\n * Update the channel's value with the given sequence of updates.\n * The order of the updates in the sequence is arbitrary.\n *\n * @throws {InvalidUpdateError} if the sequence of updates is invalid.\n * @param {Array<UpdateType>} values\n * @returns {void}\n */\n update(values: UpdateType[]): void;\n\n /**\n * Return the current value of the channel.\n *\n * @throws {EmptyChannelError} if the channel is empty (never updated yet).\n * @returns {ValueType}\n */\n get(): ValueType;\n\n /**\n * Return a string representation of the channel's current state.\n *\n * @throws {EmptyChannelError} if the channel is empty (never updated yet), or doesn't support checkpoints.\n * @returns {CheckpointType | undefined}\n */\n checkpoint(): CheckpointType | undefined;\n}\n\n// Mirrors SendInterface in \"@langchain/langgraph\"\nexport interface SendProtocol {\n node: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n args: any;\n}\n"],"mappings":";;AAAA,MAAa,QAAQ;AACrB,MAAa,QAAQ;AACrB,MAAa,YAAY;AACzB,MAAa,YAAY;AACzB,MAAa,SAAS"}
{"version":3,"file":"types.cjs","names":[],"sources":["../../src/serde/types.ts"],"sourcesContent":["export const TASKS = \"__pregel_tasks\";\nexport const ERROR = \"__error__\";\nexport const SCHEDULED = \"__scheduled__\";\nexport const INTERRUPT = \"__interrupt__\";\nexport const RESUME = \"__resume__\";\n\n// Mirrors BaseChannel in \"@langchain/langgraph\"\nexport interface ChannelProtocol<\n ValueType = unknown,\n UpdateType = unknown,\n CheckpointType = unknown\n> {\n ValueType: ValueType;\n\n UpdateType: UpdateType;\n\n /**\n * The name of the channel.\n */\n lc_graph_name: string;\n\n /**\n * Return a new identical channel, optionally initialized from a checkpoint.\n * Can be thought of as a \"restoration\" from a checkpoint which is a \"snapshot\" of the channel's state.\n *\n * @param {CheckpointType | undefined} checkpoint\n * @returns {this}\n */\n fromCheckpoint(checkpoint?: CheckpointType): this;\n\n /**\n * Update the channel's value with the given sequence of updates.\n * The order of the updates in the sequence is arbitrary.\n *\n * @throws {InvalidUpdateError} if the sequence of updates is invalid.\n * @param {Array<UpdateType>} values\n * @returns {void}\n */\n update(values: UpdateType[]): void;\n\n /**\n * Return the current value of the channel.\n *\n * @throws {EmptyChannelError} if the channel is empty (never updated yet).\n * @returns {ValueType}\n */\n get(): ValueType;\n\n /**\n * Return a string representation of the channel's current state.\n *\n * @throws {EmptyChannelError} if the channel is empty (never updated yet), or doesn't support checkpoints.\n * @returns {CheckpointType | undefined}\n */\n checkpoint(): CheckpointType | undefined;\n}\n\n// Mirrors SendInterface in \"@langchain/langgraph\"\nexport interface SendProtocol {\n node: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n args: any;\n}\n"],"mappings":";AAAA,MAAa,QAAQ;AACrB,MAAa,QAAQ;AACrB,MAAa,YAAY;AACzB,MAAa,YAAY;AACzB,MAAa,SAAS"}

@@ -7,3 +7,2 @@ //#region src/serde/types.d.ts

declare const RESUME = "__resume__";
// Mirrors BaseChannel in "@langchain/langgraph"
interface ChannelProtocol<ValueType = unknown, UpdateType = unknown, CheckpointType = unknown> {

@@ -48,6 +47,4 @@ ValueType: ValueType;

}
// Mirrors SendInterface in "@langchain/langgraph"
interface SendProtocol {
node: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
args: any;

@@ -54,0 +51,0 @@ }

@@ -1,1 +0,1 @@

{"version":3,"file":"types.d.cts","names":["TASKS","ERROR","SCHEDULED","INTERRUPT","RESUME","ChannelProtocol","ValueType","UpdateType","CheckpointType","SendProtocol"],"sources":["../../src/serde/types.d.ts"],"sourcesContent":["export declare const TASKS = \"__pregel_tasks\";\nexport declare const ERROR = \"__error__\";\nexport declare const SCHEDULED = \"__scheduled__\";\nexport declare const INTERRUPT = \"__interrupt__\";\nexport declare const RESUME = \"__resume__\";\n// Mirrors BaseChannel in \"@langchain/langgraph\"\nexport interface ChannelProtocol<ValueType = unknown, UpdateType = unknown, CheckpointType = unknown> {\n ValueType: ValueType;\n UpdateType: UpdateType;\n /**\n * The name of the channel.\n */\n lc_graph_name: string;\n /**\n * Return a new identical channel, optionally initialized from a checkpoint.\n * Can be thought of as a \"restoration\" from a checkpoint which is a \"snapshot\" of the channel's state.\n *\n * @param {CheckpointType | undefined} checkpoint\n * @returns {this}\n */\n fromCheckpoint(checkpoint?: CheckpointType): this;\n /**\n * Update the channel's value with the given sequence of updates.\n * The order of the updates in the sequence is arbitrary.\n *\n * @throws {InvalidUpdateError} if the sequence of updates is invalid.\n * @param {Array<UpdateType>} values\n * @returns {void}\n */\n update(values: UpdateType[]): void;\n /**\n * Return the current value of the channel.\n *\n * @throws {EmptyChannelError} if the channel is empty (never updated yet).\n * @returns {ValueType}\n */\n get(): ValueType;\n /**\n * Return a string representation of the channel's current state.\n *\n * @throws {EmptyChannelError} if the channel is empty (never updated yet), or doesn't support checkpoints.\n * @returns {CheckpointType | undefined}\n */\n checkpoint(): CheckpointType | undefined;\n}\n// Mirrors SendInterface in \"@langchain/langgraph\"\nexport interface SendProtocol {\n node: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n args: any;\n}\n"],"mappings":";cAAqBA,KAAAA;AAAAA,cACAC,KAAAA,GADK,WAAA;AACLA,cACAC,SAAAA,GADK,eAAA;AACLA,cACAC,SAAAA,GADS,eAAA;AACTA,cACAC,MAAAA,GADS,YAAA;AAC9B;AAEiBC,UAAAA,eAAe,CAAA,YAAA,OAAA,EAAA,aAAA,OAAA,EAAA,iBAAA,OAAA,CAAA,CAAA;EAAA,SAAA,EACjBC,SADiB;YACjBA,EACCC,UADDD;;;;eA6BJA,EAAAA,MAAAA;;;AAUX;;;;;8BA1BgCE;;;;;;;;;iBASbD;;;;;;;SAORD;;;;;;;gBAOOE;;;UAGDC,YAAAA"}
{"version":3,"file":"types.d.cts","names":[],"sources":["../../src/serde/types.ts"],"mappings":";cAAa,KAAA;AAAA,cACA,KAAA;AAAA,cACA,SAAA;AAAA,cACA,SAAA;AAAA,cACA,MAAA;AAAA,UAGI,eAAA;EAKf,SAAA,EAAW,SAAA;EAEX,UAAA,EAAY,UAAA;;;;EAKZ,aAAA;EAjBoB;;;;AACtB;;;EAyBE,cAAA,CAAe,UAAA,GAAa,cAAA;EAzBR;AACtB;;;;;AAGA;;EA+BE,MAAA,CAAO,MAAA,EAAQ,UAAA;EA1BJ;;;;;;EAkCX,GAAA,IAAO,SAAA;EAQqB;;;;;;EAA5B,UAAA,IAAc,cAAA;AAAA;AAAA,UAIC,YAAA;EACf,IAAA;EAEA,IAAA;AAAA"}

@@ -7,3 +7,2 @@ //#region src/serde/types.d.ts

declare const RESUME = "__resume__";
// Mirrors BaseChannel in "@langchain/langgraph"
interface ChannelProtocol<ValueType = unknown, UpdateType = unknown, CheckpointType = unknown> {

@@ -48,6 +47,4 @@ ValueType: ValueType;

}
// Mirrors SendInterface in "@langchain/langgraph"
interface SendProtocol {
node: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
args: any;

@@ -54,0 +51,0 @@ }

@@ -1,1 +0,1 @@

{"version":3,"file":"types.d.ts","names":["TASKS","ERROR","SCHEDULED","INTERRUPT","RESUME","ChannelProtocol","ValueType","UpdateType","CheckpointType","SendProtocol"],"sources":["../../src/serde/types.d.ts"],"sourcesContent":["export declare const TASKS = \"__pregel_tasks\";\nexport declare const ERROR = \"__error__\";\nexport declare const SCHEDULED = \"__scheduled__\";\nexport declare const INTERRUPT = \"__interrupt__\";\nexport declare const RESUME = \"__resume__\";\n// Mirrors BaseChannel in \"@langchain/langgraph\"\nexport interface ChannelProtocol<ValueType = unknown, UpdateType = unknown, CheckpointType = unknown> {\n ValueType: ValueType;\n UpdateType: UpdateType;\n /**\n * The name of the channel.\n */\n lc_graph_name: string;\n /**\n * Return a new identical channel, optionally initialized from a checkpoint.\n * Can be thought of as a \"restoration\" from a checkpoint which is a \"snapshot\" of the channel's state.\n *\n * @param {CheckpointType | undefined} checkpoint\n * @returns {this}\n */\n fromCheckpoint(checkpoint?: CheckpointType): this;\n /**\n * Update the channel's value with the given sequence of updates.\n * The order of the updates in the sequence is arbitrary.\n *\n * @throws {InvalidUpdateError} if the sequence of updates is invalid.\n * @param {Array<UpdateType>} values\n * @returns {void}\n */\n update(values: UpdateType[]): void;\n /**\n * Return the current value of the channel.\n *\n * @throws {EmptyChannelError} if the channel is empty (never updated yet).\n * @returns {ValueType}\n */\n get(): ValueType;\n /**\n * Return a string representation of the channel's current state.\n *\n * @throws {EmptyChannelError} if the channel is empty (never updated yet), or doesn't support checkpoints.\n * @returns {CheckpointType | undefined}\n */\n checkpoint(): CheckpointType | undefined;\n}\n// Mirrors SendInterface in \"@langchain/langgraph\"\nexport interface SendProtocol {\n node: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n args: any;\n}\n"],"mappings":";cAAqBA,KAAAA;AAAAA,cACAC,KAAAA,GADK,WAAA;AACLA,cACAC,SAAAA,GADK,eAAA;AACLA,cACAC,SAAAA,GADS,eAAA;AACTA,cACAC,MAAAA,GADS,YAAA;AAC9B;AAEiBC,UAAAA,eAAe,CAAA,YAAA,OAAA,EAAA,aAAA,OAAA,EAAA,iBAAA,OAAA,CAAA,CAAA;EAAA,SAAA,EACjBC,SADiB;YACjBA,EACCC,UADDD;;;;eA6BJA,EAAAA,MAAAA;;;AAUX;;;;;8BA1BgCE;;;;;;;;;iBASbD;;;;;;;SAORD;;;;;;;gBAOOE;;;UAGDC,YAAAA"}
{"version":3,"file":"types.d.ts","names":[],"sources":["../../src/serde/types.ts"],"mappings":";cAAa,KAAA;AAAA,cACA,KAAA;AAAA,cACA,SAAA;AAAA,cACA,SAAA;AAAA,cACA,MAAA;AAAA,UAGI,eAAA;EAKf,SAAA,EAAW,SAAA;EAEX,UAAA,EAAY,UAAA;;;;EAKZ,aAAA;EAjBoB;;;;AACtB;;;EAyBE,cAAA,CAAe,UAAA,GAAa,cAAA;EAzBR;AACtB;;;;;AAGA;;EA+BE,MAAA,CAAO,MAAA,EAAQ,UAAA;EA1BJ;;;;;;EAkCX,GAAA,IAAO,SAAA;EAQqB;;;;;;EAA5B,UAAA,IAAc,cAAA;AAAA;AAAA,UAIC,YAAA;EACf,IAAA;EAEA,IAAA;AAAA"}

@@ -7,5 +7,5 @@ //#region src/serde/types.ts

const RESUME = "__resume__";
//#endregion
export { ERROR, INTERRUPT, RESUME, SCHEDULED, TASKS };
//# sourceMappingURL=types.js.map

@@ -1,2 +0,1 @@

//#region src/serde/utils/fast-safe-stringify/index.ts

@@ -99,5 +98,5 @@ var LIMIT_REPLACE_NODE = "[...]";

}
//#endregion
exports.stringify = stringify;
//# sourceMappingURL=index.cjs.map

@@ -1,1 +0,1 @@

{"version":3,"file":"index.cjs","names":[],"sources":["../../../../src/serde/utils/fast-safe-stringify/index.ts"],"sourcesContent":["/* eslint-disable */\n// @ts-nocheck\n\n// Stringify that can handle circular references.\n// Inlined due to ESM import issues\n// Source: https://www.npmjs.com/package/fast-safe-stringify\n\nvar LIMIT_REPLACE_NODE = \"[...]\";\nvar CIRCULAR_REPLACE_NODE = \"[Circular]\";\n\nvar arr = [];\nvar replacerStack = [];\n\nfunction defaultOptions() {\n return {\n depthLimit: Number.MAX_SAFE_INTEGER,\n edgesLimit: Number.MAX_SAFE_INTEGER,\n };\n}\n\n// Regular stringify\nexport function stringify(obj, replacer?, spacer?, options?) {\n if (typeof options === \"undefined\") {\n options = defaultOptions();\n }\n\n decirc(obj, \"\", 0, [], undefined, 0, options);\n var res;\n try {\n if (replacerStack.length === 0) {\n res = JSON.stringify(obj, replacer, spacer);\n } else {\n res = JSON.stringify(obj, replaceGetterValues(replacer), spacer);\n }\n } catch (_) {\n return JSON.stringify(\n \"[unable to serialize, circular reference is too complex to analyze]\"\n );\n } finally {\n while (arr.length !== 0) {\n var part = arr.pop();\n if (part.length === 4) {\n Object.defineProperty(part[0], part[1], part[3]);\n } else {\n part[0][part[1]] = part[2];\n }\n }\n }\n return res;\n}\n\nfunction setReplace(replace, val, k, parent) {\n var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k);\n if (propertyDescriptor.get !== undefined) {\n if (propertyDescriptor.configurable) {\n Object.defineProperty(parent, k, { value: replace });\n arr.push([parent, k, val, propertyDescriptor]);\n } else {\n replacerStack.push([val, k, replace]);\n }\n } else {\n parent[k] = replace;\n arr.push([parent, k, val]);\n }\n}\n\nfunction decirc(val, k, edgeIndex, stack, parent, depth, options) {\n depth += 1;\n var i;\n if (typeof val === \"object\" && val !== null) {\n for (i = 0; i < stack.length; i++) {\n if (stack[i] === val) {\n setReplace(CIRCULAR_REPLACE_NODE, val, k, parent);\n return;\n }\n }\n\n if (\n typeof options.depthLimit !== \"undefined\" &&\n depth > options.depthLimit\n ) {\n setReplace(LIMIT_REPLACE_NODE, val, k, parent);\n return;\n }\n\n if (\n typeof options.edgesLimit !== \"undefined\" &&\n edgeIndex + 1 > options.edgesLimit\n ) {\n setReplace(LIMIT_REPLACE_NODE, val, k, parent);\n return;\n }\n\n stack.push(val);\n // Optimize for Arrays. Big arrays could kill the performance otherwise!\n if (Array.isArray(val)) {\n for (i = 0; i < val.length; i++) {\n decirc(val[i], i, i, stack, val, depth, options);\n }\n } else {\n var keys = Object.keys(val);\n for (i = 0; i < keys.length; i++) {\n var key = keys[i];\n decirc(val[key], key, i, stack, val, depth, options);\n }\n }\n stack.pop();\n }\n}\n\n// Stable-stringify\nfunction compareFunction(a, b) {\n if (a < b) {\n return -1;\n }\n if (a > b) {\n return 1;\n }\n return 0;\n}\n\nfunction deterministicStringify(obj, replacer, spacer, options) {\n if (typeof options === \"undefined\") {\n options = defaultOptions();\n }\n\n var tmp = deterministicDecirc(obj, \"\", 0, [], undefined, 0, options) || obj;\n var res;\n try {\n if (replacerStack.length === 0) {\n res = JSON.stringify(tmp, replacer, spacer);\n } else {\n res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer);\n }\n } catch (_) {\n return JSON.stringify(\n \"[unable to serialize, circular reference is too complex to analyze]\"\n );\n } finally {\n // Ensure that we restore the object as it was.\n while (arr.length !== 0) {\n var part = arr.pop();\n if (part.length === 4) {\n Object.defineProperty(part[0], part[1], part[3]);\n } else {\n part[0][part[1]] = part[2];\n }\n }\n }\n return res;\n}\n\nfunction deterministicDecirc(val, k, edgeIndex, stack, parent, depth, options) {\n depth += 1;\n var i;\n if (typeof val === \"object\" && val !== null) {\n for (i = 0; i < stack.length; i++) {\n if (stack[i] === val) {\n setReplace(CIRCULAR_REPLACE_NODE, val, k, parent);\n return;\n }\n }\n try {\n if (typeof val.toJSON === \"function\") {\n return;\n }\n } catch (_) {\n return;\n }\n\n if (\n typeof options.depthLimit !== \"undefined\" &&\n depth > options.depthLimit\n ) {\n setReplace(LIMIT_REPLACE_NODE, val, k, parent);\n return;\n }\n\n if (\n typeof options.edgesLimit !== \"undefined\" &&\n edgeIndex + 1 > options.edgesLimit\n ) {\n setReplace(LIMIT_REPLACE_NODE, val, k, parent);\n return;\n }\n\n stack.push(val);\n // Optimize for Arrays. Big arrays could kill the performance otherwise!\n if (Array.isArray(val)) {\n for (i = 0; i < val.length; i++) {\n deterministicDecirc(val[i], i, i, stack, val, depth, options);\n }\n } else {\n // Create a temporary object in the required way\n var tmp = {};\n var keys = Object.keys(val).sort(compareFunction);\n for (i = 0; i < keys.length; i++) {\n var key = keys[i];\n deterministicDecirc(val[key], key, i, stack, val, depth, options);\n tmp[key] = val[key];\n }\n if (typeof parent !== \"undefined\") {\n arr.push([parent, k, val]);\n parent[k] = tmp;\n } else {\n return tmp;\n }\n }\n stack.pop();\n }\n}\n\n// wraps replacer function to handle values we couldn't replace\n// and mark them as replaced value\nfunction replaceGetterValues(replacer) {\n replacer =\n typeof replacer !== \"undefined\"\n ? replacer\n : function (k, v) {\n return v;\n };\n return function (key, val) {\n if (replacerStack.length > 0) {\n for (var i = 0; i < replacerStack.length; i++) {\n var part = replacerStack[i];\n if (part[1] === key && part[0] === val) {\n val = part[2];\n replacerStack.splice(i, 1);\n break;\n }\n }\n }\n return replacer.call(this, key, val);\n };\n}\n"],"mappings":";;AAOA,IAAI,qBAAqB;AACzB,IAAI,wBAAwB;AAE5B,IAAI,MAAM;AACV,IAAI,gBAAgB;AAEpB,SAAS,iBAAiB;AACxB,QAAO;EACL,YAAY,OAAO;EACnB,YAAY,OAAO;;;AAKvB,SAAgB,UAAU,KAAK,UAAW,QAAS,SAAU;AAC3D,KAAI,OAAO,YAAY,YACrB,WAAU;AAGZ,QAAO,KAAK,IAAI,GAAG,IAAI,QAAW,GAAG;CACrC,IAAI;AACJ,KAAI;AACF,M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K,OAAO;OAErC;GACL,IAAI,OAAO,OAAO,KAAK;AACvB,QAAK,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;IAChC,IAAI,MAAM,KAAK;AACf,WAAO,IAAI,MAAM,KAAK,GAAG,OAAO,KAAK,OAAO;;;AAGhD,QAAM;;;AA4GV,SAAS,oBAAoB,UAAU;AACrC,YACE,OAAO,aAAa,cAChB,WACA,SAAU,GAAG,GAAG;AACd,SAAO;;AAEf,QAAO,SAAU,KAAK,KAAK;AACzB,MAAI,cAAc,SAAS,EACzB,MAAK,IAAI,IAAI,GAAG,IAAI,cAAc,QAAQ,KAAK;GAC7C,IAAI,OAAO,cAAc;AACzB,OAAI,KAAK,OAAO,OAAO,KAAK,OAAO,KAAK;AACtC,UAAM,KAAK;AACX,kBAAc,OAAO,GAAG;AACxB;;;AAIN,SAAO,SAAS,KAAK,MAAM,KAAK"}
{"version":3,"file":"index.cjs","names":[],"sources":["../../../../src/serde/utils/fast-safe-stringify/index.ts"],"sourcesContent":["/* eslint-disable */\n// @ts-nocheck\n\n// Stringify that can handle circular references.\n// Inlined due to ESM import issues\n// Source: https://www.npmjs.com/package/fast-safe-stringify\n\nvar LIMIT_REPLACE_NODE = \"[...]\";\nvar CIRCULAR_REPLACE_NODE = \"[Circular]\";\n\nvar arr = [];\nvar replacerStack = [];\n\nfunction defaultOptions() {\n return {\n depthLimit: Number.MAX_SAFE_INTEGER,\n edgesLimit: Number.MAX_SAFE_INTEGER,\n };\n}\n\n// Regular stringify\nexport function stringify(obj, replacer?, spacer?, options?) {\n if (typeof options === \"undefined\") {\n options = defaultOptions();\n }\n\n decirc(obj, \"\", 0, [], undefined, 0, options);\n var res;\n try {\n if (replacerStack.length === 0) {\n res = JSON.stringify(obj, replacer, spacer);\n } else {\n res = JSON.stringify(obj, replaceGetterValues(replacer), spacer);\n }\n } catch (_) {\n return JSON.stringify(\n \"[unable to serialize, circular reference is too complex to analyze]\"\n );\n } finally {\n while (arr.length !== 0) {\n var part = arr.pop();\n if (part.length === 4) {\n Object.defineProperty(part[0], part[1], part[3]);\n } else {\n part[0][part[1]] = part[2];\n }\n }\n }\n return res;\n}\n\nfunction setReplace(replace, val, k, parent) {\n var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k);\n if (propertyDescriptor.get !== undefined) {\n if (propertyDescriptor.configurable) {\n Object.defineProperty(parent, k, { value: replace });\n arr.push([parent, k, val, propertyDescriptor]);\n } else {\n replacerStack.push([val, k, replace]);\n }\n } else {\n parent[k] = replace;\n arr.push([parent, k, val]);\n }\n}\n\nfunction decirc(val, k, edgeIndex, stack, parent, depth, options) {\n depth += 1;\n var i;\n if (typeof val === \"object\" && val !== null) {\n for (i = 0; i < stack.length; i++) {\n if (stack[i] === val) {\n setReplace(CIRCULAR_REPLACE_NODE, val, k, parent);\n return;\n }\n }\n\n if (\n typeof options.depthLimit !== \"undefined\" &&\n depth > options.depthLimit\n ) {\n setReplace(LIMIT_REPLACE_NODE, val, k, parent);\n return;\n }\n\n if (\n typeof options.edgesLimit !== \"undefined\" &&\n edgeIndex + 1 > options.edgesLimit\n ) {\n setReplace(LIMIT_REPLACE_NODE, val, k, parent);\n return;\n }\n\n stack.push(val);\n // Optimize for Arrays. Big arrays could kill the performance otherwise!\n if (Array.isArray(val)) {\n for (i = 0; i < val.length; i++) {\n decirc(val[i], i, i, stack, val, depth, options);\n }\n } else {\n var keys = Object.keys(val);\n for (i = 0; i < keys.length; i++) {\n var key = keys[i];\n decirc(val[key], key, i, stack, val, depth, options);\n }\n }\n stack.pop();\n }\n}\n\n// Stable-stringify\nfunction compareFunction(a, b) {\n if (a < b) {\n return -1;\n }\n if (a > b) {\n return 1;\n }\n return 0;\n}\n\nfunction deterministicStringify(obj, replacer, spacer, options) {\n if (typeof options === \"undefined\") {\n options = defaultOptions();\n }\n\n var tmp = deterministicDecirc(obj, \"\", 0, [], undefined, 0, options) || obj;\n var res;\n try {\n if (replacerStack.length === 0) {\n res = JSON.stringify(tmp, replacer, spacer);\n } else {\n res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer);\n }\n } catch (_) {\n return JSON.stringify(\n \"[unable to serialize, circular reference is too complex to analyze]\"\n );\n } finally {\n // Ensure that we restore the object as it was.\n while (arr.length !== 0) {\n var part = arr.pop();\n if (part.length === 4) {\n Object.defineProperty(part[0], part[1], part[3]);\n } else {\n part[0][part[1]] = part[2];\n }\n }\n }\n return res;\n}\n\nfunction deterministicDecirc(val, k, edgeIndex, stack, parent, depth, options) {\n depth += 1;\n var i;\n if (typeof val === \"object\" && val !== null) {\n for (i = 0; i < stack.length; i++) {\n if (stack[i] === val) {\n setReplace(CIRCULAR_REPLACE_NODE, val, k, parent);\n return;\n }\n }\n try {\n if (typeof val.toJSON === \"function\") {\n return;\n }\n } catch (_) {\n return;\n }\n\n if (\n typeof options.depthLimit !== \"undefined\" &&\n depth > options.depthLimit\n ) {\n setReplace(LIMIT_REPLACE_NODE, val, k, parent);\n return;\n }\n\n if (\n typeof options.edgesLimit !== \"undefined\" &&\n edgeIndex + 1 > options.edgesLimit\n ) {\n setReplace(LIMIT_REPLACE_NODE, val, k, parent);\n return;\n }\n\n stack.push(val);\n // Optimize for Arrays. Big arrays could kill the performance otherwise!\n if (Array.isArray(val)) {\n for (i = 0; i < val.length; i++) {\n deterministicDecirc(val[i], i, i, stack, val, depth, options);\n }\n } else {\n // Create a temporary object in the required way\n var tmp = {};\n var keys = Object.keys(val).sort(compareFunction);\n for (i = 0; i < keys.length; i++) {\n var key = keys[i];\n deterministicDecirc(val[key], key, i, stack, val, depth, options);\n tmp[key] = val[key];\n }\n if (typeof parent !== \"undefined\") {\n arr.push([parent, k, val]);\n parent[k] = tmp;\n } else {\n return tmp;\n }\n }\n stack.pop();\n }\n}\n\n// wraps replacer function to handle values we couldn't replace\n// and mark them as replaced value\nfunction replaceGetterValues(replacer) {\n replacer =\n typeof replacer !== \"undefined\"\n ? replacer\n : function (k, v) {\n return v;\n };\n return function (key, val) {\n if (replacerStack.length > 0) {\n for (var i = 0; i < replacerStack.length; i++) {\n var part = replacerStack[i];\n if (part[1] === key && part[0] === val) {\n val = part[2];\n replacerStack.splice(i, 1);\n break;\n }\n }\n }\n return replacer.call(this, key, val);\n };\n}\n"],"mappings":";AAOA,IAAI,qBAAqB;AACzB,IAAI,wBAAwB;AAE5B,IAAI,MAAM,EAAE;AACZ,IAAI,gBAAgB,EAAE;AAEtB,SAAS,iBAAiB;AACxB,QAAO;EACL,YAAY,OAAO;EACnB,YAAY,OAAO;EACpB;;AAIH,SAAgB,UAAU,KAAK,UAAW,QAAS,SAAU;AAC3D,KAAI,OAAO,YAAY,YACrB,WAAU,gBAAgB;AAG5B,QAAO,KAAK,IAAI,GAAG,EAAE,EAAE,KAAA,GAAW,GAAG,QAAQ;CAC7C,IAAI;AACJ,KAAI;AACF,MAAI,cAAc,WAAW,EAC3B,OAAM,KAAK,UAAU,KAAK,UAAU,OAAO;MAE3C,OAAM,KAAK,UAAU,KAAK,oBAAoB,SAAS,EAAE,OAAO;UAE3D,GAAG;AACV,SAAO,KAAK,UACV,sEACD;WACO;AACR,SAAO,IAAI,WAAW,GAAG;GACvB,IAAI,OAAO,IAAI,KAAK;AACpB,OAAI,KAAK,WAAW,EAClB,QAAO,eAAe,KAAK,IAAI,KAAK,IAAI,KAAK,GAAG;OAEhD,MAAK,GAAG,KAAK,MAAM,KAAK;;;AAI9B,QAAO;;AAGT,SAAS,WAAW,SAAS,KAAK,GAAG,QAAQ;CAC3C,IAAI,qBAAqB,OAAO,yBAAyB,QAAQ,EAAE;AACnE,KAAI,mBAAmB,QAAQ,KAAA,EAC7B,KAAI,mBAAmB,cAAc;AACnC,SAAO,eAAe,QAAQ,GAAG,EAAE,OAAO,SAAS,CAAC;AACpD,MAAI,KAAK;GAAC;GAAQ;GAAG;GAAK;GAAmB,CAAC;OAE9C,eAAc,KAAK;EAAC;EAAK;EAAG;EAAQ,CAAC;MAElC;AACL,SAAO,KAAK;AACZ,MAAI,KAAK;GAAC;GAAQ;GAAG;G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 @@ //#region src/serde/utils/fast-safe-stringify/index.ts

}
//#endregion
export { stringify };
//# sourceMappingURL=index.js.map

@@ -1,1 +0,1 @@

{"version":3,"file":"index.js","names":[],"sources":["../../../../src/serde/utils/fast-safe-stringify/index.ts"],"sourcesContent":["/* eslint-disable */\n// @ts-nocheck\n\n// Stringify that can handle circular references.\n// Inlined due to ESM import issues\n// Source: https://www.npmjs.com/package/fast-safe-stringify\n\nvar LIMIT_REPLACE_NODE = \"[...]\";\nvar CIRCULAR_REPLACE_NODE = \"[Circular]\";\n\nvar arr = [];\nvar replacerStack = [];\n\nfunction defaultOptions() {\n return {\n depthLimit: Number.MAX_SAFE_INTEGER,\n edgesLimit: Number.MAX_SAFE_INTEGER,\n };\n}\n\n// Regular stringify\nexport function stringify(obj, replacer?, spacer?, options?) {\n if (typeof options === \"undefined\") {\n options = defaultOptions();\n }\n\n decirc(obj, \"\", 0, [], undefined, 0, options);\n var res;\n try {\n if (replacerStack.length === 0) {\n res = JSON.stringify(obj, replacer, spacer);\n } else {\n res = JSON.stringify(obj, replaceGetterValues(replacer), spacer);\n }\n } catch (_) {\n return JSON.stringify(\n \"[unable to serialize, circular reference is too complex to analyze]\"\n );\n } finally {\n while (arr.length !== 0) {\n var part = arr.pop();\n if (part.length === 4) {\n Object.defineProperty(part[0], part[1], part[3]);\n } else {\n part[0][part[1]] = part[2];\n }\n }\n }\n return res;\n}\n\nfunction setReplace(replace, val, k, parent) {\n var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k);\n if (propertyDescriptor.get !== undefined) {\n if (propertyDescriptor.configurable) {\n Object.defineProperty(parent, k, { value: replace });\n arr.push([parent, k, val, propertyDescriptor]);\n } else {\n replacerStack.push([val, k, replace]);\n }\n } else {\n parent[k] = replace;\n arr.push([parent, k, val]);\n }\n}\n\nfunction decirc(val, k, edgeIndex, stack, parent, depth, options) {\n depth += 1;\n var i;\n if (typeof val === \"object\" && val !== null) {\n for (i = 0; i < stack.length; i++) {\n if (stack[i] === val) {\n setReplace(CIRCULAR_REPLACE_NODE, val, k, parent);\n return;\n }\n }\n\n if (\n typeof options.depthLimit !== \"undefined\" &&\n depth > options.depthLimit\n ) {\n setReplace(LIMIT_REPLACE_NODE, val, k, parent);\n return;\n }\n\n if (\n typeof options.edgesLimit !== \"undefined\" &&\n edgeIndex + 1 > options.edgesLimit\n ) {\n setReplace(LIMIT_REPLACE_NODE, val, k, parent);\n return;\n }\n\n stack.push(val);\n // Optimize for Arrays. Big arrays could kill the performance otherwise!\n if (Array.isArray(val)) {\n for (i = 0; i < val.length; i++) {\n decirc(val[i], i, i, stack, val, depth, options);\n }\n } else {\n var keys = Object.keys(val);\n for (i = 0; i < keys.length; i++) {\n var key = keys[i];\n decirc(val[key], key, i, stack, val, depth, options);\n }\n }\n stack.pop();\n }\n}\n\n// Stable-stringify\nfunction compareFunction(a, b) {\n if (a < b) {\n return -1;\n }\n if (a > b) {\n return 1;\n }\n return 0;\n}\n\nfunction deterministicStringify(obj, replacer, spacer, options) {\n if (typeof options === \"undefined\") {\n options = defaultOptions();\n }\n\n var tmp = deterministicDecirc(obj, \"\", 0, [], undefined, 0, options) || obj;\n var res;\n try {\n if (replacerStack.length === 0) {\n res = JSON.stringify(tmp, replacer, spacer);\n } else {\n res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer);\n }\n } catch (_) {\n return JSON.stringify(\n \"[unable to serialize, circular reference is too complex to analyze]\"\n );\n } finally {\n // Ensure that we restore the object as it was.\n while (arr.length !== 0) {\n var part = arr.pop();\n if (part.length === 4) {\n Object.defineProperty(part[0], part[1], part[3]);\n } else {\n part[0][part[1]] = part[2];\n }\n }\n }\n return res;\n}\n\nfunction deterministicDecirc(val, k, edgeIndex, stack, parent, depth, options) {\n depth += 1;\n var i;\n if (typeof val === \"object\" && val !== null) {\n for (i = 0; i < stack.length; i++) {\n if (stack[i] === val) {\n setReplace(CIRCULAR_REPLACE_NODE, val, k, parent);\n return;\n }\n }\n try {\n if (typeof val.toJSON === \"function\") {\n return;\n }\n } catch (_) {\n return;\n }\n\n if (\n typeof options.depthLimit !== \"undefined\" &&\n depth > options.depthLimit\n ) {\n setReplace(LIMIT_REPLACE_NODE, val, k, parent);\n return;\n }\n\n if (\n typeof options.edgesLimit !== \"undefined\" &&\n edgeIndex + 1 > options.edgesLimit\n ) {\n setReplace(LIMIT_REPLACE_NODE, val, k, parent);\n return;\n }\n\n stack.push(val);\n // Optimize for Arrays. Big arrays could kill the performance otherwise!\n if (Array.isArray(val)) {\n for (i = 0; i < val.length; i++) {\n deterministicDecirc(val[i], i, i, stack, val, depth, options);\n }\n } else {\n // Create a temporary object in the required way\n var tmp = {};\n var keys = Object.keys(val).sort(compareFunction);\n for (i = 0; i < keys.length; i++) {\n var key = keys[i];\n deterministicDecirc(val[key], key, i, stack, val, depth, options);\n tmp[key] = val[key];\n }\n if (typeof parent !== \"undefined\") {\n arr.push([parent, k, val]);\n parent[k] = tmp;\n } else {\n return tmp;\n }\n }\n stack.pop();\n }\n}\n\n// wraps replacer function to handle values we couldn't replace\n// and mark them as replaced value\nfunction replaceGetterValues(replacer) {\n replacer =\n typeof replacer !== \"undefined\"\n ? replacer\n : function (k, v) {\n return v;\n };\n return function (key, val) {\n if (replacerStack.length > 0) {\n for (var i = 0; i < replacerStack.length; i++) {\n var part = replacerStack[i];\n if (part[1] === key && part[0] === val) {\n val = part[2];\n replacerStack.splice(i, 1);\n break;\n }\n }\n }\n return replacer.call(this, key, val);\n };\n}\n"],"mappings":";AAOA,IAAI,qBAAqB;AACzB,IAAI,wBAAwB;AAE5B,IAAI,MAAM;AACV,IAAI,gBAAgB;AAEpB,SAAS,iBAAiB;AACxB,QAAO;EACL,YAAY,OAAO;EACnB,YAAY,OAAO;;;AAKvB,SAAgB,UAAU,KAAK,UAAW,QAAS,SAAU;AAC3D,KAAI,OAAO,YAAY,YACrB,WAAU;AAGZ,QAAO,KAAK,IAAI,GAAG,IAAI,QAAW,GAAG;CACrC,IAAI;AACJ,KAAI;AACF,MAAI,c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O;OAErC;GACL,IAAI,OAAO,OAAO,KAAK;AACvB,QAAK,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;IAChC,IAAI,MAAM,KAAK;AACf,WAAO,IAAI,MAAM,KAAK,GAAG,OAAO,KAAK,OAAO;;;AAGhD,QAAM;;;AA4GV,SAAS,oBAAoB,UAAU;AACrC,YACE,OAAO,aAAa,cAChB,WACA,SAAU,GAAG,GAAG;AACd,SAAO;;AAEf,QAAO,SAAU,KAAK,KAAK;AACzB,MAAI,cAAc,SAAS,EACzB,MAAK,IAAI,IAAI,GAAG,IAAI,cAAc,QAAQ,KAAK;GAC7C,IAAI,OAAO,cAAc;AACzB,OAAI,KAAK,OAAO,OAAO,KAAK,OAAO,KAAK;AACtC,UAAM,KAAK;AACX,kBAAc,OAAO,GAAG;AACxB;;;AAIN,SAAO,SAAS,KAAK,MAAM,KAAK"}
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/serde/utils/fast-safe-stringify/index.ts"],"sourcesContent":["/* eslint-disable */\n// @ts-nocheck\n\n// Stringify that can handle circular references.\n// Inlined due to ESM import issues\n// Source: https://www.npmjs.com/package/fast-safe-stringify\n\nvar LIMIT_REPLACE_NODE = \"[...]\";\nvar CIRCULAR_REPLACE_NODE = \"[Circular]\";\n\nvar arr = [];\nvar replacerStack = [];\n\nfunction defaultOptions() {\n return {\n depthLimit: Number.MAX_SAFE_INTEGER,\n edgesLimit: Number.MAX_SAFE_INTEGER,\n };\n}\n\n// Regular stringify\nexport function stringify(obj, replacer?, spacer?, options?) {\n if (typeof options === \"undefined\") {\n options = defaultOptions();\n }\n\n decirc(obj, \"\", 0, [], undefined, 0, options);\n var res;\n try {\n if (replacerStack.length === 0) {\n res = JSON.stringify(obj, replacer, spacer);\n } else {\n res = JSON.stringify(obj, replaceGetterValues(replacer), spacer);\n }\n } catch (_) {\n return JSON.stringify(\n \"[unable to serialize, circular reference is too complex to analyze]\"\n );\n } finally {\n while (arr.length !== 0) {\n var part = arr.pop();\n if (part.length === 4) {\n Object.defineProperty(part[0], part[1], part[3]);\n } else {\n part[0][part[1]] = part[2];\n }\n }\n }\n return res;\n}\n\nfunction setReplace(replace, val, k, parent) {\n var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k);\n if (propertyDescriptor.get !== undefined) {\n if (propertyDescriptor.configurable) {\n Object.defineProperty(parent, k, { value: replace });\n arr.push([parent, k, val, propertyDescriptor]);\n } else {\n replacerStack.push([val, k, replace]);\n }\n } else {\n parent[k] = replace;\n arr.push([parent, k, val]);\n }\n}\n\nfunction decirc(val, k, edgeIndex, stack, parent, depth, options) {\n depth += 1;\n var i;\n if (typeof val === \"object\" && val !== null) {\n for (i = 0; i < stack.length; i++) {\n if (stack[i] === val) {\n setReplace(CIRCULAR_REPLACE_NODE, val, k, parent);\n return;\n }\n }\n\n if (\n typeof options.depthLimit !== \"undefined\" &&\n depth > options.depthLimit\n ) {\n setReplace(LIMIT_REPLACE_NODE, val, k, parent);\n return;\n }\n\n if (\n typeof options.edgesLimit !== \"undefined\" &&\n edgeIndex + 1 > options.edgesLimit\n ) {\n setReplace(LIMIT_REPLACE_NODE, val, k, parent);\n return;\n }\n\n stack.push(val);\n // Optimize for Arrays. Big arrays could kill the performance otherwise!\n if (Array.isArray(val)) {\n for (i = 0; i < val.length; i++) {\n decirc(val[i], i, i, stack, val, depth, options);\n }\n } else {\n var keys = Object.keys(val);\n for (i = 0; i < keys.length; i++) {\n var key = keys[i];\n decirc(val[key], key, i, stack, val, depth, options);\n }\n }\n stack.pop();\n }\n}\n\n// Stable-stringify\nfunction compareFunction(a, b) {\n if (a < b) {\n return -1;\n }\n if (a > b) {\n return 1;\n }\n return 0;\n}\n\nfunction deterministicStringify(obj, replacer, spacer, options) {\n if (typeof options === \"undefined\") {\n options = defaultOptions();\n }\n\n var tmp = deterministicDecirc(obj, \"\", 0, [], undefined, 0, options) || obj;\n var res;\n try {\n if (replacerStack.length === 0) {\n res = JSON.stringify(tmp, replacer, spacer);\n } else {\n res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer);\n }\n } catch (_) {\n return JSON.stringify(\n \"[unable to serialize, circular reference is too complex to analyze]\"\n );\n } finally {\n // Ensure that we restore the object as it was.\n while (arr.length !== 0) {\n var part = arr.pop();\n if (part.length === 4) {\n Object.defineProperty(part[0], part[1], part[3]);\n } else {\n part[0][part[1]] = part[2];\n }\n }\n }\n return res;\n}\n\nfunction deterministicDecirc(val, k, edgeIndex, stack, parent, depth, options) {\n depth += 1;\n var i;\n if (typeof val === \"object\" && val !== null) {\n for (i = 0; i < stack.length; i++) {\n if (stack[i] === val) {\n setReplace(CIRCULAR_REPLACE_NODE, val, k, parent);\n return;\n }\n }\n try {\n if (typeof val.toJSON === \"function\") {\n return;\n }\n } catch (_) {\n return;\n }\n\n if (\n typeof options.depthLimit !== \"undefined\" &&\n depth > options.depthLimit\n ) {\n setReplace(LIMIT_REPLACE_NODE, val, k, parent);\n return;\n }\n\n if (\n typeof options.edgesLimit !== \"undefined\" &&\n edgeIndex + 1 > options.edgesLimit\n ) {\n setReplace(LIMIT_REPLACE_NODE, val, k, parent);\n return;\n }\n\n stack.push(val);\n // Optimize for Arrays. Big arrays could kill the performance otherwise!\n if (Array.isArray(val)) {\n for (i = 0; i < val.length; i++) {\n deterministicDecirc(val[i], i, i, stack, val, depth, options);\n }\n } else {\n // Create a temporary object in the required way\n var tmp = {};\n var keys = Object.keys(val).sort(compareFunction);\n for (i = 0; i < keys.length; i++) {\n var key = keys[i];\n deterministicDecirc(val[key], key, i, stack, val, depth, options);\n tmp[key] = val[key];\n }\n if (typeof parent !== \"undefined\") {\n arr.push([parent, k, val]);\n parent[k] = tmp;\n } else {\n return tmp;\n }\n }\n stack.pop();\n }\n}\n\n// wraps replacer function to handle values we couldn't replace\n// and mark them as replaced value\nfunction replaceGetterValues(replacer) {\n replacer =\n typeof replacer !== \"undefined\"\n ? replacer\n : function (k, v) {\n return v;\n };\n return function (key, val) {\n if (replacerStack.length > 0) {\n for (var i = 0; i < replacerStack.length; i++) {\n var part = replacerStack[i];\n if (part[1] === key && part[0] === val) {\n val = part[2];\n replacerStack.splice(i, 1);\n break;\n }\n }\n }\n return replacer.call(this, key, val);\n };\n}\n"],"mappings":";AAOA,IAAI,qBAAqB;AACzB,IAAI,wBAAwB;AAE5B,IAAI,MAAM,EAAE;AACZ,IAAI,gBAAgB,EAAE;AAEtB,SAAS,iBAAiB;AACxB,QAAO;EACL,YAAY,OAAO;EACnB,YAAY,OAAO;EACpB;;AAIH,SAAgB,UAAU,KAAK,UAAW,QAAS,SAAU;AAC3D,KAAI,OAAO,YAAY,YACrB,WAAU,gBAAgB;AAG5B,QAAO,KAAK,IAAI,GAAG,EAAE,EAAE,KAAA,GAAW,GAAG,QAAQ;CAC7C,IAAI;AACJ,KAAI;AACF,MAAI,cAAc,WAAW,EAC3B,OAAM,KAAK,UAAU,KAAK,UAAU,OAAO;MAE3C,OAAM,KAAK,UAAU,KAAK,oBAAoB,SAAS,EAAE,OAAO;UAE3D,GAAG;AACV,SAAO,KAAK,UACV,sEACD;WACO;AACR,SAAO,IAAI,WAAW,GAAG;GACvB,IAAI,OAAO,IAAI,KAAK;AACpB,OAAI,KAAK,WAAW,EAClB,QAAO,eAAe,KAAK,IAAI,KAAK,IAAI,KAAK,GAAG;OAEhD,MAAK,GAAG,KAAK,MAAM,KAAK;;;AAI9B,QAAO;;AAGT,SAAS,WAAW,SAAS,KAAK,GAAG,QAAQ;CAC3C,IAAI,qBAAqB,OAAO,yBAAyB,QAAQ,EAAE;AACnE,KAAI,mBAAmB,QAAQ,KAAA,EAC7B,KAAI,mBAAmB,cAAc;AACnC,SAAO,eAAe,QAAQ,GAAG,EAAE,OAAO,SAAS,CAAC;AACpD,MAAI,KAAK;GAAC;GAAQ;GAAG;GAAK;GAAmB,CAAC;OAE9C,eAAc,KAAK;EAAC;EAAK;EAAG;EAAQ,CAAC;MAElC;AACL,SAAO,KAAK;AACZ,MAAI,KAAK;GAAC;GAAQ;GAAG;GAAI,CAA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src/store/base.ts

@@ -206,3 +205,2 @@ /**

};
//#endregion

@@ -213,2 +211,3 @@ exports.BaseStore = BaseStore;

exports.tokenizePath = tokenizePath;
//# sourceMappingURL=base.cjs.map

@@ -1,1 +0,1 @@

{"version":3,"file":"base.cjs","names":["current: any","results: string[]","matchConditions: MatchCondition[]"],"sources":["../../src/store/base.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Embeddings } from \"@langchain/core/embeddings\";\n\n/**\n * Error thrown when an invalid namespace is provided.\n */\nexport class InvalidNamespaceError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"InvalidNamespaceError\";\n }\n}\n\n/**\n * Validates the provided namespace.\n * @param namespace The namespace to validate.\n * @throws {InvalidNamespaceError} If the namespace is invalid.\n */\nfunction validateNamespace(namespace: string[]): void {\n if (namespace.length === 0) {\n throw new InvalidNamespaceError(\"Namespace cannot be empty.\");\n }\n for (const label of namespace) {\n if (typeof label !== \"string\") {\n throw new InvalidNamespaceError(\n `Invalid namespace label '${label}' found in ${namespace}. Namespace labels ` +\n `must be strings, but got ${typeof label}.`\n );\n }\n if (label.includes(\".\")) {\n throw new InvalidNamespaceError(\n `Invalid namespace label '${label}' found in ${namespace}. Namespace labels cannot contain periods ('.').`\n );\n }\n if (label === \"\") {\n throw new InvalidNamespaceError(\n `Namespace labels cannot be empty strings. Got ${label} in ${namespace}`\n );\n }\n }\n if (namespace[0] === \"langgraph\") {\n throw new InvalidNamespaceError(\n `Root label for namespace cannot be \"langgraph\". Got: ${namespace}`\n );\n }\n}\n\n/**\n * Represents a stored item with metadata.\n */\nexport interface Item {\n /**\n * The stored data as an object. Keys are filterable.\n */\n value: Record<string, any>;\n /**\n * Unique identifier within the namespace.\n */\n key: string;\n /**\n * Hierarchical path defining the collection in which this document resides.\n * Represented as an array of strings, allowing for nested categorization.\n * For example: [\"documents\", \"user123\"]\n */\n namespace: string[];\n /**\n * Timestamp of item creation.\n */\n createdAt: Date;\n /**\n * Timestamp of last update.\n */\n updatedAt: Date;\n}\n\n/**\n * Represents a search result item with relevance score.\n * Extends the base Item interface with an optional similarity score.\n */\nexport interface SearchItem extends Item {\n /**\n * Relevance/similarity score if from a ranked operation.\n * Higher scores indicate better matches.\n *\n * This is typically a cosine similarity score between -1 and 1,\n * where 1 indicates identical vectors and -1 indicates opposite vectors.\n */\n score?: number;\n}\n\n/**\n * Operation to retrieve an item by namespace and ID.\n */\nexport interface GetOperation {\n /**\n * Hierarchical path for the item.\n *\n * @example\n * // Get a user profile\n * namespace: [\"users\", \"profiles\"]\n */\n namespace: string[];\n\n /**\n * Unique identifier within the namespace.\n * Together with namespace forms the complete path to the item.\n *\n * @example\n * key: \"user123\" // For a user profile\n * key: \"doc456\" // For a document\n */\n key: string;\n}\n\n/**\n * Operation to search for items within a namespace prefix.\n */\nexport interface SearchOperation {\n /**\n * Hierarchical path prefix to search within.\n * Only items under this prefix will be searched.\n *\n * @example\n * // Search all user documents\n * namespacePrefix: [\"users\", \"documents\"]\n *\n * // Search everything\n * namespacePrefix: []\n */\n namespacePrefix: string[];\n\n /**\n * Key-value pairs to filter results based on exact matches or comparison operators.\n *\n * Supports both exact matches and operator-based comparisons:\n * - $eq: Equal to (same as direct value comparison)\n * - $ne: Not equal to\n * - $gt: Greater than\n * - $gte: Greater than or equal to\n * - $lt: Less than\n * - $lte: Less than or equal to\n *\n * @example\n * // Exact match\n * filter: { status: \"active\" }\n *\n * // With operators\n * filter: { score: { $gt: 4.99 } }\n *\n * // Multiple conditions\n * filter: {\n * score: { $gte: 3.0 },\n * color: \"red\"\n * }\n */\n filter?: Record<string, any>;\n\n /**\n * Maximum number of items to return.\n * @default 10\n */\n limit?: number;\n\n /**\n * Number of items to skip before returning results.\n * Useful for pagination.\n * @default 0\n */\n offset?: number;\n\n /**\n * Natural language search query for semantic search.\n * When provided, results will be ranked by relevance to this query\n * using vector similarity search.\n *\n * @example\n * // Find technical documentation about APIs\n * query: \"technical documentation about REST APIs\"\n *\n * // Find recent ML papers\n * query: \"machine learning papers from 2023\"\n */\n query?: string;\n}\n\n/**\n * Operation to store, update, or delete an item.\n */\nexport interface PutOperation {\n /**\n * Hierarchical path for the item.\n * Acts as a folder-like structure to organize items.\n * Each element represents one level in the hierarchy.\n *\n * @example\n * // Root level documents\n * namespace: [\"documents\"]\n *\n * // User-specific documents\n * namespace: [\"documents\", \"user123\"]\n *\n * // Nested cache structure\n * namespace: [\"cache\", \"docs\", \"v1\"]\n */\n namespace: string[];\n\n /**\n * Unique identifier for the document within its namespace.\n * Together with namespace forms the complete path to the item.\n *\n * Example: If namespace is [\"documents\", \"user123\"] and key is \"report1\",\n * the full path would effectively be \"documents/user123/report1\"\n */\n key: string;\n\n /**\n * Data to be stored, or null to delete the item.\n * Must be a JSON-serializable object with string keys.\n * Setting to null signals that the item should be deleted.\n *\n * @example\n * {\n * field1: \"string value\",\n * field2: 123,\n * nested: { can: \"contain\", any: \"serializable data\" }\n * }\n */\n value: Record<string, any> | null;\n\n /**\n * Controls how the item's fields are indexed for search operations.\n *\n * - undefined: Uses store's default indexing configuration\n * - false: Disables indexing for this item\n * - string[]: List of field paths to index\n *\n * Path syntax supports:\n * - Nested fields: \"metadata.title\"\n * - Array access: \"chapters[*].content\" (each indexed separately)\n * - Specific indices: \"authors[0].name\"\n *\n * @example\n * // Index specific fields\n * index: [\"metadata.title\", \"chapters[*].content\"]\n *\n * // Disable indexing\n * index: false\n */\n index?: false | string[];\n}\n\n/**\n * Operation to list and filter namespaces in the store.\n */\nexport interface ListNamespacesOperation {\n matchConditions?: MatchCondition[];\n maxDepth?: number;\n limit: number;\n offset: number;\n}\n\nexport type NameSpacePath = (string | \"*\")[];\n\nexport type NamespaceMatchType = \"prefix\" | \"suffix\";\n\nexport interface MatchCondition {\n matchType: NamespaceMatchType;\n path: NameSpacePath;\n}\n\nexport type Operation =\n | GetOperation\n | SearchOperation\n | PutOperation\n | ListNamespacesOperation;\n\nexport type OperationResults<Tuple extends readonly Operation[]> = {\n [K in keyof Tuple]: Tuple[K] extends PutOperation\n ? void\n : Tuple[K] extends SearchOperation\n ? SearchItem[]\n : Tuple[K] extends GetOperation\n ? Item | null\n : Tuple[K] extends ListNamespacesOperation\n ? string[][]\n : never;\n};\n\n/**\n * Configuration for indexing documents for semantic search in the store.\n *\n * This configures how documents are embedded and indexed for vector similarity search.\n */\nexport interface IndexConfig {\n /**\n * Number of dimensions in the embedding vectors.\n *\n * Common embedding model dimensions:\n * - OpenAI text-embedding-3-large: 256, 1024, or 3072\n * - OpenAI text-embedding-3-small: 512 or 1536\n * - OpenAI text-embedding-ada-002: 1536\n * - Cohere embed-english-v3.0: 1024\n * - Cohere embed-english-light-v3.0: 384\n * - Cohere embed-multilingual-v3.0: 1024\n * - Cohere embed-multilingual-light-v3.0: 384\n */\n dims: number;\n\n /**\n * The embeddings model to use for generating vectors.\n * This should be a LangChain Embeddings implementation.\n */\n embeddings: Embeddings;\n\n /**\n * Fields to extract text from for embedding generation.\n *\n * Path syntax supports:\n * - Simple field access: \"field\"\n * - Nested fields: \"metadata.title\"\n * - Array indexing:\n * - All elements: \"chapters[*].content\"\n * - Specific index: \"authors[0].name\"\n * - Last element: \"array[-1]\"\n *\n * @default [\"$\"] Embeds the entire document as one vector\n */\n fields?: string[];\n}\n\n/**\n * Utility function to get text at a specific JSON path\n */\nexport function getTextAtPath(obj: any, path: string): string[] {\n const parts = path.split(\".\");\n let current: any = obj;\n\n for (const part of parts) {\n if (part.includes(\"[\")) {\n const [arrayName, indexStr] = part.split(\"[\");\n const index = indexStr.replace(\"]\", \"\");\n\n if (!current[arrayName]) return [];\n\n if (index === \"*\") {\n const results: string[] = [];\n for (const item of current[arrayName]) {\n if (typeof item === \"string\") results.push(item);\n }\n return results;\n }\n\n const idx = parseInt(index, 10);\n if (Number.isNaN(idx)) return [];\n current = current[arrayName][idx];\n } else {\n current = current[part];\n }\n\n if (current === undefined) return [];\n }\n\n return typeof current === \"string\" ? [current] : [];\n}\n\n/**\n * Tokenizes a JSON path into parts\n */\nexport function tokenizePath(path: string): string[] {\n return path.split(\".\");\n}\n\n/**\n * Abstract base class for persistent key-value stores.\n *\n * Stores enable persistence and memory that can be shared across threads,\n * scoped to user IDs, assistant IDs, or other arbitrary namespaces.\n *\n * Features:\n * - Hierarchical namespaces for organization\n * - Key-value storage with metadata\n * - Vector similarity search (if configured)\n * - Filtering and pagination\n */\nexport abstract class BaseStore {\n /**\n * Execute multiple operations in a single batch.\n * This is more efficient than executing operations individually.\n *\n * @param operations Array of operations to execute\n * @returns Promise resolving to results matching the operations\n */\n abstract batch<Op extends Operation[]>(\n operations: Op\n ): Promise<OperationResults<Op>>;\n\n /**\n * Retrieve a single item by its namespace and key.\n *\n * @param namespace Hierarchical path for the item\n * @param key Unique identifier within the namespace\n * @returns Promise resolving to the item or null if not found\n */\n async get(namespace: string[], key: string): Promise<Item | null> {\n return (await this.batch<[GetOperation]>([{ namespace, key }]))[0];\n }\n\n /**\n * Search for items within a namespace prefix.\n * Supports both metadata filtering and vector similarity search.\n *\n * @param namespacePrefix Hierarchical path prefix to search within\n * @param options Search options for filtering and pagination\n * @returns Promise resolving to list of matching items with relevance scores\n *\n * @example\n * // Search with filters\n * await store.search([\"documents\"], {\n * filter: { type: \"report\", status: \"active\" },\n * limit: 5,\n * offset: 10\n * });\n *\n * // Vector similarity search\n * await store.search([\"users\", \"content\"], {\n * query: \"technical documentation about APIs\",\n * limit: 20\n * });\n */\n async search(\n namespacePrefix: string[],\n options: {\n filter?: Record<string, any>;\n limit?: number;\n offset?: number;\n query?: string;\n } = {}\n ): Promise<SearchItem[]> {\n const { filter, limit = 10, offset = 0, query } = options;\n return (\n await this.batch<[SearchOperation]>([\n {\n namespacePrefix,\n filter,\n limit,\n offset,\n query,\n },\n ])\n )[0];\n }\n\n /**\n * Store or update an item.\n *\n * @param namespace Hierarchical path for the item\n * @param key Unique identifier within the namespace\n * @param value Object containing the item's data\n * @param index Optional indexing configuration\n *\n * @example\n * // Simple storage\n * await store.put([\"docs\"], \"report\", { title: \"Annual Report\" });\n *\n * // With specific field indexing\n * await store.put(\n * [\"docs\"],\n * \"report\",\n * {\n * title: \"Q4 Report\",\n * chapters: [{ content: \"...\" }, { content: \"...\" }]\n * },\n * [\"title\", \"chapters[*].content\"]\n * );\n */\n async put(\n namespace: string[],\n key: string,\n value: Record<string, any>,\n index?: false | string[]\n ): Promise<void> {\n validateNamespace(namespace);\n await this.batch<[PutOperation]>([{ namespace, key, value, index }]);\n }\n\n /**\n * Delete an item from the store.\n *\n * @param namespace Hierarchical path for the item\n * @param key Unique identifier within the namespace\n */\n async delete(namespace: string[], key: string): Promise<void> {\n await this.batch<[PutOperation]>([{ namespace, key, value: null }]);\n }\n\n /**\n * List and filter namespaces in the store.\n * Used to explore data organization and navigate the namespace hierarchy.\n *\n * @param options Options for listing namespaces\n * @returns Promise resolving to list of namespace paths\n *\n * @example\n * // List all namespaces under \"documents\"\n * await store.listNamespaces({\n * prefix: [\"documents\"],\n * maxDepth: 2\n * });\n *\n * // List namespaces ending with \"v1\"\n * await store.listNamespaces({\n * suffix: [\"v1\"],\n * limit: 50\n * });\n */\n async listNamespaces(\n options: {\n prefix?: string[];\n suffix?: string[];\n maxDepth?: number;\n limit?: number;\n offset?: number;\n } = {}\n ): Promise<string[][]> {\n const { prefix, suffix, maxDepth, limit = 100, offset = 0 } = options;\n\n const matchConditions: MatchCondition[] = [];\n if (prefix) {\n matchConditions.push({ matchType: \"prefix\", path: prefix });\n }\n if (suffix) {\n matchConditions.push({ matchType: \"suffix\", path: suffix });\n }\n\n return (\n await this.batch<[ListNamespacesOperation]>([\n {\n matchConditions: matchConditions.length ? matchConditions : undefined,\n maxDepth,\n limit,\n offset,\n },\n ])\n )[0];\n }\n\n /**\n * Start the store. Override if initialization is needed.\n */\n start(): void | Promise<void> {}\n\n /**\n * Stop the store. Override if cleanup is needed.\n */\n stop(): void | Promise<void> {}\n}\n"],"mappings":";;;;;AAMA,IAAa,wBAAb,cAA2C,MAAM;CAC/C,YAAY,SAAiB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AW;OAAS;;;;;;;;;;;;;;;;;;;;;;;;CAyBlE,MAAM,OACJ,iBACA,UAKI,IACmB;EACvB,MAAM,EAAE,QAAQ,QAAQ,IAAI,SAAS,GAAG,UAAU;AAClD,UACE,MAAM,KAAK,MAAyB,CAClC;GACE;GACA;GACA;GACA;GACA;OAGJ;;;;;;;;;;;;;;;;;;;;;;;;;CA0BJ,MAAM,IACJ,WACA,KACA,OACA,OACe;AACf,oBAAkB;AAClB,QAAM,KAAK,MAAsB,CAAC;GAAE;GAAW;GAAK;GAAO;;;;;;;;;CAS7D,MAAM,OAAO,WAAqB,KAA4B;AAC5D,QAAM,KAAK,MAAsB,CAAC;GAAE;GAAW;GAAK,OAAO;;;;;;;;;;;;;;;;;;;;;;;CAuB7D,MAAM,eACJ,UAMI,IACiB;EACrB,MAAM,EAAE,QAAQ,QAAQ,UAAU,QAAQ,KAAK,SAAS,MAAM;EAE9D,MAAMC,kBAAoC;AAC1C,MAAI,OACF,iBAAgB,KAAK;GAAE,WAAW;GAAU,MAAM;;AAEpD,MAAI,OACF,iBAAgB,KAAK;GAAE,WAAW;GAAU,MAAM;;AAGpD,UACE,MAAM,KAAK,MAAiC,CAC1C;GACE,iBAAiB,gBAAgB,SAAS,kBAAkB;GAC5D;GACA;GACA;OAGJ;;;;;CAMJ,QAA8B;;;;CAK9B,OAA6B"}
{"version":3,"file":"base.cjs","names":[],"sources":["../../src/store/base.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Embeddings } from \"@langchain/core/embeddings\";\n\n/**\n * Error thrown when an invalid namespace is provided.\n */\nexport class InvalidNamespaceError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"InvalidNamespaceError\";\n }\n}\n\n/**\n * Validates the provided namespace.\n * @param namespace The namespace to validate.\n * @throws {InvalidNamespaceError} If the namespace is invalid.\n */\nfunction validateNamespace(namespace: string[]): void {\n if (namespace.length === 0) {\n throw new InvalidNamespaceError(\"Namespace cannot be empty.\");\n }\n for (const label of namespace) {\n if (typeof label !== \"string\") {\n throw new InvalidNamespaceError(\n `Invalid namespace label '${label}' found in ${namespace}. Namespace labels ` +\n `must be strings, but got ${typeof label}.`\n );\n }\n if (label.includes(\".\")) {\n throw new InvalidNamespaceError(\n `Invalid namespace label '${label}' found in ${namespace}. Namespace labels cannot contain periods ('.').`\n );\n }\n if (label === \"\") {\n throw new InvalidNamespaceError(\n `Namespace labels cannot be empty strings. Got ${label} in ${namespace}`\n );\n }\n }\n if (namespace[0] === \"langgraph\") {\n throw new InvalidNamespaceError(\n `Root label for namespace cannot be \"langgraph\". Got: ${namespace}`\n );\n }\n}\n\n/**\n * Represents a stored item with metadata.\n */\nexport interface Item {\n /**\n * The stored data as an object. Keys are filterable.\n */\n value: Record<string, any>;\n /**\n * Unique identifier within the namespace.\n */\n key: string;\n /**\n * Hierarchical path defining the collection in which this document resides.\n * Represented as an array of strings, allowing for nested categorization.\n * For example: [\"documents\", \"user123\"]\n */\n namespace: string[];\n /**\n * Timestamp of item creation.\n */\n createdAt: Date;\n /**\n * Timestamp of last update.\n */\n updatedAt: Date;\n}\n\n/**\n * Represents a search result item with relevance score.\n * Extends the base Item interface with an optional similarity score.\n */\nexport interface SearchItem extends Item {\n /**\n * Relevance/similarity score if from a ranked operation.\n * Higher scores indicate better matches.\n *\n * This is typically a cosine similarity score between -1 and 1,\n * where 1 indicates identical vectors and -1 indicates opposite vectors.\n */\n score?: number;\n}\n\n/**\n * Operation to retrieve an item by namespace and ID.\n */\nexport interface GetOperation {\n /**\n * Hierarchical path for the item.\n *\n * @example\n * // Get a user profile\n * namespace: [\"users\", \"profiles\"]\n */\n namespace: string[];\n\n /**\n * Unique identifier within the namespace.\n * Together with namespace forms the complete path to the item.\n *\n * @example\n * key: \"user123\" // For a user profile\n * key: \"doc456\" // For a document\n */\n key: string;\n}\n\n/**\n * Operation to search for items within a namespace prefix.\n */\nexport interface SearchOperation {\n /**\n * Hierarchical path prefix to search within.\n * Only items under this prefix will be searched.\n *\n * @example\n * // Search all user documents\n * namespacePrefix: [\"users\", \"documents\"]\n *\n * // Search everything\n * namespacePrefix: []\n */\n namespacePrefix: string[];\n\n /**\n * Key-value pairs to filter results based on exact matches or comparison operators.\n *\n * Supports both exact matches and operator-based comparisons:\n * - $eq: Equal to (same as direct value comparison)\n * - $ne: Not equal to\n * - $gt: Greater than\n * - $gte: Greater than or equal to\n * - $lt: Less than\n * - $lte: Less than or equal to\n *\n * @example\n * // Exact match\n * filter: { status: \"active\" }\n *\n * // With operators\n * filter: { score: { $gt: 4.99 } }\n *\n * // Multiple conditions\n * filter: {\n * score: { $gte: 3.0 },\n * color: \"red\"\n * }\n */\n filter?: Record<string, any>;\n\n /**\n * Maximum number of items to return.\n * @default 10\n */\n limit?: number;\n\n /**\n * Number of items to skip before returning results.\n * Useful for pagination.\n * @default 0\n */\n offset?: number;\n\n /**\n * Natural language search query for semantic search.\n * When provided, results will be ranked by relevance to this query\n * using vector similarity search.\n *\n * @example\n * // Find technical documentation about APIs\n * query: \"technical documentation about REST APIs\"\n *\n * // Find recent ML papers\n * query: \"machine learning papers from 2023\"\n */\n query?: string;\n}\n\n/**\n * Operation to store, update, or delete an item.\n */\nexport interface PutOperation {\n /**\n * Hierarchical path for the item.\n * Acts as a folder-like structure to organize items.\n * Each element represents one level in the hierarchy.\n *\n * @example\n * // Root level documents\n * namespace: [\"documents\"]\n *\n * // User-specific documents\n * namespace: [\"documents\", \"user123\"]\n *\n * // Nested cache structure\n * namespace: [\"cache\", \"docs\", \"v1\"]\n */\n namespace: string[];\n\n /**\n * Unique identifier for the document within its namespace.\n * Together with namespace forms the complete path to the item.\n *\n * Example: If namespace is [\"documents\", \"user123\"] and key is \"report1\",\n * the full path would effectively be \"documents/user123/report1\"\n */\n key: string;\n\n /**\n * Data to be stored, or null to delete the item.\n * Must be a JSON-serializable object with string keys.\n * Setting to null signals that the item should be deleted.\n *\n * @example\n * {\n * field1: \"string value\",\n * field2: 123,\n * nested: { can: \"contain\", any: \"serializable data\" }\n * }\n */\n value: Record<string, any> | null;\n\n /**\n * Controls how the item's fields are indexed for search operations.\n *\n * - undefined: Uses store's default indexing configuration\n * - false: Disables indexing for this item\n * - string[]: List of field paths to index\n *\n * Path syntax supports:\n * - Nested fields: \"metadata.title\"\n * - Array access: \"chapters[*].content\" (each indexed separately)\n * - Specific indices: \"authors[0].name\"\n *\n * @example\n * // Index specific fields\n * index: [\"metadata.title\", \"chapters[*].content\"]\n *\n * // Disable indexing\n * index: false\n */\n index?: false | string[];\n}\n\n/**\n * Operation to list and filter namespaces in the store.\n */\nexport interface ListNamespacesOperation {\n matchConditions?: MatchCondition[];\n maxDepth?: number;\n limit: number;\n offset: number;\n}\n\nexport type NameSpacePath = (string | \"*\")[];\n\nexport type NamespaceMatchType = \"prefix\" | \"suffix\";\n\nexport interface MatchCondition {\n matchType: NamespaceMatchType;\n path: NameSpacePath;\n}\n\nexport type Operation =\n | GetOperation\n | SearchOperation\n | PutOperation\n | ListNamespacesOperation;\n\nexport type OperationResults<Tuple extends readonly Operation[]> = {\n [K in keyof Tuple]: Tuple[K] extends PutOperation\n ? void\n : Tuple[K] extends SearchOperation\n ? SearchItem[]\n : Tuple[K] extends GetOperation\n ? Item | null\n : Tuple[K] extends ListNamespacesOperation\n ? string[][]\n : never;\n};\n\n/**\n * Configuration for indexing documents for semantic search in the store.\n *\n * This configures how documents are embedded and indexed for vector similarity search.\n */\nexport interface IndexConfig {\n /**\n * Number of dimensions in the embedding vectors.\n *\n * Common embedding model dimensions:\n * - OpenAI text-embedding-3-large: 256, 1024, or 3072\n * - OpenAI text-embedding-3-small: 512 or 1536\n * - OpenAI text-embedding-ada-002: 1536\n * - Cohere embed-english-v3.0: 1024\n * - Cohere embed-english-light-v3.0: 384\n * - Cohere embed-multilingual-v3.0: 1024\n * - Cohere embed-multilingual-light-v3.0: 384\n */\n dims: number;\n\n /**\n * The embeddings model to use for generating vectors.\n * This should be a LangChain Embeddings implementation.\n */\n embeddings: Embeddings;\n\n /**\n * Fields to extract text from for embedding generation.\n *\n * Path syntax supports:\n * - Simple field access: \"field\"\n * - Nested fields: \"metadata.title\"\n * - Array indexing:\n * - All elements: \"chapters[*].content\"\n * - Specific index: \"authors[0].name\"\n * - Last element: \"array[-1]\"\n *\n * @default [\"$\"] Embeds the entire document as one vector\n */\n fields?: string[];\n}\n\n/**\n * Utility function to get text at a specific JSON path\n */\nexport function getTextAtPath(obj: any, path: string): string[] {\n const parts = path.split(\".\");\n let current: any = obj;\n\n for (const part of parts) {\n if (part.includes(\"[\")) {\n const [arrayName, indexStr] = part.split(\"[\");\n const index = indexStr.replace(\"]\", \"\");\n\n if (!current[arrayName]) return [];\n\n if (index === \"*\") {\n const results: string[] = [];\n for (const item of current[arrayName]) {\n if (typeof item === \"string\") results.push(item);\n }\n return results;\n }\n\n const idx = parseInt(index, 10);\n if (Number.isNaN(idx)) return [];\n current = current[arrayName][idx];\n } else {\n current = current[part];\n }\n\n if (current === undefined) return [];\n }\n\n return typeof current === \"string\" ? [current] : [];\n}\n\n/**\n * Tokenizes a JSON path into parts\n */\nexport function tokenizePath(path: string): string[] {\n return path.split(\".\");\n}\n\n/**\n * Abstract base class for persistent key-value stores.\n *\n * Stores enable persistence and memory that can be shared across threads,\n * scoped to user IDs, assistant IDs, or other arbitrary namespaces.\n *\n * Features:\n * - Hierarchical namespaces for organization\n * - Key-value storage with metadata\n * - Vector similarity search (if configured)\n * - Filtering and pagination\n */\nexport abstract class BaseStore {\n /**\n * Execute multiple operations in a single batch.\n * This is more efficient than executing operations individually.\n *\n * @param operations Array of operations to execute\n * @returns Promise resolving to results matching the operations\n */\n abstract batch<Op extends Operation[]>(\n operations: Op\n ): Promise<OperationResults<Op>>;\n\n /**\n * Retrieve a single item by its namespace and key.\n *\n * @param namespace Hierarchical path for the item\n * @param key Unique identifier within the namespace\n * @returns Promise resolving to the item or null if not found\n */\n async get(namespace: string[], key: string): Promise<Item | null> {\n return (await this.batch<[GetOperation]>([{ namespace, key }]))[0];\n }\n\n /**\n * Search for items within a namespace prefix.\n * Supports both metadata filtering and vector similarity search.\n *\n * @param namespacePrefix Hierarchical path prefix to search within\n * @param options Search options for filtering and pagination\n * @returns Promise resolving to list of matching items with relevance scores\n *\n * @example\n * // Search with filters\n * await store.search([\"documents\"], {\n * filter: { type: \"report\", status: \"active\" },\n * limit: 5,\n * offset: 10\n * });\n *\n * // Vector similarity search\n * await store.search([\"users\", \"content\"], {\n * query: \"technical documentation about APIs\",\n * limit: 20\n * });\n */\n async search(\n namespacePrefix: string[],\n options: {\n filter?: Record<string, any>;\n limit?: number;\n offset?: number;\n query?: string;\n } = {}\n ): Promise<SearchItem[]> {\n const { filter, limit = 10, offset = 0, query } = options;\n return (\n await this.batch<[SearchOperation]>([\n {\n namespacePrefix,\n filter,\n limit,\n offset,\n query,\n },\n ])\n )[0];\n }\n\n /**\n * Store or update an item.\n *\n * @param namespace Hierarchical path for the item\n * @param key Unique identifier within the namespace\n * @param value Object containing the item's data\n * @param index Optional indexing configuration\n *\n * @example\n * // Simple storage\n * await store.put([\"docs\"], \"report\", { title: \"Annual Report\" });\n *\n * // With specific field indexing\n * await store.put(\n * [\"docs\"],\n * \"report\",\n * {\n * title: \"Q4 Report\",\n * chapters: [{ content: \"...\" }, { content: \"...\" }]\n * },\n * [\"title\", \"chapters[*].content\"]\n * );\n */\n async put(\n namespace: string[],\n key: string,\n value: Record<string, any>,\n index?: false | string[]\n ): Promise<void> {\n validateNamespace(namespace);\n await this.batch<[PutOperation]>([{ namespace, key, value, index }]);\n }\n\n /**\n * Delete an item from the store.\n *\n * @param namespace Hierarchical path for the item\n * @param key Unique identifier within the namespace\n */\n async delete(namespace: string[], key: string): Promise<void> {\n await this.batch<[PutOperation]>([{ namespace, key, value: null }]);\n }\n\n /**\n * List and filter namespaces in the store.\n * Used to explore data organization and navigate the namespace hierarchy.\n *\n * @param options Options for listing namespaces\n * @returns Promise resolving to list of namespace paths\n *\n * @example\n * // List all namespaces under \"documents\"\n * await store.listNamespaces({\n * prefix: [\"documents\"],\n * maxDepth: 2\n * });\n *\n * // List namespaces ending with \"v1\"\n * await store.listNamespaces({\n * suffix: [\"v1\"],\n * limit: 50\n * });\n */\n async listNamespaces(\n options: {\n prefix?: string[];\n suffix?: string[];\n maxDepth?: number;\n limit?: number;\n offset?: number;\n } = {}\n ): Promise<string[][]> {\n const { prefix, suffix, maxDepth, limit = 100, offset = 0 } = options;\n\n const matchConditions: MatchCondition[] = [];\n if (prefix) {\n matchConditions.push({ matchType: \"prefix\", path: prefix });\n }\n if (suffix) {\n matchConditions.push({ matchType: \"suffix\", path: suffix });\n }\n\n return (\n await this.batch<[ListNamespacesOperation]>([\n {\n matchConditions: matchConditions.length ? matchConditions : undefined,\n maxDepth,\n limit,\n offset,\n },\n ])\n )[0];\n }\n\n /**\n * Start the store. Override if initialization is needed.\n */\n start(): void | Promise<void> {}\n\n /**\n * Stop the store. Override if cleanup is needed.\n */\n stop(): void | Promise<void> {}\n}\n"],"mappings":";;;;AAMA,IAAa,wBAAb,cAA2C,MAAM;CAC/C,YAAY,SAAiB;AAC3B,QAAM,QAAQ;AACd,OAAK,OAAO;;;;;;;;AAShB,SAAS,kBAAkB,WAA2B;AACpD,KAAI,UAAU,WAAW,EACvB,OAAM,IAAI,sBAAsB,6BAA6B;AAE/D,MAAK,MAAM,SAAS,WAAW;AAC7B,MAAI,OAAO,UAAU,SACnB,OAAM,IAAI,sBACR,4BAA4B,MAAM,aAAa,UAAU,8CAC3B,OAAO,MAAM,GAC5C;AAEH,MAAI,MAAM,SAAS,IAAI,CACrB,OAAM,IAAI,sBACR,4BAA4B,MAAM,aAAa,UAAU,kDAC1D;AAEH,MAAI,UAAU,GACZ,OAAM,IAAI,sBACR,iDAAiD,MAAM,MAAM,YAC9D;;AAGL,KAAI,UAAU,OAAO,YACnB,OAAM,IAAI,sBACR,wDAAwD,YACzD;;;;;AAkSL,SAAgB,cAAc,KAAU,MAAwB;CAC9D,MAAM,QAAQ,KAAK,MAAM,IAAI;CAC7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4B;AAC5D,QAAM,KAAK,MAAsB,CAAC;GAAE;GAAW;GAAK,OAAO;GAAM,CAAC,CAAC;;;;;;;;;;;;;;;;;;;;;;CAuBrE,MAAM,eACJ,UAMI,EAAE,EACe;EACrB,MAAM,EAAE,QAAQ,QAAQ,UAAU,QAAQ,KAAK,SAAS,MAAM;EAE9D,MAAM,kBAAoC,EAAE;AAC5C,MAAI,OACF,iBAAgB,KAAK;GAAE,WAAW;GAAU,MAAM;GAAQ,CAAC;AAE7D,MAAI,OACF,iBAAgB,KAAK;GAAE,WAAW;GAAU,MAAM;GAAQ,CAAC;AAG7D,UACE,MAAM,KAAK,MAAiC,CAC1C;GACE,iBAAiB,gBAAgB,SAAS,kBAAkB,KAAA;GAC5D;GACA;GACA;GACD,CACF,CAAC,EACF;;;;;CAMJ,QAA8B;;;;CAK9B,OAA6B"}
import { Embeddings } from "@langchain/core/embeddings";
//#region src/store/base.d.ts
/**

@@ -6,0 +5,0 @@ * Error thrown when an invalid namespace is provided.

@@ -1,1 +0,1 @@

{"version":3,"file":"base.d.cts","names":["Embeddings","InvalidNamespaceError","Error","Item","Record","Date","SearchItem","GetOperation","SearchOperation","PutOperation","ListNamespacesOperation","MatchCondition","NameSpacePath","NamespaceMatchType","Operation","OperationResults","Tuple","K","IndexConfig","getTextAtPath","tokenizePath","BaseStore","Op","Promise"],"sources":["../../src/store/base.d.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Embeddings } from \"@langchain/core/embeddings\";\n/**\n * Error thrown when an invalid namespace is provided.\n */\nexport declare class InvalidNamespaceError extends Error {\n constructor(message: string);\n}\n/**\n * Represents a stored item with metadata.\n */\nexport interface Item {\n /**\n * The stored data as an object. Keys are filterable.\n */\n value: Record<string, any>;\n /**\n * Unique identifier within the namespace.\n */\n key: string;\n /**\n * Hierarchical path defining the collection in which this document resides.\n * Represented as an array of strings, allowing for nested categorization.\n * For example: [\"documents\", \"user123\"]\n */\n namespace: string[];\n /**\n * Timestamp of item creation.\n */\n createdAt: Date;\n /**\n * Timestamp of last update.\n */\n updatedAt: Date;\n}\n/**\n * Represents a search result item with relevance score.\n * Extends the base Item interface with an optional similarity score.\n */\nexport interface SearchItem extends Item {\n /**\n * Relevance/similarity score if from a ranked operation.\n * Higher scores indicate better matches.\n *\n * This is typically a cosine similarity score between -1 and 1,\n * where 1 indicates identical vectors and -1 indicates opposite vectors.\n */\n score?: number;\n}\n/**\n * Operation to retrieve an item by namespace and ID.\n */\nexport interface GetOperation {\n /**\n * Hierarchical path for the item.\n *\n * @example\n * // Get a user profile\n * namespace: [\"users\", \"profiles\"]\n */\n namespace: string[];\n /**\n * Unique identifier within the namespace.\n * Together with namespace forms the complete path to the item.\n *\n * @example\n * key: \"user123\" // For a user profile\n * key: \"doc456\" // For a document\n */\n key: string;\n}\n/**\n * Operation to search for items within a namespace prefix.\n */\nexport interface SearchOperation {\n /**\n * Hierarchical path prefix to search within.\n * Only items under this prefix will be searched.\n *\n * @example\n * // Search all user documents\n * namespacePrefix: [\"users\", \"documents\"]\n *\n * // Search everything\n * namespacePrefix: []\n */\n namespacePrefix: string[];\n /**\n * Key-value pairs to filter results based on exact matches or comparison operators.\n *\n * Supports both exact matches and operator-based comparisons:\n * - $eq: Equal to (same as direct value comparison)\n * - $ne: Not equal to\n * - $gt: Greater than\n * - $gte: Greater than or equal to\n * - $lt: Less than\n * - $lte: Less than or equal to\n *\n * @example\n * // Exact match\n * filter: { status: \"active\" }\n *\n * // With operators\n * filter: { score: { $gt: 4.99 } }\n *\n * // Multiple conditions\n * filter: {\n * score: { $gte: 3.0 },\n * color: \"red\"\n * }\n */\n filter?: Record<string, any>;\n /**\n * Maximum number of items to return.\n * @default 10\n */\n limit?: number;\n /**\n * Number of items to skip before returning results.\n * Useful for pagination.\n * @default 0\n */\n offset?: number;\n /**\n * Natural language search query for semantic search.\n * When provided, results will be ranked by relevance to this query\n * using vector similarity search.\n *\n * @example\n * // Find technical documentation about APIs\n * query: \"technical documentation about REST APIs\"\n *\n * // Find recent ML papers\n * query: \"machine learning papers from 2023\"\n */\n query?: string;\n}\n/**\n * Operation to store, update, or delete an item.\n */\nexport interface PutOperation {\n /**\n * Hierarchical path for the item.\n * Acts as a folder-like structure to organize items.\n * Each element represents one level in the hierarchy.\n *\n * @example\n * // Root level documents\n * namespace: [\"documents\"]\n *\n * // User-specific documents\n * namespace: [\"documents\", \"user123\"]\n *\n * // Nested cache structure\n * namespace: [\"cache\", \"docs\", \"v1\"]\n */\n namespace: string[];\n /**\n * Unique identifier for the document within its namespace.\n * Together with namespace forms the complete path to the item.\n *\n * Example: If namespace is [\"documents\", \"user123\"] and key is \"report1\",\n * the full path would effectively be \"documents/user123/report1\"\n */\n key: string;\n /**\n * Data to be stored, or null to delete the item.\n * Must be a JSON-serializable object with string keys.\n * Setting to null signals that the item should be deleted.\n *\n * @example\n * {\n * field1: \"string value\",\n * field2: 123,\n * nested: { can: \"contain\", any: \"serializable data\" }\n * }\n */\n value: Record<string, any> | null;\n /**\n * Controls how the item's fields are indexed for search operations.\n *\n * - undefined: Uses store's default indexing configuration\n * - false: Disables indexing for this item\n * - string[]: List of field paths to index\n *\n * Path syntax supports:\n * - Nested fields: \"metadata.title\"\n * - Array access: \"chapters[*].content\" (each indexed separately)\n * - Specific indices: \"authors[0].name\"\n *\n * @example\n * // Index specific fields\n * index: [\"metadata.title\", \"chapters[*].content\"]\n *\n * // Disable indexing\n * index: false\n */\n index?: false | string[];\n}\n/**\n * Operation to list and filter namespaces in the store.\n */\nexport interface ListNamespacesOperation {\n matchConditions?: MatchCondition[];\n maxDepth?: number;\n limit: number;\n offset: number;\n}\nexport type NameSpacePath = (string | \"*\")[];\nexport type NamespaceMatchType = \"prefix\" | \"suffix\";\nexport interface MatchCondition {\n matchType: NamespaceMatchType;\n path: NameSpacePath;\n}\nexport type Operation = GetOperation | SearchOperation | PutOperation | ListNamespacesOperation;\nexport type OperationResults<Tuple extends readonly Operation[]> = {\n [K in keyof Tuple]: Tuple[K] extends PutOperation ? void : Tuple[K] extends SearchOperation ? SearchItem[] : Tuple[K] extends GetOperation ? Item | null : Tuple[K] extends ListNamespacesOperation ? string[][] : never;\n};\n/**\n * Configuration for indexing documents for semantic search in the store.\n *\n * This configures how documents are embedded and indexed for vector similarity search.\n */\nexport interface IndexConfig {\n /**\n * Number of dimensions in the embedding vectors.\n *\n * Common embedding model dimensions:\n * - OpenAI text-embedding-3-large: 256, 1024, or 3072\n * - OpenAI text-embedding-3-small: 512 or 1536\n * - OpenAI text-embedding-ada-002: 1536\n * - Cohere embed-english-v3.0: 1024\n * - Cohere embed-english-light-v3.0: 384\n * - Cohere embed-multilingual-v3.0: 1024\n * - Cohere embed-multilingual-light-v3.0: 384\n */\n dims: number;\n /**\n * The embeddings model to use for generating vectors.\n * This should be a LangChain Embeddings implementation.\n */\n embeddings: Embeddings;\n /**\n * Fields to extract text from for embedding generation.\n *\n * Path syntax supports:\n * - Simple field access: \"field\"\n * - Nested fields: \"metadata.title\"\n * - Array indexing:\n * - All elements: \"chapters[*].content\"\n * - Specific index: \"authors[0].name\"\n * - Last element: \"array[-1]\"\n *\n * @default [\"$\"] Embeds the entire document as one vector\n */\n fields?: string[];\n}\n/**\n * Utility function to get text at a specific JSON path\n */\nexport declare function getTextAtPath(obj: any, path: string): string[];\n/**\n * Tokenizes a JSON path into parts\n */\nexport declare function tokenizePath(path: string): string[];\n/**\n * Abstract base class for persistent key-value stores.\n *\n * Stores enable persistence and memory that can be shared across threads,\n * scoped to user IDs, assistant IDs, or other arbitrary namespaces.\n *\n * Features:\n * - Hierarchical namespaces for organization\n * - Key-value storage with metadata\n * - Vector similarity search (if configured)\n * - Filtering and pagination\n */\nexport declare abstract class BaseStore {\n /**\n * Execute multiple operations in a single batch.\n * This is more efficient than executing operations individually.\n *\n * @param operations Array of operations to execute\n * @returns Promise resolving to results matching the operations\n */\n abstract batch<Op extends Operation[]>(operations: Op): Promise<OperationResults<Op>>;\n /**\n * Retrieve a single item by its namespace and key.\n *\n * @param namespace Hierarchical path for the item\n * @param key Unique identifier within the namespace\n * @returns Promise resolving to the item or null if not found\n */\n get(namespace: string[], key: string): Promise<Item | null>;\n /**\n * Search for items within a namespace prefix.\n * Supports both metadata filtering and vector similarity search.\n *\n * @param namespacePrefix Hierarchical path prefix to search within\n * @param options Search options for filtering and pagination\n * @returns Promise resolving to list of matching items with relevance scores\n *\n * @example\n * // Search with filters\n * await store.search([\"documents\"], {\n * filter: { type: \"report\", status: \"active\" },\n * limit: 5,\n * offset: 10\n * });\n *\n * // Vector similarity search\n * await store.search([\"users\", \"content\"], {\n * query: \"technical documentation about APIs\",\n * limit: 20\n * });\n */\n search(namespacePrefix: string[], options?: {\n filter?: Record<string, any>;\n limit?: number;\n offset?: number;\n query?: string;\n }): Promise<SearchItem[]>;\n /**\n * Store or update an item.\n *\n * @param namespace Hierarchical path for the item\n * @param key Unique identifier within the namespace\n * @param value Object containing the item's data\n * @param index Optional indexing configuration\n *\n * @example\n * // Simple storage\n * await store.put([\"docs\"], \"report\", { title: \"Annual Report\" });\n *\n * // With specific field indexing\n * await store.put(\n * [\"docs\"],\n * \"report\",\n * {\n * title: \"Q4 Report\",\n * chapters: [{ content: \"...\" }, { content: \"...\" }]\n * },\n * [\"title\", \"chapters[*].content\"]\n * );\n */\n put(namespace: string[], key: string, value: Record<string, any>, index?: false | string[]): Promise<void>;\n /**\n * Delete an item from the store.\n *\n * @param namespace Hierarchical path for the item\n * @param key Unique identifier within the namespace\n */\n delete(namespace: string[], key: string): Promise<void>;\n /**\n * List and filter namespaces in the store.\n * Used to explore data organization and navigate the namespace hierarchy.\n *\n * @param options Options for listing namespaces\n * @returns Promise resolving to list of namespace paths\n *\n * @example\n * // List all namespaces under \"documents\"\n * await store.listNamespaces({\n * prefix: [\"documents\"],\n * maxDepth: 2\n * });\n *\n * // List namespaces ending with \"v1\"\n * await store.listNamespaces({\n * suffix: [\"v1\"],\n * limit: 50\n * });\n */\n listNamespaces(options?: {\n prefix?: string[];\n suffix?: string[];\n maxDepth?: number;\n limit?: number;\n offset?: number;\n }): Promise<string[][]>;\n /**\n * Start the store. Override if initialization is needed.\n */\n start(): void | Promise<void>;\n /**\n * Stop the store. Override if cleanup is needed.\n */\n stop(): void | Promise<void>;\n}\n"],"mappings":";;;;;AAKA;AAMA;AAAqB,cANAC,qBAAAA,SAA8BC,KAAAA,CAM9B;aAIVE,CAAAA,OAAAA,EAAAA,MAAAA;;;;AAwBX;AAaiBG,UAzCAJ,IAAAA,CAyCY;EAsBZK;AAkEjB;AA8DA;EAMYI,KAAAA,EAjMDR,MAiMCQ,CAAAA,MAAa,EAAA,GAAA,CAAA;EACbC;AACZ;;KACeA,EAAAA,MAAAA;;;AAGf;;;WAAuCL,EAAAA,MAAAA,EAAAA;;;;EAC3BO,SAAAA,EA1LGV,IA0LHU;EAAgB;;;WACJC,EAvLTX,IAuLSW;;;;;;AAA0EV,UAjLjFA,UAAAA,SAAmBH,IAiL8DG,CAAAA;;;;;;;;;AAOlG;AAqCA;AAIA;AAaA;AAAuC,UAjOtBC,YAAAA,CAiOsB;;;;;;;;WAwCtBH,EAAAA,MAAAA,EAAAA;;;;;;;;;;;;;;UAnPAI,eAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;WAqCJJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA6BIK,YAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;SAqCNL;;;;;;;;;;;;;;;;;;;;;;;;;UAyBMM,uBAAAA;oBACKC;;;;;KAKVC,aAAAA;KACAC,kBAAAA;UACKF,cAAAA;aACFE;QACLD;;KAEEE,SAAAA,GAAYP,eAAeC,kBAAkBC,eAAeC;KAC5DK,wCAAwCD,6BACpCE,QAAQA,MAAMC,WAAWR,sBAAsBO,MAAMC,WAAWT,kBAAkBF,eAAeU,MAAMC,WAAWV,eAAeJ,cAAca,MAAMC,WAAWP;;;;;;UAO/JQ,WAAAA;;;;;;;;;;;;;;;;;;cAkBDlB;;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IACE,MAAA;IACA,MAAA;IACA,QAAA;IACA,KAAA;IACA,MAAA;EAAA,IAED,OAAA;;;;EA0BH,KAAA,CAAA,UAAgB,OAAA;;;;EAKhB,IAAA,CAAA,UAAe,OAAA;AAAA"}
import { Embeddings } from "@langchain/core/embeddings";
//#region src/store/base.d.ts
/**

@@ -6,0 +5,0 @@ * Error thrown when an invalid namespace is provided.

@@ -1,1 +0,1 @@

{"version":3,"file":"base.d.ts","names":["Embeddings","InvalidNamespaceError","Error","Item","Record","Date","SearchItem","GetOperation","SearchOperation","PutOperation","ListNamespacesOperation","MatchCondition","NameSpacePath","NamespaceMatchType","Operation","OperationResults","Tuple","K","IndexConfig","getTextAtPath","tokenizePath","BaseStore","Op","Promise"],"sources":["../../src/store/base.d.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Embeddings } from \"@langchain/core/embeddings\";\n/**\n * Error thrown when an invalid namespace is provided.\n */\nexport declare class InvalidNamespaceError extends Error {\n constructor(message: string);\n}\n/**\n * Represents a stored item with metadata.\n */\nexport interface Item {\n /**\n * The stored data as an object. Keys are filterable.\n */\n value: Record<string, any>;\n /**\n * Unique identifier within the namespace.\n */\n key: string;\n /**\n * Hierarchical path defining the collection in which this document resides.\n * Represented as an array of strings, allowing for nested categorization.\n * For example: [\"documents\", \"user123\"]\n */\n namespace: string[];\n /**\n * Timestamp of item creation.\n */\n createdAt: Date;\n /**\n * Timestamp of last update.\n */\n updatedAt: Date;\n}\n/**\n * Represents a search result item with relevance score.\n * Extends the base Item interface with an optional similarity score.\n */\nexport interface SearchItem extends Item {\n /**\n * Relevance/similarity score if from a ranked operation.\n * Higher scores indicate better matches.\n *\n * This is typically a cosine similarity score between -1 and 1,\n * where 1 indicates identical vectors and -1 indicates opposite vectors.\n */\n score?: number;\n}\n/**\n * Operation to retrieve an item by namespace and ID.\n */\nexport interface GetOperation {\n /**\n * Hierarchical path for the item.\n *\n * @example\n * // Get a user profile\n * namespace: [\"users\", \"profiles\"]\n */\n namespace: string[];\n /**\n * Unique identifier within the namespace.\n * Together with namespace forms the complete path to the item.\n *\n * @example\n * key: \"user123\" // For a user profile\n * key: \"doc456\" // For a document\n */\n key: string;\n}\n/**\n * Operation to search for items within a namespace prefix.\n */\nexport interface SearchOperation {\n /**\n * Hierarchical path prefix to search within.\n * Only items under this prefix will be searched.\n *\n * @example\n * // Search all user documents\n * namespacePrefix: [\"users\", \"documents\"]\n *\n * // Search everything\n * namespacePrefix: []\n */\n namespacePrefix: string[];\n /**\n * Key-value pairs to filter results based on exact matches or comparison operators.\n *\n * Supports both exact matches and operator-based comparisons:\n * - $eq: Equal to (same as direct value comparison)\n * - $ne: Not equal to\n * - $gt: Greater than\n * - $gte: Greater than or equal to\n * - $lt: Less than\n * - $lte: Less than or equal to\n *\n * @example\n * // Exact match\n * filter: { status: \"active\" }\n *\n * // With operators\n * filter: { score: { $gt: 4.99 } }\n *\n * // Multiple conditions\n * filter: {\n * score: { $gte: 3.0 },\n * color: \"red\"\n * }\n */\n filter?: Record<string, any>;\n /**\n * Maximum number of items to return.\n * @default 10\n */\n limit?: number;\n /**\n * Number of items to skip before returning results.\n * Useful for pagination.\n * @default 0\n */\n offset?: number;\n /**\n * Natural language search query for semantic search.\n * When provided, results will be ranked by relevance to this query\n * using vector similarity search.\n *\n * @example\n * // Find technical documentation about APIs\n * query: \"technical documentation about REST APIs\"\n *\n * // Find recent ML papers\n * query: \"machine learning papers from 2023\"\n */\n query?: string;\n}\n/**\n * Operation to store, update, or delete an item.\n */\nexport interface PutOperation {\n /**\n * Hierarchical path for the item.\n * Acts as a folder-like structure to organize items.\n * Each element represents one level in the hierarchy.\n *\n * @example\n * // Root level documents\n * namespace: [\"documents\"]\n *\n * // User-specific documents\n * namespace: [\"documents\", \"user123\"]\n *\n * // Nested cache structure\n * namespace: [\"cache\", \"docs\", \"v1\"]\n */\n namespace: string[];\n /**\n * Unique identifier for the document within its namespace.\n * Together with namespace forms the complete path to the item.\n *\n * Example: If namespace is [\"documents\", \"user123\"] and key is \"report1\",\n * the full path would effectively be \"documents/user123/report1\"\n */\n key: string;\n /**\n * Data to be stored, or null to delete the item.\n * Must be a JSON-serializable object with string keys.\n * Setting to null signals that the item should be deleted.\n *\n * @example\n * {\n * field1: \"string value\",\n * field2: 123,\n * nested: { can: \"contain\", any: \"serializable data\" }\n * }\n */\n value: Record<string, any> | null;\n /**\n * Controls how the item's fields are indexed for search operations.\n *\n * - undefined: Uses store's default indexing configuration\n * - false: Disables indexing for this item\n * - string[]: List of field paths to index\n *\n * Path syntax supports:\n * - Nested fields: \"metadata.title\"\n * - Array access: \"chapters[*].content\" (each indexed separately)\n * - Specific indices: \"authors[0].name\"\n *\n * @example\n * // Index specific fields\n * index: [\"metadata.title\", \"chapters[*].content\"]\n *\n * // Disable indexing\n * index: false\n */\n index?: false | string[];\n}\n/**\n * Operation to list and filter namespaces in the store.\n */\nexport interface ListNamespacesOperation {\n matchConditions?: MatchCondition[];\n maxDepth?: number;\n limit: number;\n offset: number;\n}\nexport type NameSpacePath = (string | \"*\")[];\nexport type NamespaceMatchType = \"prefix\" | \"suffix\";\nexport interface MatchCondition {\n matchType: NamespaceMatchType;\n path: NameSpacePath;\n}\nexport type Operation = GetOperation | SearchOperation | PutOperation | ListNamespacesOperation;\nexport type OperationResults<Tuple extends readonly Operation[]> = {\n [K in keyof Tuple]: Tuple[K] extends PutOperation ? void : Tuple[K] extends SearchOperation ? SearchItem[] : Tuple[K] extends GetOperation ? Item | null : Tuple[K] extends ListNamespacesOperation ? string[][] : never;\n};\n/**\n * Configuration for indexing documents for semantic search in the store.\n *\n * This configures how documents are embedded and indexed for vector similarity search.\n */\nexport interface IndexConfig {\n /**\n * Number of dimensions in the embedding vectors.\n *\n * Common embedding model dimensions:\n * - OpenAI text-embedding-3-large: 256, 1024, or 3072\n * - OpenAI text-embedding-3-small: 512 or 1536\n * - OpenAI text-embedding-ada-002: 1536\n * - Cohere embed-english-v3.0: 1024\n * - Cohere embed-english-light-v3.0: 384\n * - Cohere embed-multilingual-v3.0: 1024\n * - Cohere embed-multilingual-light-v3.0: 384\n */\n dims: number;\n /**\n * The embeddings model to use for generating vectors.\n * This should be a LangChain Embeddings implementation.\n */\n embeddings: Embeddings;\n /**\n * Fields to extract text from for embedding generation.\n *\n * Path syntax supports:\n * - Simple field access: \"field\"\n * - Nested fields: \"metadata.title\"\n * - Array indexing:\n * - All elements: \"chapters[*].content\"\n * - Specific index: \"authors[0].name\"\n * - Last element: \"array[-1]\"\n *\n * @default [\"$\"] Embeds the entire document as one vector\n */\n fields?: string[];\n}\n/**\n * Utility function to get text at a specific JSON path\n */\nexport declare function getTextAtPath(obj: any, path: string): string[];\n/**\n * Tokenizes a JSON path into parts\n */\nexport declare function tokenizePath(path: string): string[];\n/**\n * Abstract base class for persistent key-value stores.\n *\n * Stores enable persistence and memory that can be shared across threads,\n * scoped to user IDs, assistant IDs, or other arbitrary namespaces.\n *\n * Features:\n * - Hierarchical namespaces for organization\n * - Key-value storage with metadata\n * - Vector similarity search (if configured)\n * - Filtering and pagination\n */\nexport declare abstract class BaseStore {\n /**\n * Execute multiple operations in a single batch.\n * This is more efficient than executing operations individually.\n *\n * @param operations Array of operations to execute\n * @returns Promise resolving to results matching the operations\n */\n abstract batch<Op extends Operation[]>(operations: Op): Promise<OperationResults<Op>>;\n /**\n * Retrieve a single item by its namespace and key.\n *\n * @param namespace Hierarchical path for the item\n * @param key Unique identifier within the namespace\n * @returns Promise resolving to the item or null if not found\n */\n get(namespace: string[], key: string): Promise<Item | null>;\n /**\n * Search for items within a namespace prefix.\n * Supports both metadata filtering and vector similarity search.\n *\n * @param namespacePrefix Hierarchical path prefix to search within\n * @param options Search options for filtering and pagination\n * @returns Promise resolving to list of matching items with relevance scores\n *\n * @example\n * // Search with filters\n * await store.search([\"documents\"], {\n * filter: { type: \"report\", status: \"active\" },\n * limit: 5,\n * offset: 10\n * });\n *\n * // Vector similarity search\n * await store.search([\"users\", \"content\"], {\n * query: \"technical documentation about APIs\",\n * limit: 20\n * });\n */\n search(namespacePrefix: string[], options?: {\n filter?: Record<string, any>;\n limit?: number;\n offset?: number;\n query?: string;\n }): Promise<SearchItem[]>;\n /**\n * Store or update an item.\n *\n * @param namespace Hierarchical path for the item\n * @param key Unique identifier within the namespace\n * @param value Object containing the item's data\n * @param index Optional indexing configuration\n *\n * @example\n * // Simple storage\n * await store.put([\"docs\"], \"report\", { title: \"Annual Report\" });\n *\n * // With specific field indexing\n * await store.put(\n * [\"docs\"],\n * \"report\",\n * {\n * title: \"Q4 Report\",\n * chapters: [{ content: \"...\" }, { content: \"...\" }]\n * },\n * [\"title\", \"chapters[*].content\"]\n * );\n */\n put(namespace: string[], key: string, value: Record<string, any>, index?: false | string[]): Promise<void>;\n /**\n * Delete an item from the store.\n *\n * @param namespace Hierarchical path for the item\n * @param key Unique identifier within the namespace\n */\n delete(namespace: string[], key: string): Promise<void>;\n /**\n * List and filter namespaces in the store.\n * Used to explore data organization and navigate the namespace hierarchy.\n *\n * @param options Options for listing namespaces\n * @returns Promise resolving to list of namespace paths\n *\n * @example\n * // List all namespaces under \"documents\"\n * await store.listNamespaces({\n * prefix: [\"documents\"],\n * maxDepth: 2\n * });\n *\n * // List namespaces ending with \"v1\"\n * await store.listNamespaces({\n * suffix: [\"v1\"],\n * limit: 50\n * });\n */\n listNamespaces(options?: {\n prefix?: string[];\n suffix?: string[];\n maxDepth?: number;\n limit?: number;\n offset?: number;\n }): Promise<string[][]>;\n /**\n * Start the store. Override if initialization is needed.\n */\n start(): void | Promise<void>;\n /**\n * Stop the store. Override if cleanup is needed.\n */\n stop(): void | Promise<void>;\n}\n"],"mappings":";;;;;AAKA;AAMA;AAAqB,cANAC,qBAAAA,SAA8BC,KAAAA,CAM9B;aAIVE,CAAAA,OAAAA,EAAAA,MAAAA;;;;AAwBX;AAaiBG,UAzCAJ,IAAAA,CAyCY;EAsBZK;AAkEjB;AA8DA;EAMYI,KAAAA,EAjMDR,MAiMCQ,CAAAA,MAAa,EAA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AAA,KACA,KAAA,CAAM,CAAA,UAAW,YAAA,GACjB,IAAA,UACA,KAAA,CAAM,CAAA,UAAW,uBAAA;;;;;;UAUN,WAAA;EAsMmB;;;;;;;;;;;;EAzLlC,IAAA;EAwPe;;;;EAlPf,UAAA,EAAY,UAAA;;;;;;;;;;;;;;EAeZ,MAAA;AAAA;;;;iBAMc,aAAA,CAAc,GAAA,OAAU,IAAA;;;;iBAmCxB,YAAA,CAAa,IAAA;;;;;;;;;;;;;uBAgBP,SAAA;;;;;;;;WAQX,KAAA,YAAiB,SAAA,GAAA,CACxB,UAAA,EAAY,EAAA,GACX,OAAA,CAAQ,gBAAA,CAAiB,EAAA;;;;;;;;EAStB,GAAA,CAAI,SAAA,YAAqB,GAAA,WAAc,OAAA,CAAQ,IAAA;;;;;;;;;;;;;;;;;;;;;;;EA0B/C,MAAA,CACJ,eAAA,YACA,OAAA;IACE,MAAA,GAAS,MAAA;IACT,KAAA;IACA,MAAA;IACA,KAAA;EAAA,IAED,OAAA,CAAQ,UAAA;;;;;;;;;;;;;;;;;;;;;;;;EAsCL,GAAA,CACJ,SAAA,YACA,GAAA,UACA,KAAA,EAAO,MAAA,eACP,KAAA,sBACC,OAAA;;;;;;;EAWG,MAAA,CAAO,SAAA,YAAqB,GAAA,WAAc,OAAA;;;;;;;;;;;;;;;;;;;;;EAwB1C,cAAA,CACJ,OAAA;IACE,MAAA;IACA,MAAA;IACA,QAAA;IACA,KAAA;IACA,MAAA;EAAA,IAED,OAAA;;;;EA0BH,KAAA,CAAA,UAAgB,OAAA;;;;EAKhB,IAAA,CAAA,UAAe,OAAA;AAAA"}

@@ -205,5 +205,5 @@ //#region src/store/base.ts

};
//#endregion
export { BaseStore, InvalidNamespaceError, getTextAtPath, tokenizePath };
//# sourceMappingURL=base.js.map

@@ -1,1 +0,1 @@

{"version":3,"file":"base.js","names":["current: any","results: string[]","matchConditions: MatchCondition[]"],"sources":["../../src/store/base.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Embeddings } from \"@langchain/core/embeddings\";\n\n/**\n * Error thrown when an invalid namespace is provided.\n */\nexport class InvalidNamespaceError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"InvalidNamespaceError\";\n }\n}\n\n/**\n * Validates the provided namespace.\n * @param namespace The namespace to validate.\n * @throws {InvalidNamespaceError} If the namespace is invalid.\n */\nfunction validateNamespace(namespace: string[]): void {\n if (namespace.length === 0) {\n throw new InvalidNamespaceError(\"Namespace cannot be empty.\");\n }\n for (const label of namespace) {\n if (typeof label !== \"string\") {\n throw new InvalidNamespaceError(\n `Invalid namespace label '${label}' found in ${namespace}. Namespace labels ` +\n `must be strings, but got ${typeof label}.`\n );\n }\n if (label.includes(\".\")) {\n throw new InvalidNamespaceError(\n `Invalid namespace label '${label}' found in ${namespace}. Namespace labels cannot contain periods ('.').`\n );\n }\n if (label === \"\") {\n throw new InvalidNamespaceError(\n `Namespace labels cannot be empty strings. Got ${label} in ${namespace}`\n );\n }\n }\n if (namespace[0] === \"langgraph\") {\n throw new InvalidNamespaceError(\n `Root label for namespace cannot be \"langgraph\". Got: ${namespace}`\n );\n }\n}\n\n/**\n * Represents a stored item with metadata.\n */\nexport interface Item {\n /**\n * The stored data as an object. Keys are filterable.\n */\n value: Record<string, any>;\n /**\n * Unique identifier within the namespace.\n */\n key: string;\n /**\n * Hierarchical path defining the collection in which this document resides.\n * Represented as an array of strings, allowing for nested categorization.\n * For example: [\"documents\", \"user123\"]\n */\n namespace: string[];\n /**\n * Timestamp of item creation.\n */\n createdAt: Date;\n /**\n * Timestamp of last update.\n */\n updatedAt: Date;\n}\n\n/**\n * Represents a search result item with relevance score.\n * Extends the base Item interface with an optional similarity score.\n */\nexport interface SearchItem extends Item {\n /**\n * Relevance/similarity score if from a ranked operation.\n * Higher scores indicate better matches.\n *\n * This is typically a cosine similarity score between -1 and 1,\n * where 1 indicates identical vectors and -1 indicates opposite vectors.\n */\n score?: number;\n}\n\n/**\n * Operation to retrieve an item by namespace and ID.\n */\nexport interface GetOperation {\n /**\n * Hierarchical path for the item.\n *\n * @example\n * // Get a user profile\n * namespace: [\"users\", \"profiles\"]\n */\n namespace: string[];\n\n /**\n * Unique identifier within the namespace.\n * Together with namespace forms the complete path to the item.\n *\n * @example\n * key: \"user123\" // For a user profile\n * key: \"doc456\" // For a document\n */\n key: string;\n}\n\n/**\n * Operation to search for items within a namespace prefix.\n */\nexport interface SearchOperation {\n /**\n * Hierarchical path prefix to search within.\n * Only items under this prefix will be searched.\n *\n * @example\n * // Search all user documents\n * namespacePrefix: [\"users\", \"documents\"]\n *\n * // Search everything\n * namespacePrefix: []\n */\n namespacePrefix: string[];\n\n /**\n * Key-value pairs to filter results based on exact matches or comparison operators.\n *\n * Supports both exact matches and operator-based comparisons:\n * - $eq: Equal to (same as direct value comparison)\n * - $ne: Not equal to\n * - $gt: Greater than\n * - $gte: Greater than or equal to\n * - $lt: Less than\n * - $lte: Less than or equal to\n *\n * @example\n * // Exact match\n * filter: { status: \"active\" }\n *\n * // With operators\n * filter: { score: { $gt: 4.99 } }\n *\n * // Multiple conditions\n * filter: {\n * score: { $gte: 3.0 },\n * color: \"red\"\n * }\n */\n filter?: Record<string, any>;\n\n /**\n * Maximum number of items to return.\n * @default 10\n */\n limit?: number;\n\n /**\n * Number of items to skip before returning results.\n * Useful for pagination.\n * @default 0\n */\n offset?: number;\n\n /**\n * Natural language search query for semantic search.\n * When provided, results will be ranked by relevance to this query\n * using vector similarity search.\n *\n * @example\n * // Find technical documentation about APIs\n * query: \"technical documentation about REST APIs\"\n *\n * // Find recent ML papers\n * query: \"machine learning papers from 2023\"\n */\n query?: string;\n}\n\n/**\n * Operation to store, update, or delete an item.\n */\nexport interface PutOperation {\n /**\n * Hierarchical path for the item.\n * Acts as a folder-like structure to organize items.\n * Each element represents one level in the hierarchy.\n *\n * @example\n * // Root level documents\n * namespace: [\"documents\"]\n *\n * // User-specific documents\n * namespace: [\"documents\", \"user123\"]\n *\n * // Nested cache structure\n * namespace: [\"cache\", \"docs\", \"v1\"]\n */\n namespace: string[];\n\n /**\n * Unique identifier for the document within its namespace.\n * Together with namespace forms the complete path to the item.\n *\n * Example: If namespace is [\"documents\", \"user123\"] and key is \"report1\",\n * the full path would effectively be \"documents/user123/report1\"\n */\n key: string;\n\n /**\n * Data to be stored, or null to delete the item.\n * Must be a JSON-serializable object with string keys.\n * Setting to null signals that the item should be deleted.\n *\n * @example\n * {\n * field1: \"string value\",\n * field2: 123,\n * nested: { can: \"contain\", any: \"serializable data\" }\n * }\n */\n value: Record<string, any> | null;\n\n /**\n * Controls how the item's fields are indexed for search operations.\n *\n * - undefined: Uses store's default indexing configuration\n * - false: Disables indexing for this item\n * - string[]: List of field paths to index\n *\n * Path syntax supports:\n * - Nested fields: \"metadata.title\"\n * - Array access: \"chapters[*].content\" (each indexed separately)\n * - Specific indices: \"authors[0].name\"\n *\n * @example\n * // Index specific fields\n * index: [\"metadata.title\", \"chapters[*].content\"]\n *\n * // Disable indexing\n * index: false\n */\n index?: false | string[];\n}\n\n/**\n * Operation to list and filter namespaces in the store.\n */\nexport interface ListNamespacesOperation {\n matchConditions?: MatchCondition[];\n maxDepth?: number;\n limit: number;\n offset: number;\n}\n\nexport type NameSpacePath = (string | \"*\")[];\n\nexport type NamespaceMatchType = \"prefix\" | \"suffix\";\n\nexport interface MatchCondition {\n matchType: NamespaceMatchType;\n path: NameSpacePath;\n}\n\nexport type Operation =\n | GetOperation\n | SearchOperation\n | PutOperation\n | ListNamespacesOperation;\n\nexport type OperationResults<Tuple extends readonly Operation[]> = {\n [K in keyof Tuple]: Tuple[K] extends PutOperation\n ? void\n : Tuple[K] extends SearchOperation\n ? SearchItem[]\n : Tuple[K] extends GetOperation\n ? Item | null\n : Tuple[K] extends ListNamespacesOperation\n ? string[][]\n : never;\n};\n\n/**\n * Configuration for indexing documents for semantic search in the store.\n *\n * This configures how documents are embedded and indexed for vector similarity search.\n */\nexport interface IndexConfig {\n /**\n * Number of dimensions in the embedding vectors.\n *\n * Common embedding model dimensions:\n * - OpenAI text-embedding-3-large: 256, 1024, or 3072\n * - OpenAI text-embedding-3-small: 512 or 1536\n * - OpenAI text-embedding-ada-002: 1536\n * - Cohere embed-english-v3.0: 1024\n * - Cohere embed-english-light-v3.0: 384\n * - Cohere embed-multilingual-v3.0: 1024\n * - Cohere embed-multilingual-light-v3.0: 384\n */\n dims: number;\n\n /**\n * The embeddings model to use for generating vectors.\n * This should be a LangChain Embeddings implementation.\n */\n embeddings: Embeddings;\n\n /**\n * Fields to extract text from for embedding generation.\n *\n * Path syntax supports:\n * - Simple field access: \"field\"\n * - Nested fields: \"metadata.title\"\n * - Array indexing:\n * - All elements: \"chapters[*].content\"\n * - Specific index: \"authors[0].name\"\n * - Last element: \"array[-1]\"\n *\n * @default [\"$\"] Embeds the entire document as one vector\n */\n fields?: string[];\n}\n\n/**\n * Utility function to get text at a specific JSON path\n */\nexport function getTextAtPath(obj: any, path: string): string[] {\n const parts = path.split(\".\");\n let current: any = obj;\n\n for (const part of parts) {\n if (part.includes(\"[\")) {\n const [arrayName, indexStr] = part.split(\"[\");\n const index = indexStr.replace(\"]\", \"\");\n\n if (!current[arrayName]) return [];\n\n if (index === \"*\") {\n const results: string[] = [];\n for (const item of current[arrayName]) {\n if (typeof item === \"string\") results.push(item);\n }\n return results;\n }\n\n const idx = parseInt(index, 10);\n if (Number.isNaN(idx)) return [];\n current = current[arrayName][idx];\n } else {\n current = current[part];\n }\n\n if (current === undefined) return [];\n }\n\n return typeof current === \"string\" ? [current] : [];\n}\n\n/**\n * Tokenizes a JSON path into parts\n */\nexport function tokenizePath(path: string): string[] {\n return path.split(\".\");\n}\n\n/**\n * Abstract base class for persistent key-value stores.\n *\n * Stores enable persistence and memory that can be shared across threads,\n * scoped to user IDs, assistant IDs, or other arbitrary namespaces.\n *\n * Features:\n * - Hierarchical namespaces for organization\n * - Key-value storage with metadata\n * - Vector similarity search (if configured)\n * - Filtering and pagination\n */\nexport abstract class BaseStore {\n /**\n * Execute multiple operations in a single batch.\n * This is more efficient than executing operations individually.\n *\n * @param operations Array of operations to execute\n * @returns Promise resolving to results matching the operations\n */\n abstract batch<Op extends Operation[]>(\n operations: Op\n ): Promise<OperationResults<Op>>;\n\n /**\n * Retrieve a single item by its namespace and key.\n *\n * @param namespace Hierarchical path for the item\n * @param key Unique identifier within the namespace\n * @returns Promise resolving to the item or null if not found\n */\n async get(namespace: string[], key: string): Promise<Item | null> {\n return (await this.batch<[GetOperation]>([{ namespace, key }]))[0];\n }\n\n /**\n * Search for items within a namespace prefix.\n * Supports both metadata filtering and vector similarity search.\n *\n * @param namespacePrefix Hierarchical path prefix to search within\n * @param options Search options for filtering and pagination\n * @returns Promise resolving to list of matching items with relevance scores\n *\n * @example\n * // Search with filters\n * await store.search([\"documents\"], {\n * filter: { type: \"report\", status: \"active\" },\n * limit: 5,\n * offset: 10\n * });\n *\n * // Vector similarity search\n * await store.search([\"users\", \"content\"], {\n * query: \"technical documentation about APIs\",\n * limit: 20\n * });\n */\n async search(\n namespacePrefix: string[],\n options: {\n filter?: Record<string, any>;\n limit?: number;\n offset?: number;\n query?: string;\n } = {}\n ): Promise<SearchItem[]> {\n const { filter, limit = 10, offset = 0, query } = options;\n return (\n await this.batch<[SearchOperation]>([\n {\n namespacePrefix,\n filter,\n limit,\n offset,\n query,\n },\n ])\n )[0];\n }\n\n /**\n * Store or update an item.\n *\n * @param namespace Hierarchical path for the item\n * @param key Unique identifier within the namespace\n * @param value Object containing the item's data\n * @param index Optional indexing configuration\n *\n * @example\n * // Simple storage\n * await store.put([\"docs\"], \"report\", { title: \"Annual Report\" });\n *\n * // With specific field indexing\n * await store.put(\n * [\"docs\"],\n * \"report\",\n * {\n * title: \"Q4 Report\",\n * chapters: [{ content: \"...\" }, { content: \"...\" }]\n * },\n * [\"title\", \"chapters[*].content\"]\n * );\n */\n async put(\n namespace: string[],\n key: string,\n value: Record<string, any>,\n index?: false | string[]\n ): Promise<void> {\n validateNamespace(namespace);\n await this.batch<[PutOperation]>([{ namespace, key, value, index }]);\n }\n\n /**\n * Delete an item from the store.\n *\n * @param namespace Hierarchical path for the item\n * @param key Unique identifier within the namespace\n */\n async delete(namespace: string[], key: string): Promise<void> {\n await this.batch<[PutOperation]>([{ namespace, key, value: null }]);\n }\n\n /**\n * List and filter namespaces in the store.\n * Used to explore data organization and navigate the namespace hierarchy.\n *\n * @param options Options for listing namespaces\n * @returns Promise resolving to list of namespace paths\n *\n * @example\n * // List all namespaces under \"documents\"\n * await store.listNamespaces({\n * prefix: [\"documents\"],\n * maxDepth: 2\n * });\n *\n * // List namespaces ending with \"v1\"\n * await store.listNamespaces({\n * suffix: [\"v1\"],\n * limit: 50\n * });\n */\n async listNamespaces(\n options: {\n prefix?: string[];\n suffix?: string[];\n maxDepth?: number;\n limit?: number;\n offset?: number;\n } = {}\n ): Promise<string[][]> {\n const { prefix, suffix, maxDepth, limit = 100, offset = 0 } = options;\n\n const matchConditions: MatchCondition[] = [];\n if (prefix) {\n matchConditions.push({ matchType: \"prefix\", path: prefix });\n }\n if (suffix) {\n matchConditions.push({ matchType: \"suffix\", path: suffix });\n }\n\n return (\n await this.batch<[ListNamespacesOperation]>([\n {\n matchConditions: matchConditions.length ? matchConditions : undefined,\n maxDepth,\n limit,\n offset,\n },\n ])\n )[0];\n }\n\n /**\n * Start the store. Override if initialization is needed.\n */\n start(): void | Promise<void> {}\n\n /**\n * Stop the store. Override if cleanup is needed.\n */\n stop(): void | Promise<void> {}\n}\n"],"mappings":";;;;AAMA,IAAa,wBAAb,cAA2C,MAAM;CAC/C,YAAY,SAAiB;AAC3B,QAAM;AACN,OAAK,OAAO;;;;;;;;AAShB,SAAS,kBAAkB,WAA2B;AACpD,KAAI,UAAU,WAAW,EACvB,OAAM,IAAI,sBAAsB;AAElC,MAAK,MAAM,SAAS,WAAW;AAC7B,MAAI,OAAO,UAAU,SACnB,OAAM,IAAI,sBACR,4BAA4B,MAAM,aAAa,UAAU,8CAC3B,OAAO,MAAM;AAG/C,M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,KACA,OACA,OACe;AACf,oBAAkB;AAClB,QAAM,KAAK,MAAsB,CAAC;GAAE;GAAW;GAAK;GAAO;;;;;;;;;CAS7D,MAAM,OAAO,WAAqB,KAA4B;AAC5D,QAAM,KAAK,MAAsB,CAAC;GAAE;GAAW;GAAK,OAAO;;;;;;;;;;;;;;;;;;;;;;;CAuB7D,MAAM,eACJ,UAMI,IACiB;EACrB,MAAM,EAAE,QAAQ,QAAQ,UAAU,QAAQ,KAAK,SAAS,MAAM;EAE9D,MAAMC,kBAAoC;AAC1C,MAAI,OACF,iBAAgB,KAAK;GAAE,WAAW;GAAU,MAAM;;AAEpD,MAAI,OACF,iBAAgB,KAAK;GAAE,WAAW;GAAU,MAAM;;AAGpD,UACE,MAAM,KAAK,MAAiC,CAC1C;GACE,iBAAiB,gBAAgB,SAAS,kBAAkB;GAC5D;GACA;GACA;OAGJ;;;;;CAMJ,QAA8B;;;;CAK9B,OAA6B"}
{"version":3,"file":"base.js","names":[],"sources":["../../src/store/base.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Embeddings } from \"@langchain/core/embeddings\";\n\n/**\n * Error thrown when an invalid namespace is provided.\n */\nexport class InvalidNamespaceError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"InvalidNamespaceError\";\n }\n}\n\n/**\n * Validates the provided namespace.\n * @param namespace The namespace to validate.\n * @throws {InvalidNamespaceError} If the namespace is invalid.\n */\nfunction validateNamespace(namespace: string[]): void {\n if (namespace.length === 0) {\n throw new InvalidNamespaceError(\"Namespace cannot be empty.\");\n }\n for (const label of namespace) {\n if (typeof label !== \"string\") {\n throw new InvalidNamespaceError(\n `Invalid namespace label '${label}' found in ${namespace}. Namespace labels ` +\n `must be strings, but got ${typeof label}.`\n );\n }\n if (label.includes(\".\")) {\n throw new InvalidNamespaceError(\n `Invalid namespace label '${label}' found in ${namespace}. Namespace labels cannot contain periods ('.').`\n );\n }\n if (label === \"\") {\n throw new InvalidNamespaceError(\n `Namespace labels cannot be empty strings. Got ${label} in ${namespace}`\n );\n }\n }\n if (namespace[0] === \"langgraph\") {\n throw new InvalidNamespaceError(\n `Root label for namespace cannot be \"langgraph\". Got: ${namespace}`\n );\n }\n}\n\n/**\n * Represents a stored item with metadata.\n */\nexport interface Item {\n /**\n * The stored data as an object. Keys are filterable.\n */\n value: Record<string, any>;\n /**\n * Unique identifier within the namespace.\n */\n key: string;\n /**\n * Hierarchical path defining the collection in which this document resides.\n * Represented as an array of strings, allowing for nested categorization.\n * For example: [\"documents\", \"user123\"]\n */\n namespace: string[];\n /**\n * Timestamp of item creation.\n */\n createdAt: Date;\n /**\n * Timestamp of last update.\n */\n updatedAt: Date;\n}\n\n/**\n * Represents a search result item with relevance score.\n * Extends the base Item interface with an optional similarity score.\n */\nexport interface SearchItem extends Item {\n /**\n * Relevance/similarity score if from a ranked operation.\n * Higher scores indicate better matches.\n *\n * This is typically a cosine similarity score between -1 and 1,\n * where 1 indicates identical vectors and -1 indicates opposite vectors.\n */\n score?: number;\n}\n\n/**\n * Operation to retrieve an item by namespace and ID.\n */\nexport interface GetOperation {\n /**\n * Hierarchical path for the item.\n *\n * @example\n * // Get a user profile\n * namespace: [\"users\", \"profiles\"]\n */\n namespace: string[];\n\n /**\n * Unique identifier within the namespace.\n * Together with namespace forms the complete path to the item.\n *\n * @example\n * key: \"user123\" // For a user profile\n * key: \"doc456\" // For a document\n */\n key: string;\n}\n\n/**\n * Operation to search for items within a namespace prefix.\n */\nexport interface SearchOperation {\n /**\n * Hierarchical path prefix to search within.\n * Only items under this prefix will be searched.\n *\n * @example\n * // Search all user documents\n * namespacePrefix: [\"users\", \"documents\"]\n *\n * // Search everything\n * namespacePrefix: []\n */\n namespacePrefix: string[];\n\n /**\n * Key-value pairs to filter results based on exact matches or comparison operators.\n *\n * Supports both exact matches and operator-based comparisons:\n * - $eq: Equal to (same as direct value comparison)\n * - $ne: Not equal to\n * - $gt: Greater than\n * - $gte: Greater than or equal to\n * - $lt: Less than\n * - $lte: Less than or equal to\n *\n * @example\n * // Exact match\n * filter: { status: \"active\" }\n *\n * // With operators\n * filter: { score: { $gt: 4.99 } }\n *\n * // Multiple conditions\n * filter: {\n * score: { $gte: 3.0 },\n * color: \"red\"\n * }\n */\n filter?: Record<string, any>;\n\n /**\n * Maximum number of items to return.\n * @default 10\n */\n limit?: number;\n\n /**\n * Number of items to skip before returning results.\n * Useful for pagination.\n * @default 0\n */\n offset?: number;\n\n /**\n * Natural language search query for semantic search.\n * When provided, results will be ranked by relevance to this query\n * using vector similarity search.\n *\n * @example\n * // Find technical documentation about APIs\n * query: \"technical documentation about REST APIs\"\n *\n * // Find recent ML papers\n * query: \"machine learning papers from 2023\"\n */\n query?: string;\n}\n\n/**\n * Operation to store, update, or delete an item.\n */\nexport interface PutOperation {\n /**\n * Hierarchical path for the item.\n * Acts as a folder-like structure to organize items.\n * Each element represents one level in the hierarchy.\n *\n * @example\n * // Root level documents\n * namespace: [\"documents\"]\n *\n * // User-specific documents\n * namespace: [\"documents\", \"user123\"]\n *\n * // Nested cache structure\n * namespace: [\"cache\", \"docs\", \"v1\"]\n */\n namespace: string[];\n\n /**\n * Unique identifier for the document within its namespace.\n * Together with namespace forms the complete path to the item.\n *\n * Example: If namespace is [\"documents\", \"user123\"] and key is \"report1\",\n * the full path would effectively be \"documents/user123/report1\"\n */\n key: string;\n\n /**\n * Data to be stored, or null to delete the item.\n * Must be a JSON-serializable object with string keys.\n * Setting to null signals that the item should be deleted.\n *\n * @example\n * {\n * field1: \"string value\",\n * field2: 123,\n * nested: { can: \"contain\", any: \"serializable data\" }\n * }\n */\n value: Record<string, any> | null;\n\n /**\n * Controls how the item's fields are indexed for search operations.\n *\n * - undefined: Uses store's default indexing configuration\n * - false: Disables indexing for this item\n * - string[]: List of field paths to index\n *\n * Path syntax supports:\n * - Nested fields: \"metadata.title\"\n * - Array access: \"chapters[*].content\" (each indexed separately)\n * - Specific indices: \"authors[0].name\"\n *\n * @example\n * // Index specific fields\n * index: [\"metadata.title\", \"chapters[*].content\"]\n *\n * // Disable indexing\n * index: false\n */\n index?: false | string[];\n}\n\n/**\n * Operation to list and filter namespaces in the store.\n */\nexport interface ListNamespacesOperation {\n matchConditions?: MatchCondition[];\n maxDepth?: number;\n limit: number;\n offset: number;\n}\n\nexport type NameSpacePath = (string | \"*\")[];\n\nexport type NamespaceMatchType = \"prefix\" | \"suffix\";\n\nexport interface MatchCondition {\n matchType: NamespaceMatchType;\n path: NameSpacePath;\n}\n\nexport type Operation =\n | GetOperation\n | SearchOperation\n | PutOperation\n | ListNamespacesOperation;\n\nexport type OperationResults<Tuple extends readonly Operation[]> = {\n [K in keyof Tuple]: Tuple[K] extends PutOperation\n ? void\n : Tuple[K] extends SearchOperation\n ? SearchItem[]\n : Tuple[K] extends GetOperation\n ? Item | null\n : Tuple[K] extends ListNamespacesOperation\n ? string[][]\n : never;\n};\n\n/**\n * Configuration for indexing documents for semantic search in the store.\n *\n * This configures how documents are embedded and indexed for vector similarity search.\n */\nexport interface IndexConfig {\n /**\n * Number of dimensions in the embedding vectors.\n *\n * Common embedding model dimensions:\n * - OpenAI text-embedding-3-large: 256, 1024, or 3072\n * - OpenAI text-embedding-3-small: 512 or 1536\n * - OpenAI text-embedding-ada-002: 1536\n * - Cohere embed-english-v3.0: 1024\n * - Cohere embed-english-light-v3.0: 384\n * - Cohere embed-multilingual-v3.0: 1024\n * - Cohere embed-multilingual-light-v3.0: 384\n */\n dims: number;\n\n /**\n * The embeddings model to use for generating vectors.\n * This should be a LangChain Embeddings implementation.\n */\n embeddings: Embeddings;\n\n /**\n * Fields to extract text from for embedding generation.\n *\n * Path syntax supports:\n * - Simple field access: \"field\"\n * - Nested fields: \"metadata.title\"\n * - Array indexing:\n * - All elements: \"chapters[*].content\"\n * - Specific index: \"authors[0].name\"\n * - Last element: \"array[-1]\"\n *\n * @default [\"$\"] Embeds the entire document as one vector\n */\n fields?: string[];\n}\n\n/**\n * Utility function to get text at a specific JSON path\n */\nexport function getTextAtPath(obj: any, path: string): string[] {\n const parts = path.split(\".\");\n let current: any = obj;\n\n for (const part of parts) {\n if (part.includes(\"[\")) {\n const [arrayName, indexStr] = part.split(\"[\");\n const index = indexStr.replace(\"]\", \"\");\n\n if (!current[arrayName]) return [];\n\n if (index === \"*\") {\n const results: string[] = [];\n for (const item of current[arrayName]) {\n if (typeof item === \"string\") results.push(item);\n }\n return results;\n }\n\n const idx = parseInt(index, 10);\n if (Number.isNaN(idx)) return [];\n current = current[arrayName][idx];\n } else {\n current = current[part];\n }\n\n if (current === undefined) return [];\n }\n\n return typeof current === \"string\" ? [current] : [];\n}\n\n/**\n * Tokenizes a JSON path into parts\n */\nexport function tokenizePath(path: string): string[] {\n return path.split(\".\");\n}\n\n/**\n * Abstract base class for persistent key-value stores.\n *\n * Stores enable persistence and memory that can be shared across threads,\n * scoped to user IDs, assistant IDs, or other arbitrary namespaces.\n *\n * Features:\n * - Hierarchical namespaces for organization\n * - Key-value storage with metadata\n * - Vector similarity search (if configured)\n * - Filtering and pagination\n */\nexport abstract class BaseStore {\n /**\n * Execute multiple operations in a single batch.\n * This is more efficient than executing operations individually.\n *\n * @param operations Array of operations to execute\n * @returns Promise resolving to results matching the operations\n */\n abstract batch<Op extends Operation[]>(\n operations: Op\n ): Promise<OperationResults<Op>>;\n\n /**\n * Retrieve a single item by its namespace and key.\n *\n * @param namespace Hierarchical path for the item\n * @param key Unique identifier within the namespace\n * @returns Promise resolving to the item or null if not found\n */\n async get(namespace: string[], key: string): Promise<Item | null> {\n return (await this.batch<[GetOperation]>([{ namespace, key }]))[0];\n }\n\n /**\n * Search for items within a namespace prefix.\n * Supports both metadata filtering and vector similarity search.\n *\n * @param namespacePrefix Hierarchical path prefix to search within\n * @param options Search options for filtering and pagination\n * @returns Promise resolving to list of matching items with relevance scores\n *\n * @example\n * // Search with filters\n * await store.search([\"documents\"], {\n * filter: { type: \"report\", status: \"active\" },\n * limit: 5,\n * offset: 10\n * });\n *\n * // Vector similarity search\n * await store.search([\"users\", \"content\"], {\n * query: \"technical documentation about APIs\",\n * limit: 20\n * });\n */\n async search(\n namespacePrefix: string[],\n options: {\n filter?: Record<string, any>;\n limit?: number;\n offset?: number;\n query?: string;\n } = {}\n ): Promise<SearchItem[]> {\n const { filter, limit = 10, offset = 0, query } = options;\n return (\n await this.batch<[SearchOperation]>([\n {\n namespacePrefix,\n filter,\n limit,\n offset,\n query,\n },\n ])\n )[0];\n }\n\n /**\n * Store or update an item.\n *\n * @param namespace Hierarchical path for the item\n * @param key Unique identifier within the namespace\n * @param value Object containing the item's data\n * @param index Optional indexing configuration\n *\n * @example\n * // Simple storage\n * await store.put([\"docs\"], \"report\", { title: \"Annual Report\" });\n *\n * // With specific field indexing\n * await store.put(\n * [\"docs\"],\n * \"report\",\n * {\n * title: \"Q4 Report\",\n * chapters: [{ content: \"...\" }, { content: \"...\" }]\n * },\n * [\"title\", \"chapters[*].content\"]\n * );\n */\n async put(\n namespace: string[],\n key: string,\n value: Record<string, any>,\n index?: false | string[]\n ): Promise<void> {\n validateNamespace(namespace);\n await this.batch<[PutOperation]>([{ namespace, key, value, index }]);\n }\n\n /**\n * Delete an item from the store.\n *\n * @param namespace Hierarchical path for the item\n * @param key Unique identifier within the namespace\n */\n async delete(namespace: string[], key: string): Promise<void> {\n await this.batch<[PutOperation]>([{ namespace, key, value: null }]);\n }\n\n /**\n * List and filter namespaces in the store.\n * Used to explore data organization and navigate the namespace hierarchy.\n *\n * @param options Options for listing namespaces\n * @returns Promise resolving to list of namespace paths\n *\n * @example\n * // List all namespaces under \"documents\"\n * await store.listNamespaces({\n * prefix: [\"documents\"],\n * maxDepth: 2\n * });\n *\n * // List namespaces ending with \"v1\"\n * await store.listNamespaces({\n * suffix: [\"v1\"],\n * limit: 50\n * });\n */\n async listNamespaces(\n options: {\n prefix?: string[];\n suffix?: string[];\n maxDepth?: number;\n limit?: number;\n offset?: number;\n } = {}\n ): Promise<string[][]> {\n const { prefix, suffix, maxDepth, limit = 100, offset = 0 } = options;\n\n const matchConditions: MatchCondition[] = [];\n if (prefix) {\n matchConditions.push({ matchType: \"prefix\", path: prefix });\n }\n if (suffix) {\n matchConditions.push({ matchType: \"suffix\", path: suffix });\n }\n\n return (\n await this.batch<[ListNamespacesOperation]>([\n {\n matchConditions: matchConditions.length ? matchConditions : undefined,\n maxDepth,\n limit,\n offset,\n },\n ])\n )[0];\n }\n\n /**\n * Start the store. Override if initialization is needed.\n */\n start(): void | Promise<void> {}\n\n /**\n * Stop the store. Override if cleanup is needed.\n */\n stop(): void | Promise<void> {}\n}\n"],"mappings":";;;;AAMA,IAAa,wBAAb,cAA2C,MAAM;CAC/C,YAAY,SAAiB;AAC3B,QAAM,QAAQ;AACd,OAAK,OAAO;;;;;;;;AAShB,SAAS,kBAAkB,WAA2B;AACpD,KAAI,UAAU,WAAW,EACvB,OAAM,IAAI,sBAAsB,6BAA6B;AAE/D,MAAK,MAAM,SAAS,WAAW;AAC7B,MAAI,OAAO,UAAU,SACnB,OAAM,IAAI,sBACR,4BAA4B,MAAM,aAAa,UAAU,8CAC3B,OAAO,MAAM,GAC5C;AAEH,MAAI,MAAM,SAAS,IAAI,CACrB,OAAM,IAAI,sBACR,4BAA4B,MAAM,aAAa,UAAU,kDAC1D;AAEH,MAAI,UAAU,GACZ,OAAM,IAAI,sBACR,iDAAiD,MAAM,MAAM,YAC9D;;AAGL,KAAI,UAAU,OAAO,YACnB,OAAM,IAAI,sBACR,wDAAwD,YACzD;;;;;AAkSL,SAAgB,cAAc,KAAU,MAAwB;CAC9D,MAAM,QAAQ,KAAK,MAAM,IAAI;CAC7B,IAAI,UAAe;AAEnB,MAAK,MAAM,QAAQ,OAAO;AACxB,MAAI,KAAK,SAAS,IAAI,EAAE;GACtB,MAAM,CAAC,WAAW,YAAY,KAAK,MAAM,IAAI;GAC7C,MAAM,QAAQ,SAAS,QAAQ,KAAK,GAAG;AAEvC,OAAI,CAAC,QAAQ,WAAY,QAAO,EAAE;AAElC,OAAI,UAAU,KAAK;IACjB,MAA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gB,KAAK;GAAE,WAAW;GAAU,MAAM;GAAQ,CAAC;AAE7D,MAAI,OACF,iBAAgB,KAAK;GAAE,WAAW;GAAU,MAAM;GAAQ,CAAC;AAG7D,UACE,MAAM,KAAK,MAAiC,CAC1C;GACE,iBAAiB,gBAAgB,SAAS,kBAAkB,KAAA;GAC5D;GACA;GACA;GACD,CACF,CAAC,EACF;;;;;CAMJ,QAA8B;;;;CAK9B,OAA6B"}

@@ -1,3 +0,2 @@

const require_base = require('./base.cjs');
const require_base = require("./base.cjs");
//#region src/store/batch.ts

@@ -98,4 +97,3 @@ /**

batch.forEach(({ resolve }, key) => {
const index = Array.from(batch.keys()).indexOf(key);
resolve(results[index]);
resolve(results[Array.from(batch.keys()).indexOf(key)]);
});

@@ -118,5 +116,5 @@ } catch (e) {

};
//#endregion
exports.AsyncBatchedStore = AsyncBatchedStore;
//# sourceMappingURL=batch.cjs.map

@@ -1,1 +0,1 @@

{"version":3,"file":"batch.cjs","names":["BaseStore"],"sources":["../../src/store/batch.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport {\n BaseStore,\n type Item,\n type SearchOperation,\n type PutOperation,\n type GetOperation,\n type Operation,\n OperationResults,\n} from \"./base.js\";\n\n/**\n * Extracts and returns the underlying store from an `AsyncBatchedStore`,\n * or returns the input if it is not an `AsyncBatchedStore`.\n */\nconst extractStore = (input: BaseStore | AsyncBatchedStore): BaseStore => {\n if (\"lg_name\" in input && input.lg_name === \"AsyncBatchedStore\") {\n // @ts-expect-error is a protected property\n return input.store;\n }\n return input;\n};\n\nexport class AsyncBatchedStore extends BaseStore {\n lg_name = \"AsyncBatchedStore\";\n\n protected store: BaseStore;\n\n private queue: Map<\n number,\n {\n operation: Operation;\n resolve: (value: any) => void;\n reject: (reason?: any) => void;\n }\n > = new Map();\n\n private nextKey: number = 0;\n\n private running = false;\n\n private processingTask: Promise<void> | null = null;\n\n constructor(store: BaseStore) {\n super();\n this.store = extractStore(store);\n }\n\n get isRunning(): boolean {\n return this.running;\n }\n\n /**\n * @ignore\n * Batch is not implemented here as we're only extending `BaseStore`\n * to allow it to be passed where `BaseStore` is expected, and implement\n * the convenience methods (get, search, put, delete).\n */\n async batch<Op extends Operation[]>(\n _operations: Op\n ): Promise<OperationResults<Op>> {\n throw new Error(\n \"The `batch` method is not implemented on `AsyncBatchedStore`.\" +\n \"\\n Instead, it calls the `batch` method on the wrapped store.\" +\n \"\\n If you are seeing this error, something is wrong.\"\n );\n }\n\n async get(namespace: string[], key: string): Promise<Item | null> {\n return this.enqueueOperation({ namespace, key } as GetOperation);\n }\n\n async search(\n namespacePrefix: string[],\n options?: {\n filter?: Record<string, any>;\n limit?: number;\n offset?: number;\n query?: string;\n }\n ): Promise<Item[]> {\n const { filter, limit = 10, offset = 0, query } = options || {};\n return this.enqueueOperation({\n namespacePrefix,\n filter,\n limit,\n offset,\n query,\n } as SearchOperation);\n }\n\n async put(\n namespace: string[],\n key: string,\n value: Record<string, any>\n ): Promise<void> {\n return this.enqueueOperation({ namespace, key, value } as PutOperation);\n }\n\n async delete(namespace: string[], key: string): Promise<void> {\n return this.enqueueOperation({\n namespace,\n key,\n value: null,\n } as PutOperation);\n }\n\n start(): void {\n if (!this.running) {\n this.running = true;\n this.processingTask = this.processBatchQueue();\n }\n }\n\n async stop(): Promise<void> {\n this.running = false;\n if (this.processingTask) {\n await this.processingTask;\n }\n }\n\n private enqueueOperation<T>(operation: Operation): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const key = this.nextKey;\n this.nextKey += 1;\n this.queue.set(key, { operation, resolve, reject });\n });\n }\n\n private async processBatchQueue(): Promise<void> {\n while (this.running) {\n await new Promise((resolve) => {\n setTimeout(resolve, 0);\n });\n if (this.queue.size === 0) continue;\n\n const batch = new Map(this.queue);\n this.queue.clear();\n\n try {\n const operations = Array.from(batch.values()).map(\n ({ operation }) => operation\n );\n const results = await this.store.batch(operations);\n\n batch.forEach(({ resolve }, key) => {\n const index = Array.from(batch.keys()).indexOf(key);\n resolve(results[index]);\n });\n } catch (e) {\n batch.forEach(({ reject }) => {\n reject(e);\n });\n }\n }\n }\n\n // AsyncBatchedStore is internal and gets passed as args into traced tasks\n // some BaseStores contain circular references so just serialize without it\n // as this causes warnings when tracing with LangSmith.\n toJSON() {\n return {\n queue: this.queue,\n nextKey: this.nextKey,\n running: this.running,\n store: \"[LangGraphStore]\",\n };\n }\n}\n"],"mappings":";;;;;;;AAgBA,MAAM,gBAAgB,UAAoD;AACxE,KAAI,aAAa,SAAS,MAAM,YAAY,oBAE1C,QAAO,MAAM;AAEf,QAAO;;AAGT,IAAa,oBAAb,cAAuCA,uBAAU;CAC/C,UAAU;CAEV,AAAU;CAEV,AAAQ,wBAOJ,IAAI;CAER,AAAQ,UAAkB;CAE1B,AAAQ,UAAU;CAElB,AAAQ,iBAAuC;CAE/C,YAAY,OAAkB;AAC5B;AACA,OAAK,QAAQ,aAAa;;CAG5B,IAAI,YAAqB;AACvB,SAAO,KAAK;;;;;;;;CASd,MAAM,MACJ,aAC+B;AAC/B,QAAM,IAAI,MACR;;CAMJ,MAAM,IAAI,WAAqB,KAAmC;AAChE,SAAO,KAAK,iBAAiB;GAAE;GAAW;;;CAG5C,MAAM,OACJ,iBACA,SAMiB;EACjB,MAAM,EAAE,QAAQ,QAAQ,IAAI,SAAS,GAAG,UAAU,WAAW;AAC7D,SAAO,KAAK,iBAAiB;GAC3B;GACA;GACA;GACA;GACA;;;CAIJ,MAAM,IACJ,WACA,KACA,OACe;AACf,SAAO,KAAK,iBAAiB;GAAE;GAAW;GAAK;;;CAGjD,MAAM,OAAO,WAAqB,KAA4B;AAC5D,SAAO,KAAK,iBAAiB;GAC3B;GACA;GACA,OAAO;;;CAIX,QAAc;AACZ,MAAI,CAAC,KAAK,SAAS;AACjB,QAAK,UAAU;AACf,QAAK,iBAAiB,KAAK;;;CAI/B,MAAM,OAAsB;AAC1B,OAAK,UAAU;AACf,MAAI,KAAK,eACP,OAAM,KAAK;;CAIf,AAAQ,iBAAoB,WAAkC;AAC5D,SAAO,IAAI,SAAY,SAAS,WAAW;GACzC,MAAM,MAAM,KAAK;AACjB,QAAK,WAAW;AAChB,QAAK,MAAM,IAAI,KAAK;IAAE;IAAW;IAAS;;;;CAI9C,MAAc,oBAAmC;AAC/C,SAAO,KAAK,SAAS;AACnB,SAAM,IAAI,SAAS,YAAY;AAC7B,eAAW,SAAS;;AAEtB,OAAI,KAAK,MAAM,SAAS,EAAG;GAE3B,MAAM,QAAQ,IAAI,IAAI,KAAK;AAC3B,QAAK,MAAM;AAEX,OAAI;IACF,MAAM,aAAa,MAAM,KAAK,MAAM,UAAU,KAC3C,EAAE,gBAAgB;IAErB,MAAM,UAAU,MAAM,KAAK,MAAM,MAAM;AAEvC,UAAM,SAAS,EAAE,WAAW,QAAQ;KAClC,MAAM,QAAQ,MAAM,KAAK,MAAM,QAAQ,QAAQ;AAC/C,aAAQ,QAAQ;;YAEX,GAAG;AACV,UAAM,SAAS,EAAE,aAAa;AAC5B,YAAO;;;;;CASf,SAAS;AACP,SAAO;GACL,OAAO,KAAK;GACZ,SAAS,KAAK;GACd,SAAS,KAAK;GACd,OAAO"}
{"version":3,"file":"batch.cjs","names":["BaseStore"],"sources":["../../src/store/batch.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport {\n BaseStore,\n type Item,\n type SearchOperation,\n type PutOperation,\n type GetOperation,\n type Operation,\n OperationResults,\n} from \"./base.js\";\n\n/**\n * Extracts and returns the underlying store from an `AsyncBatchedStore`,\n * or returns the input if it is not an `AsyncBatchedStore`.\n */\nconst extractStore = (input: BaseStore | AsyncBatchedStore): BaseStore => {\n if (\"lg_name\" in input && input.lg_name === \"AsyncBatchedStore\") {\n // @ts-expect-error is a protected property\n return input.store;\n }\n return input;\n};\n\nexport class AsyncBatchedStore extends BaseStore {\n lg_name = \"AsyncBatchedStore\";\n\n protected store: BaseStore;\n\n private queue: Map<\n number,\n {\n operation: Operation;\n resolve: (value: any) => void;\n reject: (reason?: any) => void;\n }\n > = new Map();\n\n private nextKey: number = 0;\n\n private running = false;\n\n private processingTask: Promise<void> | null = null;\n\n constructor(store: BaseStore) {\n super();\n this.store = extractStore(store);\n }\n\n get isRunning(): boolean {\n return this.running;\n }\n\n /**\n * @ignore\n * Batch is not implemented here as we're only extending `BaseStore`\n * to allow it to be passed where `BaseStore` is expected, and implement\n * the convenience methods (get, search, put, delete).\n */\n async batch<Op extends Operation[]>(\n _operations: Op\n ): Promise<OperationResults<Op>> {\n throw new Error(\n \"The `batch` method is not implemented on `AsyncBatchedStore`.\" +\n \"\\n Instead, it calls the `batch` method on the wrapped store.\" +\n \"\\n If you are seeing this error, something is wrong.\"\n );\n }\n\n async get(namespace: string[], key: string): Promise<Item | null> {\n return this.enqueueOperation({ namespace, key } as GetOperation);\n }\n\n async search(\n namespacePrefix: string[],\n options?: {\n filter?: Record<string, any>;\n limit?: number;\n offset?: number;\n query?: string;\n }\n ): Promise<Item[]> {\n const { filter, limit = 10, offset = 0, query } = options || {};\n return this.enqueueOperation({\n namespacePrefix,\n filter,\n limit,\n offset,\n query,\n } as SearchOperation);\n }\n\n async put(\n namespace: string[],\n key: string,\n value: Record<string, any>\n ): Promise<void> {\n return this.enqueueOperation({ namespace, key, value } as PutOperation);\n }\n\n async delete(namespace: string[], key: string): Promise<void> {\n return this.enqueueOperation({\n namespace,\n key,\n value: null,\n } as PutOperation);\n }\n\n start(): void {\n if (!this.running) {\n this.running = true;\n this.processingTask = this.processBatchQueue();\n }\n }\n\n async stop(): Promise<void> {\n this.running = false;\n if (this.processingTask) {\n await this.processingTask;\n }\n }\n\n private enqueueOperation<T>(operation: Operation): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const key = this.nextKey;\n this.nextKey += 1;\n this.queue.set(key, { operation, resolve, reject });\n });\n }\n\n private async processBatchQueue(): Promise<void> {\n while (this.running) {\n await new Promise((resolve) => {\n setTimeout(resolve, 0);\n });\n if (this.queue.size === 0) continue;\n\n const batch = new Map(this.queue);\n this.queue.clear();\n\n try {\n const operations = Array.from(batch.values()).map(\n ({ operation }) => operation\n );\n const results = await this.store.batch(operations);\n\n batch.forEach(({ resolve }, key) => {\n const index = Array.from(batch.keys()).indexOf(key);\n resolve(results[index]);\n });\n } catch (e) {\n batch.forEach(({ reject }) => {\n reject(e);\n });\n }\n }\n }\n\n // AsyncBatchedStore is internal and gets passed as args into traced tasks\n // some BaseStores contain circular references so just serialize without it\n // as this causes warnings when tracing with LangSmith.\n toJSON() {\n return {\n queue: this.queue,\n nextKey: this.nextKey,\n running: this.running,\n store: \"[LangGraphStore]\",\n };\n }\n}\n"],"mappings":";;;;;;AAgBA,MAAM,gBAAgB,UAAoD;AACxE,KAAI,aAAa,SAAS,MAAM,YAAY,oBAE1C,QAAO,MAAM;AAEf,QAAO;;AAGT,IAAa,oBAAb,cAAuCA,aAAAA,UAAU;CAC/C,UAAU;CAEV;CAEA,wBAOI,IAAI,KAAK;CAEb,UAA0B;CAE1B,UAAkB;CAElB,iBAA+C;CAE/C,YAAY,OAAkB;AAC5B,SAAO;AACP,OAAK,QAAQ,aAAa,MAAM;;CAGlC,IAAI,YAAqB;AACvB,SAAO,KAAK;;;;;;;;CASd,MAAM,MACJ,aAC+B;AAC/B,QAAM,IAAI,MACR,iLAGD;;CAGH,MAAM,IAAI,WAAqB,KAAmC;AAChE,SAAO,KAAK,iBAAiB;GAAE;GAAW;GAAK,CAAiB;;CAGlE,MAAM,OACJ,iBACA,SAMiB;EACjB,MAAM,EAAE,QAAQ,QAAQ,IAAI,SAAS,GAAG,UAAU,WAAW,EAAE;AAC/D,SAAO,KAAK,iBAAiB;GAC3B;GACA;GACA;GACA;GACA;GACD,CAAoB;;CAGvB,MAAM,IACJ,WACA,KACA,OACe;AACf,SAAO,KAAK,iBAAiB;GAAE;GAAW;GAAK;GAAO,CAAiB;;CAGzE,MAAM,OAAO,WAAqB,KAA4B;AAC5D,SAAO,KAAK,iBAAiB;GAC3B;GACA;GACA,OAAO;GACR,CAAiB;;CAGpB,QAAc;AACZ,MAAI,CAAC,KAAK,SAAS;AACjB,QAAK,UAAU;AACf,QAAK,iBAAiB,KAAK,mBAAmB;;;CAIlD,MAAM,OAAsB;AAC1B,OAAK,UAAU;AACf,MAAI,KAAK,eACP,OAAM,KAAK;;CAIf,iBAA4B,WAAkC;AAC5D,SAAO,IAAI,SAAY,SAAS,WAAW;GACzC,MAAM,MAAM,KAAK;AACjB,QAAK,WAAW;AAChB,QAAK,MAAM,IAAI,KAAK;IAAE;IAAW;IAAS;IAAQ,CAAC;IACnD;;CAGJ,MAAc,oBAAmC;AAC/C,SAAO,KAAK,SAAS;AACnB,SAAM,IAAI,SAAS,YAAY;AAC7B,eAAW,SAAS,EAAE;KACtB;AACF,OAAI,KAAK,MAAM,SAAS,EAAG;GAE3B,MAAM,QAAQ,IAAI,IAAI,KAAK,MAAM;AACjC,QAAK,MAAM,OAAO;AAElB,OAAI;IACF,MAAM,aAAa,MAAM,KAAK,MAAM,QAAQ,CAAC,CAAC,KAC3C,EAAE,gBAAgB,UACpB;IACD,MAAM,UAAU,MAAM,KAAK,MAAM,MAAM,WAAW;AAElD,UAAM,SAAS,EAAE,WAAW,QAAQ;AAElC,aAAQ,QADM,MAAM,KAAK,MAAM,MAAM,CAAC,CAAC,QAAQ,IAAI,EAC5B;MACvB;YACK,GAAG;AACV,UAAM,SAAS,EAAE,aAAa;AAC5B,YAAO,EAAE;MACT;;;;CAQR,SAAS;AACP,SAAO;GACL,OAAO,KAAK;GACZ,SAAS,KAAK;GACd,SAAS,KAAK;GACd,OAAO;GACR"}

@@ -33,5 +33,2 @@ import { BaseStore, Item, Operation, OperationResults } from "./base.cjs";

private processBatchQueue;
// AsyncBatchedStore is internal and gets passed as args into traced tasks
// some BaseStores contain circular references so just serialize without it
// as this causes warnings when tracing with LangSmith.
toJSON(): {

@@ -38,0 +35,0 @@ queue: Map<number, {

@@ -1,1 +0,1 @@

{"version":3,"file":"batch.d.cts","names":["BaseStore","Item","Operation","OperationResults","AsyncBatchedStore","Op","Promise","Record","Map"],"sources":["../../src/store/batch.d.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { BaseStore, type Item, type Operation, OperationResults } from \"./base.js\";\nexport declare class AsyncBatchedStore extends BaseStore {\n lg_name: string;\n protected store: BaseStore;\n private queue;\n private nextKey;\n private running;\n private processingTask;\n constructor(store: BaseStore);\n get isRunning(): boolean;\n /**\n * @ignore\n * Batch is not implemented here as we're only extending `BaseStore`\n * to allow it to be passed where `BaseStore` is expected, and implement\n * the convenience methods (get, search, put, delete).\n */\n batch<Op extends Operation[]>(_operations: Op): Promise<OperationResults<Op>>;\n get(namespace: string[], key: string): Promise<Item | null>;\n search(namespacePrefix: string[], options?: {\n filter?: Record<string, any>;\n limit?: number;\n offset?: number;\n query?: string;\n }): Promise<Item[]>;\n put(namespace: string[], key: string, value: Record<string, any>): Promise<void>;\n delete(namespace: string[], key: string): Promise<void>;\n start(): void;\n stop(): Promise<void>;\n private enqueueOperation;\n private processBatchQueue;\n // AsyncBatchedStore is internal and gets passed as args into traced tasks\n // some BaseStores contain circular references so just serialize without it\n // as this causes warnings when tracing with LangSmith.\n toJSON(): {\n queue: Map<number, {\n operation: Operation;\n resolve: (value: any) => void;\n reject: (reason?: any) => void;\n }>;\n nextKey: number;\n running: boolean;\n store: string;\n };\n}\n"],"mappings":";;;cAEqBI,iBAAAA,SAA0BJ,SAAAA;EAA1BI,OAAAA,EAAAA,MAAAA;EAAiB,UAAA,KAAA,EAEjBJ,SAFiB;UAEjBA,KAAAA;UAKEA,OAAAA;UAQFE,OAAAA;UAA0BG,cAAAA;aAA8BA,CAAAA,KAAAA,EARtDL,SAQsDK;MAAjBF,SAAAA,CAAAA,CAAAA,EAAAA,OAAAA;;;;;;;OAQXI,CAAAA,WAR5BL,SAQ4BK,EAAAA,CAAAA,CAAAA,WAAAA,EARFF,EAQEE,CAAAA,EARGD,OAQHC,CARWJ,gBAQXI,CAR4BF,EAQ5BE,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A+Bd,MAAA,CAAA"}

@@ -33,5 +33,2 @@ import { BaseStore, Item, Operation, OperationResults } from "./base.js";

private processBatchQueue;
// AsyncBatchedStore is internal and gets passed as args into traced tasks
// some BaseStores contain circular references so just serialize without it
// as this causes warnings when tracing with LangSmith.
toJSON(): {

@@ -38,0 +35,0 @@ queue: Map<number, {

@@ -1,1 +0,1 @@

{"version":3,"file":"batch.d.ts","names":["BaseStore","Item","Operation","OperationResults","AsyncBatchedStore","Op","Promise","Record","Map"],"sources":["../../src/store/batch.d.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { BaseStore, type Item, type Operation, OperationResults } from \"./base.js\";\nexport declare class AsyncBatchedStore extends BaseStore {\n lg_name: string;\n protected store: BaseStore;\n private queue;\n private nextKey;\n private running;\n private processingTask;\n constructor(store: BaseStore);\n get isRunning(): boolean;\n /**\n * @ignore\n * Batch is not implemented here as we're only extending `BaseStore`\n * to allow it to be passed where `BaseStore` is expected, and implement\n * the convenience methods (get, search, put, delete).\n */\n batch<Op extends Operation[]>(_operations: Op): Promise<OperationResults<Op>>;\n get(namespace: string[], key: string): Promise<Item | null>;\n search(namespacePrefix: string[], options?: {\n filter?: Record<string, any>;\n limit?: number;\n offset?: number;\n query?: string;\n }): Promise<Item[]>;\n put(namespace: string[], key: string, value: Record<string, any>): Promise<void>;\n delete(namespace: string[], key: string): Promise<void>;\n start(): void;\n stop(): Promise<void>;\n private enqueueOperation;\n private processBatchQueue;\n // AsyncBatchedStore is internal and gets passed as args into traced tasks\n // some BaseStores contain circular references so just serialize without it\n // as this causes warnings when tracing with LangSmith.\n toJSON(): {\n queue: Map<number, {\n operation: Operation;\n resolve: (value: any) => void;\n reject: (reason?: any) => void;\n }>;\n nextKey: number;\n running: boolean;\n store: string;\n };\n}\n"],"mappings":";;;cAEqBI,iBAAAA,SAA0BJ,SAAAA;EAA1BI,OAAAA,EAAAA,MAAAA;EAAiB,UAAA,KAAA,EAEjBJ,SAFiB;UAEjBA,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IACT,KAAA;IACA,MAAA;IACA,KAAA;EAAA,IAED,OAAA,CAAQ,IAAA;EAWL,GAAA,CACJ,SAAA,YACA,GAAA,UACA,KAAA,EAAO,MAAA,gBACN,OAAA;EAIG,MAAA,CAAO,SAAA,YAAqB,GAAA,WAAc,OAAA;EAQhD,KAAA,CAAA;EAOM,IAAA,CAAA,GAAQ,OAAA;EAAA,QAON,gBAAA;EAAA,QAQM,iBAAA;EA+Bd,MAAA,CAAA"}
import { BaseStore } from "./base.js";
//#region src/store/batch.ts

@@ -98,4 +97,3 @@ /**

batch.forEach(({ resolve }, key) => {
const index = Array.from(batch.keys()).indexOf(key);
resolve(results[index]);
resolve(results[Array.from(batch.keys()).indexOf(key)]);
});

@@ -118,5 +116,5 @@ } catch (e) {

};
//#endregion
export { AsyncBatchedStore };
//# sourceMappingURL=batch.js.map

@@ -1,1 +0,1 @@

{"version":3,"file":"batch.js","names":[],"sources":["../../src/store/batch.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport {\n BaseStore,\n type Item,\n type SearchOperation,\n type PutOperation,\n type GetOperation,\n type Operation,\n OperationResults,\n} from \"./base.js\";\n\n/**\n * Extracts and returns the underlying store from an `AsyncBatchedStore`,\n * or returns the input if it is not an `AsyncBatchedStore`.\n */\nconst extractStore = (input: BaseStore | AsyncBatchedStore): BaseStore => {\n if (\"lg_name\" in input && input.lg_name === \"AsyncBatchedStore\") {\n // @ts-expect-error is a protected property\n return input.store;\n }\n return input;\n};\n\nexport class AsyncBatchedStore extends BaseStore {\n lg_name = \"AsyncBatchedStore\";\n\n protected store: BaseStore;\n\n private queue: Map<\n number,\n {\n operation: Operation;\n resolve: (value: any) => void;\n reject: (reason?: any) => void;\n }\n > = new Map();\n\n private nextKey: number = 0;\n\n private running = false;\n\n private processingTask: Promise<void> | null = null;\n\n constructor(store: BaseStore) {\n super();\n this.store = extractStore(store);\n }\n\n get isRunning(): boolean {\n return this.running;\n }\n\n /**\n * @ignore\n * Batch is not implemented here as we're only extending `BaseStore`\n * to allow it to be passed where `BaseStore` is expected, and implement\n * the convenience methods (get, search, put, delete).\n */\n async batch<Op extends Operation[]>(\n _operations: Op\n ): Promise<OperationResults<Op>> {\n throw new Error(\n \"The `batch` method is not implemented on `AsyncBatchedStore`.\" +\n \"\\n Instead, it calls the `batch` method on the wrapped store.\" +\n \"\\n If you are seeing this error, something is wrong.\"\n );\n }\n\n async get(namespace: string[], key: string): Promise<Item | null> {\n return this.enqueueOperation({ namespace, key } as GetOperation);\n }\n\n async search(\n namespacePrefix: string[],\n options?: {\n filter?: Record<string, any>;\n limit?: number;\n offset?: number;\n query?: string;\n }\n ): Promise<Item[]> {\n const { filter, limit = 10, offset = 0, query } = options || {};\n return this.enqueueOperation({\n namespacePrefix,\n filter,\n limit,\n offset,\n query,\n } as SearchOperation);\n }\n\n async put(\n namespace: string[],\n key: string,\n value: Record<string, any>\n ): Promise<void> {\n return this.enqueueOperation({ namespace, key, value } as PutOperation);\n }\n\n async delete(namespace: string[], key: string): Promise<void> {\n return this.enqueueOperation({\n namespace,\n key,\n value: null,\n } as PutOperation);\n }\n\n start(): void {\n if (!this.running) {\n this.running = true;\n this.processingTask = this.processBatchQueue();\n }\n }\n\n async stop(): Promise<void> {\n this.running = false;\n if (this.processingTask) {\n await this.processingTask;\n }\n }\n\n private enqueueOperation<T>(operation: Operation): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const key = this.nextKey;\n this.nextKey += 1;\n this.queue.set(key, { operation, resolve, reject });\n });\n }\n\n private async processBatchQueue(): Promise<void> {\n while (this.running) {\n await new Promise((resolve) => {\n setTimeout(resolve, 0);\n });\n if (this.queue.size === 0) continue;\n\n const batch = new Map(this.queue);\n this.queue.clear();\n\n try {\n const operations = Array.from(batch.values()).map(\n ({ operation }) => operation\n );\n const results = await this.store.batch(operations);\n\n batch.forEach(({ resolve }, key) => {\n const index = Array.from(batch.keys()).indexOf(key);\n resolve(results[index]);\n });\n } catch (e) {\n batch.forEach(({ reject }) => {\n reject(e);\n });\n }\n }\n }\n\n // AsyncBatchedStore is internal and gets passed as args into traced tasks\n // some BaseStores contain circular references so just serialize without it\n // as this causes warnings when tracing with LangSmith.\n toJSON() {\n return {\n queue: this.queue,\n nextKey: this.nextKey,\n running: this.running,\n store: \"[LangGraphStore]\",\n };\n }\n}\n"],"mappings":";;;;;;;AAgBA,MAAM,gBAAgB,UAAoD;AACxE,KAAI,aAAa,SAAS,MAAM,YAAY,oBAE1C,QAAO,MAAM;AAEf,QAAO;;AAGT,IAAa,oBAAb,cAAuC,UAAU;CAC/C,UAAU;CAEV,AAAU;CAEV,AAAQ,wBAOJ,IAAI;CAER,AAAQ,UAAkB;CAE1B,AAAQ,UAAU;CAElB,AAAQ,iBAAuC;CAE/C,YAAY,OAAkB;AAC5B;AACA,OAAK,QAAQ,aAAa;;CAG5B,IAAI,YAAqB;AACvB,SAAO,KAAK;;;;;;;;CASd,MAAM,MACJ,aAC+B;AAC/B,QAAM,IAAI,MACR;;CAMJ,MAAM,IAAI,WAAqB,KAAmC;AAChE,SAAO,KAAK,iBAAiB;GAAE;GAAW;;;CAG5C,MAAM,OACJ,iBACA,SAMiB;EACjB,MAAM,EAAE,QAAQ,QAAQ,IAAI,SAAS,GAAG,UAAU,WAAW;AAC7D,SAAO,KAAK,iBAAiB;GAC3B;GACA;GACA;GACA;GACA;;;CAIJ,MAAM,IACJ,WACA,KACA,OACe;AACf,SAAO,KAAK,iBAAiB;GAAE;GAAW;GAAK;;;CAGjD,MAAM,OAAO,WAAqB,KAA4B;AAC5D,SAAO,KAAK,iBAAiB;GAC3B;GACA;GACA,OAAO;;;CAIX,QAAc;AACZ,MAAI,CAAC,KAAK,SAAS;AACjB,QAAK,UAAU;AACf,QAAK,iBAAiB,KAAK;;;CAI/B,MAAM,OAAsB;AAC1B,OAAK,UAAU;AACf,MAAI,KAAK,eACP,OAAM,KAAK;;CAIf,AAAQ,iBAAoB,WAAkC;AAC5D,SAAO,IAAI,SAAY,SAAS,WAAW;GACzC,MAAM,MAAM,KAAK;AACjB,QAAK,WAAW;AAChB,QAAK,MAAM,IAAI,KAAK;IAAE;IAAW;IAAS;;;;CAI9C,MAAc,oBAAmC;AAC/C,SAAO,KAAK,SAAS;AACnB,SAAM,IAAI,SAAS,YAAY;AAC7B,eAAW,SAAS;;AAEtB,OAAI,KAAK,MAAM,SAAS,EAAG;GAE3B,MAAM,QAAQ,IAAI,IAAI,KAAK;AAC3B,QAAK,MAAM;AAEX,OAAI;IACF,MAAM,aAAa,MAAM,KAAK,MAAM,UAAU,KAC3C,EAAE,gBAAgB;IAErB,MAAM,UAAU,MAAM,KAAK,MAAM,MAAM;AAEvC,UAAM,SAAS,EAAE,WAAW,QAAQ;KAClC,MAAM,QAAQ,MAAM,KAAK,MAAM,QAAQ,QAAQ;AAC/C,aAAQ,QAAQ;;YAEX,GAAG;AACV,UAAM,SAAS,EAAE,aAAa;AAC5B,YAAO;;;;;CASf,SAAS;AACP,SAAO;GACL,OAAO,KAAK;GACZ,SAAS,KAAK;GACd,SAAS,KAAK;GACd,OAAO"}
{"version":3,"file":"batch.js","names":[],"sources":["../../src/store/batch.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport {\n BaseStore,\n type Item,\n type SearchOperation,\n type PutOperation,\n type GetOperation,\n type Operation,\n OperationResults,\n} from \"./base.js\";\n\n/**\n * Extracts and returns the underlying store from an `AsyncBatchedStore`,\n * or returns the input if it is not an `AsyncBatchedStore`.\n */\nconst extractStore = (input: BaseStore | AsyncBatchedStore): BaseStore => {\n if (\"lg_name\" in input && input.lg_name === \"AsyncBatchedStore\") {\n // @ts-expect-error is a protected property\n return input.store;\n }\n return input;\n};\n\nexport class AsyncBatchedStore extends BaseStore {\n lg_name = \"AsyncBatchedStore\";\n\n protected store: BaseStore;\n\n private queue: Map<\n number,\n {\n operation: Operation;\n resolve: (value: any) => void;\n reject: (reason?: any) => void;\n }\n > = new Map();\n\n private nextKey: number = 0;\n\n private running = false;\n\n private processingTask: Promise<void> | null = null;\n\n constructor(store: BaseStore) {\n super();\n this.store = extractStore(store);\n }\n\n get isRunning(): boolean {\n return this.running;\n }\n\n /**\n * @ignore\n * Batch is not implemented here as we're only extending `BaseStore`\n * to allow it to be passed where `BaseStore` is expected, and implement\n * the convenience methods (get, search, put, delete).\n */\n async batch<Op extends Operation[]>(\n _operations: Op\n ): Promise<OperationResults<Op>> {\n throw new Error(\n \"The `batch` method is not implemented on `AsyncBatchedStore`.\" +\n \"\\n Instead, it calls the `batch` method on the wrapped store.\" +\n \"\\n If you are seeing this error, something is wrong.\"\n );\n }\n\n async get(namespace: string[], key: string): Promise<Item | null> {\n return this.enqueueOperation({ namespace, key } as GetOperation);\n }\n\n async search(\n namespacePrefix: string[],\n options?: {\n filter?: Record<string, any>;\n limit?: number;\n offset?: number;\n query?: string;\n }\n ): Promise<Item[]> {\n const { filter, limit = 10, offset = 0, query } = options || {};\n return this.enqueueOperation({\n namespacePrefix,\n filter,\n limit,\n offset,\n query,\n } as SearchOperation);\n }\n\n async put(\n namespace: string[],\n key: string,\n value: Record<string, any>\n ): Promise<void> {\n return this.enqueueOperation({ namespace, key, value } as PutOperation);\n }\n\n async delete(namespace: string[], key: string): Promise<void> {\n return this.enqueueOperation({\n namespace,\n key,\n value: null,\n } as PutOperation);\n }\n\n start(): void {\n if (!this.running) {\n this.running = true;\n this.processingTask = this.processBatchQueue();\n }\n }\n\n async stop(): Promise<void> {\n this.running = false;\n if (this.processingTask) {\n await this.processingTask;\n }\n }\n\n private enqueueOperation<T>(operation: Operation): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const key = this.nextKey;\n this.nextKey += 1;\n this.queue.set(key, { operation, resolve, reject });\n });\n }\n\n private async processBatchQueue(): Promise<void> {\n while (this.running) {\n await new Promise((resolve) => {\n setTimeout(resolve, 0);\n });\n if (this.queue.size === 0) continue;\n\n const batch = new Map(this.queue);\n this.queue.clear();\n\n try {\n const operations = Array.from(batch.values()).map(\n ({ operation }) => operation\n );\n const results = await this.store.batch(operations);\n\n batch.forEach(({ resolve }, key) => {\n const index = Array.from(batch.keys()).indexOf(key);\n resolve(results[index]);\n });\n } catch (e) {\n batch.forEach(({ reject }) => {\n reject(e);\n });\n }\n }\n }\n\n // AsyncBatchedStore is internal and gets passed as args into traced tasks\n // some BaseStores contain circular references so just serialize without it\n // as this causes warnings when tracing with LangSmith.\n toJSON() {\n return {\n queue: this.queue,\n nextKey: this.nextKey,\n running: this.running,\n store: \"[LangGraphStore]\",\n };\n }\n}\n"],"mappings":";;;;;;AAgBA,MAAM,gBAAgB,UAAoD;AACxE,KAAI,aAAa,SAAS,MAAM,YAAY,oBAE1C,QAAO,MAAM;AAEf,QAAO;;AAGT,IAAa,oBAAb,cAAuC,UAAU;CAC/C,UAAU;CAEV;CAEA,wBAOI,IAAI,KAAK;CAEb,UAA0B;CAE1B,UAAkB;CAElB,iBAA+C;CAE/C,YAAY,OAAkB;AAC5B,SAAO;AACP,OAAK,QAAQ,aAAa,MAAM;;CAGlC,IAAI,YAAqB;AACvB,SAAO,KAAK;;;;;;;;CASd,MAAM,MACJ,aAC+B;AAC/B,QAAM,IAAI,MACR,iLAGD;;CAGH,MAAM,IAAI,WAAqB,KAAmC;AAChE,SAAO,KAAK,iBAAiB;GAAE;GAAW;GAAK,CAAiB;;CAGlE,MAAM,OACJ,iBACA,SAMiB;EACjB,MAAM,EAAE,QAAQ,QAAQ,IAAI,SAAS,GAAG,UAAU,WAAW,EAAE;AAC/D,SAAO,KAAK,iBAAiB;GAC3B;GACA;GACA;GACA;GACA;GACD,CAAoB;;CAGvB,MAAM,IACJ,WACA,KACA,OACe;AACf,SAAO,KAAK,iBAAiB;GAAE;GAAW;GAAK;GAAO,CAAiB;;CAGzE,MAAM,OAAO,WAAqB,KAA4B;AAC5D,SAAO,KAAK,iBAAiB;GAC3B;GACA;GACA,OAAO;GACR,CAAiB;;CAGpB,QAAc;AACZ,MAAI,CAAC,KAAK,SAAS;AACjB,QAAK,UAAU;AACf,QAAK,iBAAiB,KAAK,mBAAmB;;;CAIlD,MAAM,OAAsB;AAC1B,OAAK,UAAU;AACf,MAAI,KAAK,eACP,OAAM,KAAK;;CAIf,iBAA4B,WAAkC;AAC5D,SAAO,IAAI,SAAY,SAAS,WAAW;GACzC,MAAM,MAAM,KAAK;AACjB,QAAK,WAAW;AAChB,QAAK,MAAM,IAAI,KAAK;IAAE;IAAW;IAAS;IAAQ,CAAC;IACnD;;CAGJ,MAAc,oBAAmC;AAC/C,SAAO,KAAK,SAAS;AACnB,SAAM,IAAI,SAAS,YAAY;AAC7B,eAAW,SAAS,EAAE;KACtB;AACF,OAAI,KAAK,MAAM,SAAS,EAAG;GAE3B,MAAM,QAAQ,IAAI,IAAI,KAAK,MAAM;AACjC,QAAK,MAAM,OAAO;AAElB,OAAI;IACF,MAAM,aAAa,MAAM,KAAK,MAAM,QAAQ,CAAC,CAAC,KAC3C,EAAE,gBAAgB,UACpB;IACD,MAAM,UAAU,MAAM,KAAK,MAAM,MAAM,WAAW;AAElD,UAAM,SAAS,EAAE,WAAW,QAAQ;AAElC,aAAQ,QADM,MAAM,KAAK,MAAM,MAAM,CAAC,CAAC,QAAQ,IAAI,EAC5B;MACvB;YACK,GAAG;AACV,UAAM,SAAS,EAAE,aAAa;AAC5B,YAAO,EAAE;MACT;;;;CAQR,SAAS;AACP,SAAO;GACL,OAAO,KAAK;GACZ,SAAS,KAAK;GACd,SAAS,KAAK;GACd,OAAO;GACR"}

@@ -1,4 +0,3 @@

const require_base = require('./base.cjs');
const require_utils = require('./utils.cjs');
const require_base = require("./base.cjs");
const require_utils = require("./utils.cjs");
//#region src/store/memory.ts

@@ -73,4 +72,3 @@ /**

const queryVector = queryVectors[op.query];
const scoredResults = this.scoreResults(candidates, queryVector, op.offset ?? 0, op.limit ?? 10);
results[i] = scoredResults;
results[i] = this.scoreResults(candidates, queryVector, op.offset ?? 0, op.limit ?? 10);
} else results[i] = this.paginateResults(candidates.map((item) => ({

@@ -96,4 +94,3 @@ ...item,

const namespaceKey = op.namespace.join(":");
const item = this.data.get(namespaceKey)?.get(op.key);
return item ?? null;
return this.data.get(namespaceKey)?.get(op.key) ?? null;
}

@@ -121,4 +118,3 @@ putOperation(op) {

listNamespacesOperation(op) {
const allNamespaces = Array.from(this.data.keys()).map((ns) => ns.split(":"));
let namespaces = allNamespaces;
let namespaces = Array.from(this.data.keys()).map((ns) => ns.split(":"));
if (op.matchConditions && op.matchConditions.length > 0) namespaces = namespaces.filter((ns) => op.matchConditions.every((condition) => this.doesMatch(condition, ns)));

@@ -165,4 +161,3 @@ if (op.maxDepth !== void 0) namespaces = Array.from(new Set(namespaces.map((ns) => ns.slice(0, op.maxDepth).join(":")))).map((ns) => ns.split(":"));

}
const scores = this.cosineSimilarity(queryVector, flatVectors);
const sortedResults = scores.map((score, i) => [score, flatItems[i]]).sort((a, b) => b[0] - a[0]);
const sortedResults = this.cosineSimilarity(queryVector, flatVectors).map((score, i) => [score, flatItems[i]]).sort((a, b) => b[0] - a[0]);
const seen = /* @__PURE__ */ new Set();

@@ -233,4 +228,3 @@ const kept = [];

if (!namespaceMap.has(key)) namespaceMap.set(key, /* @__PURE__ */ new Map());
const itemMap = namespaceMap.get(key);
itemMap.set(field, embedding);
namespaceMap.get(key).set(field, embedding);
}

@@ -266,6 +260,6 @@ }

var MemoryStore = class extends InMemoryStore {};
//#endregion
exports.InMemoryStore = InMemoryStore;
exports.MemoryStore = MemoryStore;
//# sourceMappingURL=memory.cjs.map

@@ -1,1 +0,1 @@

{"version":3,"file":"memory.cjs","names":["BaseStore","tokenizePath","candidates: Item[]","compareValues","flatItems: Item[]","flatVectors: number[][]","scoreless: Item[]","kept: Array<[number | undefined, Item]>","toEmbed: { [text: string]: [string[], string, string][] }","getTextAtPath"],"sources":["../../src/store/memory.ts"],"sourcesContent":["import {\n BaseStore,\n type OperationResults,\n type Item,\n type Operation,\n MatchCondition,\n ListNamespacesOperation,\n PutOperation,\n SearchOperation,\n GetOperation,\n type IndexConfig,\n type SearchItem,\n} from \"./base.js\";\nimport { tokenizePath, compareValues, getTextAtPath } from \"./utils.js\";\n\n/**\n * In-memory key-value store with optional vector search.\n *\n * A lightweight store implementation using JavaScript Maps. Supports basic\n * key-value operations and vector search when configured with embeddings.\n *\n * @example\n * ```typescript\n * // Basic key-value storage\n * const store = new InMemoryStore();\n * await store.put([\"users\", \"123\"], \"prefs\", { theme: \"dark\" });\n * const item = await store.get([\"users\", \"123\"], \"prefs\");\n *\n * // Vector search with embeddings\n * import { OpenAIEmbeddings } from \"@langchain/openai\";\n * const store = new InMemoryStore({\n * index: {\n * dims: 1536,\n * embeddings: new OpenAIEmbeddings({ modelName: \"text-embedding-3-small\" }),\n * }\n * });\n *\n * // Store documents\n * await store.put([\"docs\"], \"doc1\", { text: \"Python tutorial\" });\n * await store.put([\"docs\"], \"doc2\", { text: \"TypeScript guide\" });\n *\n * // Search by similarity\n * const results = await store.search([\"docs\"], { query: \"python programming\" });\n * ```\n *\n * **Warning**: This store keeps all data in memory. Data is lost when the process exits.\n * For persistence, use a database-backed store.\n */\nexport class InMemoryStore extends BaseStore {\n private data: Map<string, Map<string, Item>> = new Map();\n\n // Namespace -> Key -> Path/field -> Vector\n private vectors: Map<string, Map<string, Map<string, number[]>>> = new Map();\n\n private _indexConfig?: IndexConfig & {\n __tokenizedFields: Array<[string, string[]]>;\n };\n\n constructor(options?: { index?: IndexConfig }) {\n super();\n if (options?.index) {\n this._indexConfig = {\n ...options.index,\n __tokenizedFields: (options.index.fields ?? [\"$\"]).map((p) => [\n p,\n p === \"$\" ? [p] : tokenizePath(p),\n ]),\n };\n }\n }\n\n async batch<Op extends readonly Operation[]>(\n operations: Op\n ): Promise<OperationResults<Op>> {\n const results = [];\n const putOps = new Map<string, PutOperation>();\n const searchOps = new Map<number, [SearchOperation, Item[]]>();\n\n // First pass - handle gets and prepare search/put operations\n for (let i = 0; i < operations.length; i += 1) {\n const op = operations[i];\n if (\"key\" in op && \"namespace\" in op && !(\"value\" in op)) {\n // GetOperation\n results.push(this.getOperation(op));\n } else if (\"namespacePrefix\" in op) {\n // SearchOperation\n const candidates = this.filterItems(op);\n searchOps.set(i, [op, candidates]);\n results.push(null);\n } else if (\"value\" in op) {\n // PutOperation\n const key = `${op.namespace.join(\":\")}:${op.key}`;\n putOps.set(key, op);\n results.push(null);\n } else if (\"matchConditions\" in op) {\n // ListNamespacesOperation\n results.push(this.listNamespacesOperation(op));\n }\n }\n\n // Handle search operations with embeddings\n if (searchOps.size > 0) {\n if (this._indexConfig?.embeddings) {\n const queries = new Set<string>();\n for (const [op] of searchOps.values()) {\n if (op.query) queries.add(op.query);\n }\n\n // Get embeddings for all queries\n const queryEmbeddings =\n queries.size > 0\n ? await Promise.all(\n Array.from(queries).map((q) =>\n this._indexConfig!.embeddings.embedQuery(q)\n )\n )\n : [];\n const queryVectors = Object.fromEntries(\n Array.from(queries).map((q, i) => [q, queryEmbeddings[i]])\n );\n\n // Process each search operation\n for (const [i, [op, candidates]] of searchOps.entries()) {\n if (op.query && queryVectors[op.query]) {\n const queryVector = queryVectors[op.query];\n const scoredResults = this.scoreResults(\n candidates,\n queryVector,\n op.offset ?? 0,\n op.limit ?? 10\n );\n results[i] = scoredResults;\n } else {\n results[i] = this.paginateResults(\n candidates.map((item) => ({ ...item, score: undefined })),\n op.offset ?? 0,\n op.limit ?? 10\n );\n }\n }\n } else {\n // No embeddings - just paginate the filtered results\n for (const [i, [op, candidates]] of searchOps.entries()) {\n results[i] = this.paginateResults(\n candidates.map((item) => ({ ...item, score: undefined })),\n op.offset ?? 0,\n op.limit ?? 10\n );\n }\n }\n }\n\n // Handle put operations with embeddings\n if (putOps.size > 0 && this._indexConfig?.embeddings) {\n const toEmbed = this.extractTexts(Array.from(putOps.values()));\n if (Object.keys(toEmbed).length > 0) {\n const embeddings = await this._indexConfig.embeddings.embedDocuments(\n Object.keys(toEmbed)\n );\n this.insertVectors(toEmbed, embeddings);\n }\n }\n\n // Apply all put operations\n for (const op of putOps.values()) {\n this.putOperation(op);\n }\n\n return results as OperationResults<Op>;\n }\n\n private getOperation(op: GetOperation): Item | null {\n const namespaceKey = op.namespace.join(\":\");\n const item = this.data.get(namespaceKey)?.get(op.key);\n return item ?? null;\n }\n\n private putOperation(op: PutOperation): void {\n const namespaceKey = op.namespace.join(\":\");\n if (!this.data.has(namespaceKey)) {\n this.data.set(namespaceKey, new Map());\n }\n const namespaceMap = this.data.get(namespaceKey)!;\n\n if (op.value === null) {\n namespaceMap.delete(op.key);\n } else {\n const now = new Date();\n if (namespaceMap.has(op.key)) {\n const item = namespaceMap.get(op.key)!;\n item.value = op.value;\n item.updatedAt = now;\n } else {\n namespaceMap.set(op.key, {\n value: op.value,\n key: op.key,\n namespace: op.namespace,\n createdAt: now,\n updatedAt: now,\n });\n }\n }\n }\n\n private listNamespacesOperation(op: ListNamespacesOperation): string[][] {\n const allNamespaces = Array.from(this.data.keys()).map((ns) =>\n ns.split(\":\")\n );\n let namespaces = allNamespaces;\n\n if (op.matchConditions && op.matchConditions.length > 0) {\n namespaces = namespaces.filter((ns) =>\n op.matchConditions!.every((condition) => this.doesMatch(condition, ns))\n );\n }\n\n if (op.maxDepth !== undefined) {\n namespaces = Array.from(\n new Set(namespaces.map((ns) => ns.slice(0, op.maxDepth).join(\":\")))\n ).map((ns) => ns.split(\":\"));\n }\n\n namespaces.sort((a, b) => a.join(\":\").localeCompare(b.join(\":\")));\n\n return namespaces.slice(\n op.offset ?? 0,\n (op.offset ?? 0) + (op.limit ?? namespaces.length)\n );\n }\n\n private doesMatch(matchCondition: MatchCondition, key: string[]): boolean {\n const { matchType, path } = matchCondition;\n\n if (matchType === \"prefix\") {\n if (path.length > key.length) return false;\n return path.every((pElem, index) => {\n const kElem = key[index];\n return pElem === \"*\" || kElem === pElem;\n });\n } else if (matchType === \"suffix\") {\n if (path.length > key.length) return false;\n return path.every((pElem, index) => {\n const kElem = key[key.length - path.length + index];\n return pElem === \"*\" || kElem === pElem;\n });\n }\n\n throw new Error(`Unsupported match type: ${matchType}`);\n }\n\n private filterItems(op: SearchOperation): Item[] {\n const candidates: Item[] = [];\n for (const [namespace, items] of this.data.entries()) {\n if (namespace.startsWith(op.namespacePrefix.join(\":\"))) {\n candidates.push(...items.values());\n }\n }\n\n let filteredCandidates = candidates;\n if (op.filter) {\n filteredCandidates = candidates.filter((item) =>\n Object.entries(op.filter!).every(([key, value]) =>\n compareValues(item.value[key], value)\n )\n );\n }\n return filteredCandidates;\n }\n\n private scoreResults(\n candidates: Item[],\n queryVector: number[],\n offset: number = 0,\n limit: number = 10\n ): SearchItem[] {\n const flatItems: Item[] = [];\n const flatVectors: number[][] = [];\n const scoreless: Item[] = [];\n\n for (const item of candidates) {\n const vectors = this.getVectors(item);\n if (vectors.length) {\n for (const vector of vectors) {\n flatItems.push(item);\n flatVectors.push(vector);\n }\n } else {\n scoreless.push(item);\n }\n }\n\n const scores = this.cosineSimilarity(queryVector, flatVectors);\n\n const sortedResults = scores\n .map((score, i) => [score, flatItems[i]] as [number, Item])\n .sort((a, b) => b[0] - a[0]);\n\n const seen = new Set<string>();\n const kept: Array<[number | undefined, Item]> = [];\n\n for (const [score, item] of sortedResults) {\n const key = `${item.namespace.join(\":\")}:${item.key}`;\n if (seen.has(key)) continue;\n\n const ix = seen.size;\n if (ix >= offset + limit) break;\n if (ix < offset) {\n seen.add(key);\n continue;\n }\n\n seen.add(key);\n kept.push([score, item]);\n }\n\n if (scoreless.length && kept.length < limit) {\n for (const item of scoreless.slice(0, limit - kept.length)) {\n const key = `${item.namespace.join(\":\")}:${item.key}`;\n if (!seen.has(key)) {\n seen.add(key);\n kept.push([undefined, item]);\n }\n }\n }\n return kept.map(([score, item]) => ({\n ...item,\n score,\n }));\n }\n\n private paginateResults(\n results: SearchItem[],\n offset: number,\n limit: number\n ): SearchItem[] {\n return results.slice(offset, offset + limit);\n }\n\n private extractTexts(ops: PutOperation[]): {\n [text: string]: [string[], string, string][];\n } {\n if (!ops.length || !this._indexConfig) {\n return {};\n }\n\n const toEmbed: { [text: string]: [string[], string, string][] } = {};\n\n for (const op of ops) {\n if (op.value !== null && op.index !== false) {\n const paths =\n op.index === null || op.index === undefined\n ? this._indexConfig.__tokenizedFields ?? []\n : op.index.map(\n (ix) => [ix, tokenizePath(ix)] as [string, string[]]\n );\n for (const [path, field] of paths) {\n const texts = getTextAtPath(op.value, field);\n if (texts.length) {\n if (texts.length > 1) {\n texts.forEach((text, i) => {\n if (!toEmbed[text]) toEmbed[text] = [];\n toEmbed[text].push([op.namespace, op.key, `${path}.${i}`]);\n });\n } else {\n if (!toEmbed[texts[0]]) toEmbed[texts[0]] = [];\n toEmbed[texts[0]].push([op.namespace, op.key, path]);\n }\n }\n }\n }\n }\n\n return toEmbed;\n }\n\n private insertVectors(\n texts: { [text: string]: [string[], string, string][] },\n embeddings: number[][]\n ): void {\n for (const [text, metadata] of Object.entries(texts)) {\n const embedding = embeddings.shift();\n if (!embedding) {\n throw new Error(`No embedding found for text: ${text}`);\n }\n\n for (const [namespace, key, field] of metadata) {\n const namespaceKey = namespace.join(\":\");\n if (!this.vectors.has(namespaceKey)) {\n this.vectors.set(namespaceKey, new Map());\n }\n const namespaceMap = this.vectors.get(namespaceKey)!;\n if (!namespaceMap.has(key)) {\n namespaceMap.set(key, new Map());\n }\n const itemMap = namespaceMap.get(key)!;\n itemMap.set(field, embedding);\n }\n }\n }\n\n private getVectors(item: Item): number[][] {\n const namespaceKey = item.namespace.join(\":\");\n const itemKey = item.key;\n if (!this.vectors.has(namespaceKey)) {\n return [];\n }\n const namespaceMap = this.vectors.get(namespaceKey)!;\n if (!namespaceMap.has(itemKey)) {\n return [];\n }\n const itemMap = namespaceMap.get(itemKey)!;\n const vectors = Array.from(itemMap.values());\n if (!vectors.length) {\n return [];\n }\n return vectors;\n }\n\n private cosineSimilarity(X: number[], Y: number[][]): number[] {\n if (!Y.length) return [];\n\n // Calculate dot products for all vectors at once\n const dotProducts = Y.map((vector) =>\n vector.reduce((acc, val, i) => acc + val * X[i], 0)\n );\n\n // Calculate magnitudes\n const magnitude1 = Math.sqrt(X.reduce((acc, val) => acc + val * val, 0));\n const magnitudes2 = Y.map((vector) =>\n Math.sqrt(vector.reduce((acc, val) => acc + val * val, 0))\n );\n\n // Calculate similarities\n return dotProducts.map((dot, i) => {\n const magnitude2 = magnitudes2[i];\n return magnitude1 && magnitude2 ? dot / (magnitude1 * magnitude2) : 0;\n });\n }\n\n public get indexConfig(): IndexConfig | undefined {\n return this._indexConfig;\n }\n}\n\n/** @deprecated Alias for InMemoryStore */\nexport class MemoryStore extends InMemoryStore {}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,IAAa,gBAAb,cAAmCA,uBAAU;CAC3C,AAAQ,uBAAuC,IAAI;CAGnD,AAAQ,0BAA2D,IAAI;CAEvE,AAAQ;CAIR,YAAY,SAAmC;AAC7C;AACA,MAAI,SAAS,MACX,MAAK,eAAe;GAClB,GAAG,QAAQ;GACX,oBAAoB,QAAQ,MAAM,UAAU,CAAC,MAAM,KAAK,MAAM,CAC5D,GACA,MAAM,MAAM,CAAC,KAAKC,2BAAa;;;CAMvC,MAAM,MACJ,YAC+B;EAC/B,MAAM,UAAU;EAChB,MAAM,yBAAS,IAAI;EACnB,MAAM,4BAAY,IAAI;AAGtB,OAAK,IAAI,IAAI,GAAG,IAAI,WAAW,QAAQ,KAAK,GAAG;GAC7C,MAAM,KAAK,WAAW;AACtB,OAAI,SAAS,MAAM,eAAe,MAAM,EAAE,WAAW,IAEnD,SAAQ,KAAK,KAAK,aAAa;YACtB,qBAAqB,IAAI;IAElC,MAAM,aAAa,KAAK,YAAY;AACpC,cAAU,IAAI,GAAG,CAAC,IAAI;AACtB,YAAQ,KAAK;cACJ,WAAW,IAAI;IAExB,MAAM,MAAM,GAAG,GAAG,UAAU,KAAK,KAAK,GAAG,GAAG;AAC5C,WAAO,IAAI,KAAK;AAChB,YAAQ,KAAK;cACJ,qBAAqB,GAE9B,SAAQ,KAAK,KAA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AAa,YAAY;AAC/B,UAAO,cAAc,aAAa,OAAO,aAAa,cAAc;;;CAIxE,IAAW,cAAuC;AAChD,SAAO,KAAK;;;;AAKhB,IAAa,cAAb,cAAiC,cAAc"}
{"version":3,"file":"memory.cjs","names":["BaseStore","tokenizePath","compareValues","getTextAtPath"],"sources":["../../src/store/memory.ts"],"sourcesContent":["import {\n BaseStore,\n type OperationResults,\n type Item,\n type Operation,\n MatchCondition,\n ListNamespacesOperation,\n PutOperation,\n SearchOperation,\n GetOperation,\n type IndexConfig,\n type SearchItem,\n} from \"./base.js\";\nimport { tokenizePath, compareValues, getTextAtPath } from \"./utils.js\";\n\n/**\n * In-memory key-value store with optional vector search.\n *\n * A lightweight store implementation using JavaScript Maps. Supports basic\n * key-value operations and vector search when configured with embeddings.\n *\n * @example\n * ```typescript\n * // Basic key-value storage\n * const store = new InMemoryStore();\n * await store.put([\"users\", \"123\"], \"prefs\", { theme: \"dark\" });\n * const item = await store.get([\"users\", \"123\"], \"prefs\");\n *\n * // Vector search with embeddings\n * import { OpenAIEmbeddings } from \"@langchain/openai\";\n * const store = new InMemoryStore({\n * index: {\n * dims: 1536,\n * embeddings: new OpenAIEmbeddings({ modelName: \"text-embedding-3-small\" }),\n * }\n * });\n *\n * // Store documents\n * await store.put([\"docs\"], \"doc1\", { text: \"Python tutorial\" });\n * await store.put([\"docs\"], \"doc2\", { text: \"TypeScript guide\" });\n *\n * // Search by similarity\n * const results = await store.search([\"docs\"], { query: \"python programming\" });\n * ```\n *\n * **Warning**: This store keeps all data in memory. Data is lost when the process exits.\n * For persistence, use a database-backed store.\n */\nexport class InMemoryStore extends BaseStore {\n private data: Map<string, Map<string, Item>> = new Map();\n\n // Namespace -> Key -> Path/field -> Vector\n private vectors: Map<string, Map<string, Map<string, number[]>>> = new Map();\n\n private _indexConfig?: IndexConfig & {\n __tokenizedFields: Array<[string, string[]]>;\n };\n\n constructor(options?: { index?: IndexConfig }) {\n super();\n if (options?.index) {\n this._indexConfig = {\n ...options.index,\n __tokenizedFields: (options.index.fields ?? [\"$\"]).map((p) => [\n p,\n p === \"$\" ? [p] : tokenizePath(p),\n ]),\n };\n }\n }\n\n async batch<Op extends readonly Operation[]>(\n operations: Op\n ): Promise<OperationResults<Op>> {\n const results = [];\n const putOps = new Map<string, PutOperation>();\n const searchOps = new Map<number, [SearchOperation, Item[]]>();\n\n // First pass - handle gets and prepare search/put operations\n for (let i = 0; i < operations.length; i += 1) {\n const op = operations[i];\n if (\"key\" in op && \"namespace\" in op && !(\"value\" in op)) {\n // GetOperation\n results.push(this.getOperation(op));\n } else if (\"namespacePrefix\" in op) {\n // SearchOperation\n const candidates = this.filterItems(op);\n searchOps.set(i, [op, candidates]);\n results.push(null);\n } else if (\"value\" in op) {\n // PutOperation\n const key = `${op.namespace.join(\":\")}:${op.key}`;\n putOps.set(key, op);\n results.push(null);\n } else if (\"matchConditions\" in op) {\n // ListNamespacesOperation\n results.push(this.listNamespacesOperation(op));\n }\n }\n\n // Handle search operations with embeddings\n if (searchOps.size > 0) {\n if (this._indexConfig?.embeddings) {\n const queries = new Set<string>();\n for (const [op] of searchOps.values()) {\n if (op.query) queries.add(op.query);\n }\n\n // Get embeddings for all queries\n const queryEmbeddings =\n queries.size > 0\n ? await Promise.all(\n Array.from(queries).map((q) =>\n this._indexConfig!.embeddings.embedQuery(q)\n )\n )\n : [];\n const queryVectors = Object.fromEntries(\n Array.from(queries).map((q, i) => [q, queryEmbeddings[i]])\n );\n\n // Process each search operation\n for (const [i, [op, candidates]] of searchOps.entries()) {\n if (op.query && queryVectors[op.query]) {\n const queryVector = queryVectors[op.query];\n const scoredResults = this.scoreResults(\n candidates,\n queryVector,\n op.offset ?? 0,\n op.limit ?? 10\n );\n results[i] = scoredResults;\n } else {\n results[i] = this.paginateResults(\n candidates.map((item) => ({ ...item, score: undefined })),\n op.offset ?? 0,\n op.limit ?? 10\n );\n }\n }\n } else {\n // No embeddings - just paginate the filtered results\n for (const [i, [op, candidates]] of searchOps.entries()) {\n results[i] = this.paginateResults(\n candidates.map((item) => ({ ...item, score: undefined })),\n op.offset ?? 0,\n op.limit ?? 10\n );\n }\n }\n }\n\n // Handle put operations with embeddings\n if (putOps.size > 0 && this._indexConfig?.embeddings) {\n const toEmbed = this.extractTexts(Array.from(putOps.values()));\n if (Object.keys(toEmbed).length > 0) {\n const embeddings = await this._indexConfig.embeddings.embedDocuments(\n Object.keys(toEmbed)\n );\n this.insertVectors(toEmbed, embeddings);\n }\n }\n\n // Apply all put operations\n for (const op of putOps.values()) {\n this.putOperation(op);\n }\n\n return results as OperationResults<Op>;\n }\n\n private getOperation(op: GetOperation): Item | null {\n const namespaceKey = op.namespace.join(\":\");\n const item = this.data.get(namespaceKey)?.get(op.key);\n return item ?? null;\n }\n\n private putOperation(op: PutOperation): void {\n const namespaceKey = op.namespace.join(\":\");\n if (!this.data.has(namespaceKey)) {\n this.data.set(namespaceKey, new Map());\n }\n const namespaceMap = this.data.get(namespaceKey)!;\n\n if (op.value === null) {\n namespaceMap.delete(op.key);\n } else {\n const now = new Date();\n if (namespaceMap.has(op.key)) {\n const item = namespaceMap.get(op.key)!;\n item.value = op.value;\n item.updatedAt = now;\n } else {\n namespaceMap.set(op.key, {\n value: op.value,\n key: op.key,\n namespace: op.namespace,\n createdAt: now,\n updatedAt: now,\n });\n }\n }\n }\n\n private listNamespacesOperation(op: ListNamespacesOperation): string[][] {\n const allNamespaces = Array.from(this.data.keys()).map((ns) =>\n ns.split(\":\")\n );\n let namespaces = allNamespaces;\n\n if (op.matchConditions && op.matchConditions.length > 0) {\n namespaces = namespaces.filter((ns) =>\n op.matchConditions!.every((condition) => this.doesMatch(condition, ns))\n );\n }\n\n if (op.maxDepth !== undefined) {\n namespaces = Array.from(\n new Set(namespaces.map((ns) => ns.slice(0, op.maxDepth).join(\":\")))\n ).map((ns) => ns.split(\":\"));\n }\n\n namespaces.sort((a, b) => a.join(\":\").localeCompare(b.join(\":\")));\n\n return namespaces.slice(\n op.offset ?? 0,\n (op.offset ?? 0) + (op.limit ?? namespaces.length)\n );\n }\n\n private doesMatch(matchCondition: MatchCondition, key: string[]): boolean {\n const { matchType, path } = matchCondition;\n\n if (matchType === \"prefix\") {\n if (path.length > key.length) return false;\n return path.every((pElem, index) => {\n const kElem = key[index];\n return pElem === \"*\" || kElem === pElem;\n });\n } else if (matchType === \"suffix\") {\n if (path.length > key.length) return false;\n return path.every((pElem, index) => {\n const kElem = key[key.length - path.length + index];\n return pElem === \"*\" || kElem === pElem;\n });\n }\n\n throw new Error(`Unsupported match type: ${matchType}`);\n }\n\n private filterItems(op: SearchOperation): Item[] {\n const candidates: Item[] = [];\n for (const [namespace, items] of this.data.entries()) {\n if (namespace.startsWith(op.namespacePrefix.join(\":\"))) {\n candidates.push(...items.values());\n }\n }\n\n let filteredCandidates = candidates;\n if (op.filter) {\n filteredCandidates = candidates.filter((item) =>\n Object.entries(op.filter!).every(([key, value]) =>\n compareValues(item.value[key], value)\n )\n );\n }\n return filteredCandidates;\n }\n\n private scoreResults(\n candidates: Item[],\n queryVector: number[],\n offset: number = 0,\n limit: number = 10\n ): SearchItem[] {\n const flatItems: Item[] = [];\n const flatVectors: number[][] = [];\n const scoreless: Item[] = [];\n\n for (const item of candidates) {\n const vectors = this.getVectors(item);\n if (vectors.length) {\n for (const vector of vectors) {\n flatItems.push(item);\n flatVectors.push(vector);\n }\n } else {\n scoreless.push(item);\n }\n }\n\n const scores = this.cosineSimilarity(queryVector, flatVectors);\n\n const sortedResults = scores\n .map((score, i) => [score, flatItems[i]] as [number, Item])\n .sort((a, b) => b[0] - a[0]);\n\n const seen = new Set<string>();\n const kept: Array<[number | undefined, Item]> = [];\n\n for (const [score, item] of sortedResults) {\n const key = `${item.namespace.join(\":\")}:${item.key}`;\n if (seen.has(key)) continue;\n\n const ix = seen.size;\n if (ix >= offset + limit) break;\n if (ix < offset) {\n seen.add(key);\n continue;\n }\n\n seen.add(key);\n kept.push([score, item]);\n }\n\n if (scoreless.length && kept.length < limit) {\n for (const item of scoreless.slice(0, limit - kept.length)) {\n const key = `${item.namespace.join(\":\")}:${item.key}`;\n if (!seen.has(key)) {\n seen.add(key);\n kept.push([undefined, item]);\n }\n }\n }\n return kept.map(([score, item]) => ({\n ...item,\n score,\n }));\n }\n\n private paginateResults(\n results: SearchItem[],\n offset: number,\n limit: number\n ): SearchItem[] {\n return results.slice(offset, offset + limit);\n }\n\n private extractTexts(ops: PutOperation[]): {\n [text: string]: [string[], string, string][];\n } {\n if (!ops.length || !this._indexConfig) {\n return {};\n }\n\n const toEmbed: { [text: string]: [string[], string, string][] } = {};\n\n for (const op of ops) {\n if (op.value !== null && op.index !== false) {\n const paths =\n op.index === null || op.index === undefined\n ? this._indexConfig.__tokenizedFields ?? []\n : op.index.map(\n (ix) => [ix, tokenizePath(ix)] as [string, string[]]\n );\n for (const [path, field] of paths) {\n const texts = getTextAtPath(op.value, field);\n if (texts.length) {\n if (texts.length > 1) {\n texts.forEach((text, i) => {\n if (!toEmbed[text]) toEmbed[text] = [];\n toEmbed[text].push([op.namespace, op.key, `${path}.${i}`]);\n });\n } else {\n if (!toEmbed[texts[0]]) toEmbed[texts[0]] = [];\n toEmbed[texts[0]].push([op.namespace, op.key, path]);\n }\n }\n }\n }\n }\n\n return toEmbed;\n }\n\n private insertVectors(\n texts: { [text: string]: [string[], string, string][] },\n embeddings: number[][]\n ): void {\n for (const [text, metadata] of Object.entries(texts)) {\n const embedding = embeddings.shift();\n if (!embedding) {\n throw new Error(`No embedding found for text: ${text}`);\n }\n\n for (const [namespace, key, field] of metadata) {\n const namespaceKey = namespace.join(\":\");\n if (!this.vectors.has(namespaceKey)) {\n this.vectors.set(namespaceKey, new Map());\n }\n const namespaceMap = this.vectors.get(namespaceKey)!;\n if (!namespaceMap.has(key)) {\n namespaceMap.set(key, new Map());\n }\n const itemMap = namespaceMap.get(key)!;\n itemMap.set(field, embedding);\n }\n }\n }\n\n private getVectors(item: Item): number[][] {\n const namespaceKey = item.namespace.join(\":\");\n const itemKey = item.key;\n if (!this.vectors.has(namespaceKey)) {\n return [];\n }\n const namespaceMap = this.vectors.get(namespaceKey)!;\n if (!namespaceMap.has(itemKey)) {\n return [];\n }\n const itemMap = namespaceMap.get(itemKey)!;\n const vectors = Array.from(itemMap.values());\n if (!vectors.length) {\n return [];\n }\n return vectors;\n }\n\n private cosineSimilarity(X: number[], Y: number[][]): number[] {\n if (!Y.length) return [];\n\n // Calculate dot products for all vectors at once\n const dotProducts = Y.map((vector) =>\n vector.reduce((acc, val, i) => acc + val * X[i], 0)\n );\n\n // Calculate magnitudes\n const magnitude1 = Math.sqrt(X.reduce((acc, val) => acc + val * val, 0));\n const magnitudes2 = Y.map((vector) =>\n Math.sqrt(vector.reduce((acc, val) => acc + val * val, 0))\n );\n\n // Calculate similarities\n return dotProducts.map((dot, i) => {\n const magnitude2 = magnitudes2[i];\n return magnitude1 && magnitude2 ? dot / (magnitude1 * magnitude2) : 0;\n });\n }\n\n public get indexConfig(): IndexConfig | undefined {\n return this._indexConfig;\n }\n}\n\n/** @deprecated Alias for InMemoryStore */\nexport class MemoryStore extends InMemoryStore {}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,IAAa,gBAAb,cAAmCA,aAAAA,UAAU;CAC3C,uBAA+C,IAAI,KAAK;CAGxD,0BAAmE,IAAI,KAAK;CAE5E;CAIA,YAAY,SAAmC;AAC7C,SAAO;AACP,MAAI,SAAS,MACX,MAAK,eAAe;GAClB,GAAG,QAAQ;GACX,oBAAoB,QAAQ,MAAM,UAAU,CAAC,IAAI,EAAE,KAAK,MAAM,CAC5D,GACA,MAAM,MAAM,CAAC,EAAE,GAAGC,cAAAA,aAAa,EAAE,CAClC,CAAC;GACH;;CAIL,MAAM,MACJ,YAC+B;EAC/B,MAAM,UAAU,EAAE;EAClB,MAAM,yBAAS,IAAI,KAA2B;EAC9C,MAAM,4BAAY,IAAI,KAAwC;AAG9D,OAAK,IAAI,IAAI,GAAG,IAAI,WAAW,QAAQ,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AO,cAAc,aAAa,OAAO,aAAa,cAAc;IACpE;;CAGJ,IAAW,cAAuC;AAChD,SAAO,KAAK;;;;AAKhB,IAAa,cAAb,cAAiC,cAAc"}
import { BaseStore, IndexConfig, Operation, OperationResults } from "./base.cjs";
//#region src/store/memory.d.ts
/**

@@ -40,3 +39,2 @@ * In-memory key-value store with optional vector search.

private data;
// Namespace -> Key -> Path/field -> Vector
private vectors;

@@ -43,0 +41,0 @@ private _indexConfig?;

@@ -1,1 +0,1 @@

{"version":3,"file":"memory.d.cts","names":["BaseStore","OperationResults","Operation","IndexConfig","InMemoryStore","Op","Promise","MemoryStore"],"sources":["../../src/store/memory.d.ts"],"sourcesContent":["import { BaseStore, type OperationResults, type Operation, type IndexConfig } from \"./base.js\";\n/**\n * In-memory key-value store with optional vector search.\n *\n * A lightweight store implementation using JavaScript Maps. Supports basic\n * key-value operations and vector search when configured with embeddings.\n *\n * @example\n * ```typescript\n * // Basic key-value storage\n * const store = new InMemoryStore();\n * await store.put([\"users\", \"123\"], \"prefs\", { theme: \"dark\" });\n * const item = await store.get([\"users\", \"123\"], \"prefs\");\n *\n * // Vector search with embeddings\n * import { OpenAIEmbeddings } from \"@langchain/openai\";\n * const store = new InMemoryStore({\n * index: {\n * dims: 1536,\n * embeddings: new OpenAIEmbeddings({ modelName: \"text-embedding-3-small\" }),\n * }\n * });\n *\n * // Store documents\n * await store.put([\"docs\"], \"doc1\", { text: \"Python tutorial\" });\n * await store.put([\"docs\"], \"doc2\", { text: \"TypeScript guide\" });\n *\n * // Search by similarity\n * const results = await store.search([\"docs\"], { query: \"python programming\" });\n * ```\n *\n * **Warning**: This store keeps all data in memory. Data is lost when the process exits.\n * For persistence, use a database-backed store.\n */\nexport declare class InMemoryStore extends BaseStore {\n private data;\n // Namespace -> Key -> Path/field -> Vector\n private vectors;\n private _indexConfig?;\n constructor(options?: {\n index?: IndexConfig;\n });\n batch<Op extends readonly Operation[]>(operations: Op): Promise<OperationResults<Op>>;\n private getOperation;\n private putOperation;\n private listNamespacesOperation;\n private doesMatch;\n private filterItems;\n private scoreResults;\n private paginateResults;\n private extractTexts;\n private insertVectors;\n private getVectors;\n private cosineSimilarity;\n get indexConfig(): IndexConfig | undefined;\n}\n/** @deprecated Alias for InMemoryStore */\nexport declare class MemoryStore extends InMemoryStore {\n}\n"],"mappings":";;;;;;AAkCA;;;;;;;;;;;AAuBA;;;;;;;;;;;;;;;;;;;;cAvBqBI,aAAAA,SAAsBJ,SAAAA;;;;;;YAM3BG;;4BAEcD,yBAAyBG,KAAKC,QAAQL,iBAAiBI;;;;;;;;;;;;qBAY9DF;;;cAGFI,WAAAA,SAAoBH,aAAAA"}
{"version":3,"file":"memory.d.cts","names":[],"sources":["../../src/store/memory.ts"],"mappings":";;;;;AAgDA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAAa,aAAA,SAAsB,SAAA;EAAA,QACzB,IAAA;EAAA,QAGA,OAAA;EAAA,QAEA,YAAA;EAIR,WAAA,CAAY,OAAA;IAAY,KAAA,GAAQ,WAAA;EAAA;EAa1B,KAAA,qBAA0B,SAAA,GAAA,CAC9B,UAAA,EAAY,EAAA,GACX,OAAA,CAAQ,gBAAA,CAAiB,EAAA;EAAA,QAkGpB,YAAA;EAAA,QAMA,YAAA;EAAA,QA2BA,uBAAA;EAAA,QA0BA,SAAA;EAAA,QAoBA,WAAA;EAAA,QAmBA,YAAA;EAAA,QA6DA,eAAA;EAAA,QAQA,YAAA;EAAA,QAqCA,aAAA;EAAA,QAyBA,UAAA;EAAA,QAkBA,gBAAA;EAAA,IAqBG,WAAA,CAAA,GAAe,WAAA;AAAA;;cAMf,WAAA,SAAoB,aAAA"}
import { BaseStore, IndexConfig, Operation, OperationResults } from "./base.js";
//#region src/store/memory.d.ts
/**

@@ -40,3 +39,2 @@ * In-memory key-value store with optional vector search.

private data;
// Namespace -> Key -> Path/field -> Vector
private vectors;

@@ -43,0 +41,0 @@ private _indexConfig?;

@@ -1,1 +0,1 @@

{"version":3,"file":"memory.d.ts","names":["BaseStore","OperationResults","Operation","IndexConfig","InMemoryStore","Op","Promise","MemoryStore"],"sources":["../../src/store/memory.d.ts"],"sourcesContent":["import { BaseStore, type OperationResults, type Operation, type IndexConfig } from \"./base.js\";\n/**\n * In-memory key-value store with optional vector search.\n *\n * A lightweight store implementation using JavaScript Maps. Supports basic\n * key-value operations and vector search when configured with embeddings.\n *\n * @example\n * ```typescript\n * // Basic key-value storage\n * const store = new InMemoryStore();\n * await store.put([\"users\", \"123\"], \"prefs\", { theme: \"dark\" });\n * const item = await store.get([\"users\", \"123\"], \"prefs\");\n *\n * // Vector search with embeddings\n * import { OpenAIEmbeddings } from \"@langchain/openai\";\n * const store = new InMemoryStore({\n * index: {\n * dims: 1536,\n * embeddings: new OpenAIEmbeddings({ modelName: \"text-embedding-3-small\" }),\n * }\n * });\n *\n * // Store documents\n * await store.put([\"docs\"], \"doc1\", { text: \"Python tutorial\" });\n * await store.put([\"docs\"], \"doc2\", { text: \"TypeScript guide\" });\n *\n * // Search by similarity\n * const results = await store.search([\"docs\"], { query: \"python programming\" });\n * ```\n *\n * **Warning**: This store keeps all data in memory. Data is lost when the process exits.\n * For persistence, use a database-backed store.\n */\nexport declare class InMemoryStore extends BaseStore {\n private data;\n // Namespace -> Key -> Path/field -> Vector\n private vectors;\n private _indexConfig?;\n constructor(options?: {\n index?: IndexConfig;\n });\n batch<Op extends readonly Operation[]>(operations: Op): Promise<OperationResults<Op>>;\n private getOperation;\n private putOperation;\n private listNamespacesOperation;\n private doesMatch;\n private filterItems;\n private scoreResults;\n private paginateResults;\n private extractTexts;\n private insertVectors;\n private getVectors;\n private cosineSimilarity;\n get indexConfig(): IndexConfig | undefined;\n}\n/** @deprecated Alias for InMemoryStore */\nexport declare class MemoryStore extends InMemoryStore {\n}\n"],"mappings":";;;;;;AAkCA;;;;;;;;;;;AAuBA;;;;;;;;;;;;;;;;;;;;cAvBqBI,aAAAA,SAAsBJ,SAAAA;;;;;;YAM3BG;;4BAEcD,yBAAyBG,KAAKC,QAAQL,iBAAiBI;;;;;;;;;;;;qBAY9DF;;;cAGFI,WAAAA,SAAoBH,aAAAA"}
{"version":3,"file":"memory.d.ts","names":[],"sources":["../../src/store/memory.ts"],"mappings":";;;;;AAgDA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAAa,aAAA,SAAsB,SAAA;EAAA,QACzB,IAAA;EAAA,QAGA,OAAA;EAAA,QAEA,YAAA;EAIR,WAAA,CAAY,OAAA;IAAY,KAAA,GAAQ,WAAA;EAAA;EAa1B,KAAA,qBAA0B,SAAA,GAAA,CAC9B,UAAA,EAAY,EAAA,GACX,OAAA,CAAQ,gBAAA,CAAiB,EAAA;EAAA,QAkGpB,YAAA;EAAA,QAMA,YAAA;EAAA,QA2BA,uBAAA;EAAA,QA0BA,SAAA;EAAA,QAoBA,WAAA;EAAA,QAmBA,YAAA;EAAA,QA6DA,eAAA;EAAA,QAQA,YAAA;EAAA,QAqCA,aAAA;EAAA,QAyBA,UAAA;EAAA,QAkBA,gBAAA;EAAA,IAqBG,WAAA,CAAA,GAAe,WAAA;AAAA;;cAMf,WAAA,SAAoB,aAAA"}
import { BaseStore } from "./base.js";
import { compareValues, getTextAtPath, tokenizePath } from "./utils.js";
//#region src/store/memory.ts

@@ -73,4 +72,3 @@ /**

const queryVector = queryVectors[op.query];
const scoredResults = this.scoreResults(candidates, queryVector, op.offset ?? 0, op.limit ?? 10);
results[i] = scoredResults;
results[i] = this.scoreResults(candidates, queryVector, op.offset ?? 0, op.limit ?? 10);
} else results[i] = this.paginateResults(candidates.map((item) => ({

@@ -96,4 +94,3 @@ ...item,

const namespaceKey = op.namespace.join(":");
const item = this.data.get(namespaceKey)?.get(op.key);
return item ?? null;
return this.data.get(namespaceKey)?.get(op.key) ?? null;
}

@@ -121,4 +118,3 @@ putOperation(op) {

listNamespacesOperation(op) {
const allNamespaces = Array.from(this.data.keys()).map((ns) => ns.split(":"));
let namespaces = allNamespaces;
let namespaces = Array.from(this.data.keys()).map((ns) => ns.split(":"));
if (op.matchConditions && op.matchConditions.length > 0) namespaces = namespaces.filter((ns) => op.matchConditions.every((condition) => this.doesMatch(condition, ns)));

@@ -165,4 +161,3 @@ if (op.maxDepth !== void 0) namespaces = Array.from(new Set(namespaces.map((ns) => ns.slice(0, op.maxDepth).join(":")))).map((ns) => ns.split(":"));

}
const scores = this.cosineSimilarity(queryVector, flatVectors);
const sortedResults = scores.map((score, i) => [score, flatItems[i]]).sort((a, b) => b[0] - a[0]);
const sortedResults = this.cosineSimilarity(queryVector, flatVectors).map((score, i) => [score, flatItems[i]]).sort((a, b) => b[0] - a[0]);
const seen = /* @__PURE__ */ new Set();

@@ -233,4 +228,3 @@ const kept = [];

if (!namespaceMap.has(key)) namespaceMap.set(key, /* @__PURE__ */ new Map());
const itemMap = namespaceMap.get(key);
itemMap.set(field, embedding);
namespaceMap.get(key).set(field, embedding);
}

@@ -266,5 +260,5 @@ }

var MemoryStore = class extends InMemoryStore {};
//#endregion
export { InMemoryStore, MemoryStore };
//# sourceMappingURL=memory.js.map

@@ -1,1 +0,1 @@

{"version":3,"file":"memory.js","names":["candidates: Item[]","flatItems: Item[]","flatVectors: number[][]","scoreless: Item[]","kept: Array<[number | undefined, Item]>","toEmbed: { [text: string]: [string[], string, string][] }"],"sources":["../../src/store/memory.ts"],"sourcesContent":["import {\n BaseStore,\n type OperationResults,\n type Item,\n type Operation,\n MatchCondition,\n ListNamespacesOperation,\n PutOperation,\n SearchOperation,\n GetOperation,\n type IndexConfig,\n type SearchItem,\n} from \"./base.js\";\nimport { tokenizePath, compareValues, getTextAtPath } from \"./utils.js\";\n\n/**\n * In-memory key-value store with optional vector search.\n *\n * A lightweight store implementation using JavaScript Maps. Supports basic\n * key-value operations and vector search when configured with embeddings.\n *\n * @example\n * ```typescript\n * // Basic key-value storage\n * const store = new InMemoryStore();\n * await store.put([\"users\", \"123\"], \"prefs\", { theme: \"dark\" });\n * const item = await store.get([\"users\", \"123\"], \"prefs\");\n *\n * // Vector search with embeddings\n * import { OpenAIEmbeddings } from \"@langchain/openai\";\n * const store = new InMemoryStore({\n * index: {\n * dims: 1536,\n * embeddings: new OpenAIEmbeddings({ modelName: \"text-embedding-3-small\" }),\n * }\n * });\n *\n * // Store documents\n * await store.put([\"docs\"], \"doc1\", { text: \"Python tutorial\" });\n * await store.put([\"docs\"], \"doc2\", { text: \"TypeScript guide\" });\n *\n * // Search by similarity\n * const results = await store.search([\"docs\"], { query: \"python programming\" });\n * ```\n *\n * **Warning**: This store keeps all data in memory. Data is lost when the process exits.\n * For persistence, use a database-backed store.\n */\nexport class InMemoryStore extends BaseStore {\n private data: Map<string, Map<string, Item>> = new Map();\n\n // Namespace -> Key -> Path/field -> Vector\n private vectors: Map<string, Map<string, Map<string, number[]>>> = new Map();\n\n private _indexConfig?: IndexConfig & {\n __tokenizedFields: Array<[string, string[]]>;\n };\n\n constructor(options?: { index?: IndexConfig }) {\n super();\n if (options?.index) {\n this._indexConfig = {\n ...options.index,\n __tokenizedFields: (options.index.fields ?? [\"$\"]).map((p) => [\n p,\n p === \"$\" ? [p] : tokenizePath(p),\n ]),\n };\n }\n }\n\n async batch<Op extends readonly Operation[]>(\n operations: Op\n ): Promise<OperationResults<Op>> {\n const results = [];\n const putOps = new Map<string, PutOperation>();\n const searchOps = new Map<number, [SearchOperation, Item[]]>();\n\n // First pass - handle gets and prepare search/put operations\n for (let i = 0; i < operations.length; i += 1) {\n const op = operations[i];\n if (\"key\" in op && \"namespace\" in op && !(\"value\" in op)) {\n // GetOperation\n results.push(this.getOperation(op));\n } else if (\"namespacePrefix\" in op) {\n // SearchOperation\n const candidates = this.filterItems(op);\n searchOps.set(i, [op, candidates]);\n results.push(null);\n } else if (\"value\" in op) {\n // PutOperation\n const key = `${op.namespace.join(\":\")}:${op.key}`;\n putOps.set(key, op);\n results.push(null);\n } else if (\"matchConditions\" in op) {\n // ListNamespacesOperation\n results.push(this.listNamespacesOperation(op));\n }\n }\n\n // Handle search operations with embeddings\n if (searchOps.size > 0) {\n if (this._indexConfig?.embeddings) {\n const queries = new Set<string>();\n for (const [op] of searchOps.values()) {\n if (op.query) queries.add(op.query);\n }\n\n // Get embeddings for all queries\n const queryEmbeddings =\n queries.size > 0\n ? await Promise.all(\n Array.from(queries).map((q) =>\n this._indexConfig!.embeddings.embedQuery(q)\n )\n )\n : [];\n const queryVectors = Object.fromEntries(\n Array.from(queries).map((q, i) => [q, queryEmbeddings[i]])\n );\n\n // Process each search operation\n for (const [i, [op, candidates]] of searchOps.entries()) {\n if (op.query && queryVectors[op.query]) {\n const queryVector = queryVectors[op.query];\n const scoredResults = this.scoreResults(\n candidates,\n queryVector,\n op.offset ?? 0,\n op.limit ?? 10\n );\n results[i] = scoredResults;\n } else {\n results[i] = this.paginateResults(\n candidates.map((item) => ({ ...item, score: undefined })),\n op.offset ?? 0,\n op.limit ?? 10\n );\n }\n }\n } else {\n // No embeddings - just paginate the filtered results\n for (const [i, [op, candidates]] of searchOps.entries()) {\n results[i] = this.paginateResults(\n candidates.map((item) => ({ ...item, score: undefined })),\n op.offset ?? 0,\n op.limit ?? 10\n );\n }\n }\n }\n\n // Handle put operations with embeddings\n if (putOps.size > 0 && this._indexConfig?.embeddings) {\n const toEmbed = this.extractTexts(Array.from(putOps.values()));\n if (Object.keys(toEmbed).length > 0) {\n const embeddings = await this._indexConfig.embeddings.embedDocuments(\n Object.keys(toEmbed)\n );\n this.insertVectors(toEmbed, embeddings);\n }\n }\n\n // Apply all put operations\n for (const op of putOps.values()) {\n this.putOperation(op);\n }\n\n return results as OperationResults<Op>;\n }\n\n private getOperation(op: GetOperation): Item | null {\n const namespaceKey = op.namespace.join(\":\");\n const item = this.data.get(namespaceKey)?.get(op.key);\n return item ?? null;\n }\n\n private putOperation(op: PutOperation): void {\n const namespaceKey = op.namespace.join(\":\");\n if (!this.data.has(namespaceKey)) {\n this.data.set(namespaceKey, new Map());\n }\n const namespaceMap = this.data.get(namespaceKey)!;\n\n if (op.value === null) {\n namespaceMap.delete(op.key);\n } else {\n const now = new Date();\n if (namespaceMap.has(op.key)) {\n const item = namespaceMap.get(op.key)!;\n item.value = op.value;\n item.updatedAt = now;\n } else {\n namespaceMap.set(op.key, {\n value: op.value,\n key: op.key,\n namespace: op.namespace,\n createdAt: now,\n updatedAt: now,\n });\n }\n }\n }\n\n private listNamespacesOperation(op: ListNamespacesOperation): string[][] {\n const allNamespaces = Array.from(this.data.keys()).map((ns) =>\n ns.split(\":\")\n );\n let namespaces = allNamespaces;\n\n if (op.matchConditions && op.matchConditions.length > 0) {\n namespaces = namespaces.filter((ns) =>\n op.matchConditions!.every((condition) => this.doesMatch(condition, ns))\n );\n }\n\n if (op.maxDepth !== undefined) {\n namespaces = Array.from(\n new Set(namespaces.map((ns) => ns.slice(0, op.maxDepth).join(\":\")))\n ).map((ns) => ns.split(\":\"));\n }\n\n namespaces.sort((a, b) => a.join(\":\").localeCompare(b.join(\":\")));\n\n return namespaces.slice(\n op.offset ?? 0,\n (op.offset ?? 0) + (op.limit ?? namespaces.length)\n );\n }\n\n private doesMatch(matchCondition: MatchCondition, key: string[]): boolean {\n const { matchType, path } = matchCondition;\n\n if (matchType === \"prefix\") {\n if (path.length > key.length) return false;\n return path.every((pElem, index) => {\n const kElem = key[index];\n return pElem === \"*\" || kElem === pElem;\n });\n } else if (matchType === \"suffix\") {\n if (path.length > key.length) return false;\n return path.every((pElem, index) => {\n const kElem = key[key.length - path.length + index];\n return pElem === \"*\" || kElem === pElem;\n });\n }\n\n throw new Error(`Unsupported match type: ${matchType}`);\n }\n\n private filterItems(op: SearchOperation): Item[] {\n const candidates: Item[] = [];\n for (const [namespace, items] of this.data.entries()) {\n if (namespace.startsWith(op.namespacePrefix.join(\":\"))) {\n candidates.push(...items.values());\n }\n }\n\n let filteredCandidates = candidates;\n if (op.filter) {\n filteredCandidates = candidates.filter((item) =>\n Object.entries(op.filter!).every(([key, value]) =>\n compareValues(item.value[key], value)\n )\n );\n }\n return filteredCandidates;\n }\n\n private scoreResults(\n candidates: Item[],\n queryVector: number[],\n offset: number = 0,\n limit: number = 10\n ): SearchItem[] {\n const flatItems: Item[] = [];\n const flatVectors: number[][] = [];\n const scoreless: Item[] = [];\n\n for (const item of candidates) {\n const vectors = this.getVectors(item);\n if (vectors.length) {\n for (const vector of vectors) {\n flatItems.push(item);\n flatVectors.push(vector);\n }\n } else {\n scoreless.push(item);\n }\n }\n\n const scores = this.cosineSimilarity(queryVector, flatVectors);\n\n const sortedResults = scores\n .map((score, i) => [score, flatItems[i]] as [number, Item])\n .sort((a, b) => b[0] - a[0]);\n\n const seen = new Set<string>();\n const kept: Array<[number | undefined, Item]> = [];\n\n for (const [score, item] of sortedResults) {\n const key = `${item.namespace.join(\":\")}:${item.key}`;\n if (seen.has(key)) continue;\n\n const ix = seen.size;\n if (ix >= offset + limit) break;\n if (ix < offset) {\n seen.add(key);\n continue;\n }\n\n seen.add(key);\n kept.push([score, item]);\n }\n\n if (scoreless.length && kept.length < limit) {\n for (const item of scoreless.slice(0, limit - kept.length)) {\n const key = `${item.namespace.join(\":\")}:${item.key}`;\n if (!seen.has(key)) {\n seen.add(key);\n kept.push([undefined, item]);\n }\n }\n }\n return kept.map(([score, item]) => ({\n ...item,\n score,\n }));\n }\n\n private paginateResults(\n results: SearchItem[],\n offset: number,\n limit: number\n ): SearchItem[] {\n return results.slice(offset, offset + limit);\n }\n\n private extractTexts(ops: PutOperation[]): {\n [text: string]: [string[], string, string][];\n } {\n if (!ops.length || !this._indexConfig) {\n return {};\n }\n\n const toEmbed: { [text: string]: [string[], string, string][] } = {};\n\n for (const op of ops) {\n if (op.value !== null && op.index !== false) {\n const paths =\n op.index === null || op.index === undefined\n ? this._indexConfig.__tokenizedFields ?? []\n : op.index.map(\n (ix) => [ix, tokenizePath(ix)] as [string, string[]]\n );\n for (const [path, field] of paths) {\n const texts = getTextAtPath(op.value, field);\n if (texts.length) {\n if (texts.length > 1) {\n texts.forEach((text, i) => {\n if (!toEmbed[text]) toEmbed[text] = [];\n toEmbed[text].push([op.namespace, op.key, `${path}.${i}`]);\n });\n } else {\n if (!toEmbed[texts[0]]) toEmbed[texts[0]] = [];\n toEmbed[texts[0]].push([op.namespace, op.key, path]);\n }\n }\n }\n }\n }\n\n return toEmbed;\n }\n\n private insertVectors(\n texts: { [text: string]: [string[], string, string][] },\n embeddings: number[][]\n ): void {\n for (const [text, metadata] of Object.entries(texts)) {\n const embedding = embeddings.shift();\n if (!embedding) {\n throw new Error(`No embedding found for text: ${text}`);\n }\n\n for (const [namespace, key, field] of metadata) {\n const namespaceKey = namespace.join(\":\");\n if (!this.vectors.has(namespaceKey)) {\n this.vectors.set(namespaceKey, new Map());\n }\n const namespaceMap = this.vectors.get(namespaceKey)!;\n if (!namespaceMap.has(key)) {\n namespaceMap.set(key, new Map());\n }\n const itemMap = namespaceMap.get(key)!;\n itemMap.set(field, embedding);\n }\n }\n }\n\n private getVectors(item: Item): number[][] {\n const namespaceKey = item.namespace.join(\":\");\n const itemKey = item.key;\n if (!this.vectors.has(namespaceKey)) {\n return [];\n }\n const namespaceMap = this.vectors.get(namespaceKey)!;\n if (!namespaceMap.has(itemKey)) {\n return [];\n }\n const itemMap = namespaceMap.get(itemKey)!;\n const vectors = Array.from(itemMap.values());\n if (!vectors.length) {\n return [];\n }\n return vectors;\n }\n\n private cosineSimilarity(X: number[], Y: number[][]): number[] {\n if (!Y.length) return [];\n\n // Calculate dot products for all vectors at once\n const dotProducts = Y.map((vector) =>\n vector.reduce((acc, val, i) => acc + val * X[i], 0)\n );\n\n // Calculate magnitudes\n const magnitude1 = Math.sqrt(X.reduce((acc, val) => acc + val * val, 0));\n const magnitudes2 = Y.map((vector) =>\n Math.sqrt(vector.reduce((acc, val) => acc + val * val, 0))\n );\n\n // Calculate similarities\n return dotProducts.map((dot, i) => {\n const magnitude2 = magnitudes2[i];\n return magnitude1 && magnitude2 ? dot / (magnitude1 * magnitude2) : 0;\n });\n }\n\n public get indexConfig(): IndexConfig | undefined {\n return this._indexConfig;\n }\n}\n\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IAAI,cACpB,MAAK,QAAQ,IAAI,8BAAc,IAAI;IAErC,MAAM,eAAe,KAAK,QAAQ,IAAI;AACtC,QAAI,CAAC,aAAa,IAAI,KACpB,cAAa,IAAI,qBAAK,IAAI;IAE5B,MAAM,UAAU,aAAa,IAAI;AACjC,YAAQ,IAAI,OAAO;;;;CAKzB,AAAQ,WAAW,MAAwB;EACzC,MAAM,eAAe,KAAK,UAAU,KAAK;EACzC,MAAM,UAAU,KAAK;AACrB,MAAI,CAAC,KAAK,QAAQ,IAAI,cACpB,QAAO;EAET,MAAM,eAAe,KAAK,QAAQ,IAAI;AACtC,MAAI,CAAC,aAAa,IAAI,SACpB,QAAO;EAET,MAAM,UAAU,aAAa,IAAI;EACjC,MAAM,UAAU,MAAM,KAAK,QAAQ;AACnC,MAAI,CAAC,QAAQ,OACX,QAAO;AAET,SAAO;;CAGT,AAAQ,iBAAiB,GAAa,GAAyB;AAC7D,MAAI,CAAC,EAAE,OAAQ,QAAO;EAGtB,MAAM,cAAc,EAAE,KAAK,WACzB,OAAO,QAAQ,KAAK,KAAK,MAAM,MAAM,MAAM,EAAE,IAAI;EAInD,MAAM,aAAa,KAAK,KAAK,EAAE,QAAQ,KAAK,QAAQ,MAAM,MAAM,KAAK;EACrE,MAAM,cAAc,EAAE,KAAK,WACzB,KAAK,KAAK,OAAO,QAAQ,KAAK,QAAQ,MAAM,MAAM,KAAK;AAIzD,SAAO,YAAY,KAAK,KAAK,MAAM;GACjC,MAAM,aAAa,YAAY;AAC/B,UAAO,cAAc,aAAa,OAAO,aAAa,cAAc;;;CAIxE,IAAW,cAAuC;AAChD,SAAO,KAAK;;;;AAKhB,IAAa,cAAb,cAAiC,cAAc"}
{"version":3,"file":"memory.js","names":[],"sources":["../../src/store/memory.ts"],"sourcesContent":["import {\n BaseStore,\n type OperationResults,\n type Item,\n type Operation,\n MatchCondition,\n ListNamespacesOperation,\n PutOperation,\n SearchOperation,\n GetOperation,\n type IndexConfig,\n type SearchItem,\n} from \"./base.js\";\nimport { tokenizePath, compareValues, getTextAtPath } from \"./utils.js\";\n\n/**\n * In-memory key-value store with optional vector search.\n *\n * A lightweight store implementation using JavaScript Maps. Supports basic\n * key-value operations and vector search when configured with embeddings.\n *\n * @example\n * ```typescript\n * // Basic key-value storage\n * const store = new InMemoryStore();\n * await store.put([\"users\", \"123\"], \"prefs\", { theme: \"dark\" });\n * const item = await store.get([\"users\", \"123\"], \"prefs\");\n *\n * // Vector search with embeddings\n * import { OpenAIEmbeddings } from \"@langchain/openai\";\n * const store = new InMemoryStore({\n * index: {\n * dims: 1536,\n * embeddings: new OpenAIEmbeddings({ modelName: \"text-embedding-3-small\" }),\n * }\n * });\n *\n * // Store documents\n * await store.put([\"docs\"], \"doc1\", { text: \"Python tutorial\" });\n * await store.put([\"docs\"], \"doc2\", { text: \"TypeScript guide\" });\n *\n * // Search by similarity\n * const results = await store.search([\"docs\"], { query: \"python programming\" });\n * ```\n *\n * **Warning**: This store keeps all data in memory. Data is lost when the process exits.\n * For persistence, use a database-backed store.\n */\nexport class InMemoryStore extends BaseStore {\n private data: Map<string, Map<string, Item>> = new Map();\n\n // Namespace -> Key -> Path/field -> Vector\n private vectors: Map<string, Map<string, Map<string, number[]>>> = new Map();\n\n private _indexConfig?: IndexConfig & {\n __tokenizedFields: Array<[string, string[]]>;\n };\n\n constructor(options?: { index?: IndexConfig }) {\n super();\n if (options?.index) {\n this._indexConfig = {\n ...options.index,\n __tokenizedFields: (options.index.fields ?? [\"$\"]).map((p) => [\n p,\n p === \"$\" ? [p] : tokenizePath(p),\n ]),\n };\n }\n }\n\n async batch<Op extends readonly Operation[]>(\n operations: Op\n ): Promise<OperationResults<Op>> {\n const results = [];\n const putOps = new Map<string, PutOperation>();\n const searchOps = new Map<number, [SearchOperation, Item[]]>();\n\n // First pass - handle gets and prepare search/put operations\n for (let i = 0; i < operations.length; i += 1) {\n const op = operations[i];\n if (\"key\" in op && \"namespace\" in op && !(\"value\" in op)) {\n // GetOperation\n results.push(this.getOperation(op));\n } else if (\"namespacePrefix\" in op) {\n // SearchOperation\n const candidates = this.filterItems(op);\n searchOps.set(i, [op, candidates]);\n results.push(null);\n } else if (\"value\" in op) {\n // PutOperation\n const key = `${op.namespace.join(\":\")}:${op.key}`;\n putOps.set(key, op);\n results.push(null);\n } else if (\"matchConditions\" in op) {\n // ListNamespacesOperation\n results.push(this.listNamespacesOperation(op));\n }\n }\n\n // Handle search operations with embeddings\n if (searchOps.size > 0) {\n if (this._indexConfig?.embeddings) {\n const queries = new Set<string>();\n for (const [op] of searchOps.values()) {\n if (op.query) queries.add(op.query);\n }\n\n // Get embeddings for all queries\n const queryEmbeddings =\n queries.size > 0\n ? await Promise.all(\n Array.from(queries).map((q) =>\n this._indexConfig!.embeddings.embedQuery(q)\n )\n )\n : [];\n const queryVectors = Object.fromEntries(\n Array.from(queries).map((q, i) => [q, queryEmbeddings[i]])\n );\n\n // Process each search operation\n for (const [i, [op, candidates]] of searchOps.entries()) {\n if (op.query && queryVectors[op.query]) {\n const queryVector = queryVectors[op.query];\n const scoredResults = this.scoreResults(\n candidates,\n queryVector,\n op.offset ?? 0,\n op.limit ?? 10\n );\n results[i] = scoredResults;\n } else {\n results[i] = this.paginateResults(\n candidates.map((item) => ({ ...item, score: undefined })),\n op.offset ?? 0,\n op.limit ?? 10\n );\n }\n }\n } else {\n // No embeddings - just paginate the filtered results\n for (const [i, [op, candidates]] of searchOps.entries()) {\n results[i] = this.paginateResults(\n candidates.map((item) => ({ ...item, score: undefined })),\n op.offset ?? 0,\n op.limit ?? 10\n );\n }\n }\n }\n\n // Handle put operations with embeddings\n if (putOps.size > 0 && this._indexConfig?.embeddings) {\n const toEmbed = this.extractTexts(Array.from(putOps.values()));\n if (Object.keys(toEmbed).length > 0) {\n const embeddings = await this._indexConfig.embeddings.embedDocuments(\n Object.keys(toEmbed)\n );\n this.insertVectors(toEmbed, embeddings);\n }\n }\n\n // Apply all put operations\n for (const op of putOps.values()) {\n this.putOperation(op);\n }\n\n return results as OperationResults<Op>;\n }\n\n private getOperation(op: GetOperation): Item | null {\n const namespaceKey = op.namespace.join(\":\");\n const item = this.data.get(namespaceKey)?.get(op.key);\n return item ?? null;\n }\n\n private putOperation(op: PutOperation): void {\n const namespaceKey = op.namespace.join(\":\");\n if (!this.data.has(namespaceKey)) {\n this.data.set(namespaceKey, new Map());\n }\n const namespaceMap = this.data.get(namespaceKey)!;\n\n if (op.value === null) {\n namespaceMap.delete(op.key);\n } else {\n const now = new Date();\n if (namespaceMap.has(op.key)) {\n const item = namespaceMap.get(op.key)!;\n item.value = op.value;\n item.updatedAt = now;\n } else {\n namespaceMap.set(op.key, {\n value: op.value,\n key: op.key,\n namespace: op.namespace,\n createdAt: now,\n updatedAt: now,\n });\n }\n }\n }\n\n private listNamespacesOperation(op: ListNamespacesOperation): string[][] {\n const allNamespaces = Array.from(this.data.keys()).map((ns) =>\n ns.split(\":\")\n );\n let namespaces = allNamespaces;\n\n if (op.matchConditions && op.matchConditions.length > 0) {\n namespaces = namespaces.filter((ns) =>\n op.matchConditions!.every((condition) => this.doesMatch(condition, ns))\n );\n }\n\n if (op.maxDepth !== undefined) {\n namespaces = Array.from(\n new Set(namespaces.map((ns) => ns.slice(0, op.maxDepth).join(\":\")))\n ).map((ns) => ns.split(\":\"));\n }\n\n namespaces.sort((a, b) => a.join(\":\").localeCompare(b.join(\":\")));\n\n return namespaces.slice(\n op.offset ?? 0,\n (op.offset ?? 0) + (op.limit ?? namespaces.length)\n );\n }\n\n private doesMatch(matchCondition: MatchCondition, key: string[]): boolean {\n const { matchType, path } = matchCondition;\n\n if (matchType === \"prefix\") {\n if (path.length > key.length) return false;\n return path.every((pElem, index) => {\n const kElem = key[index];\n return pElem === \"*\" || kElem === pElem;\n });\n } else if (matchType === \"suffix\") {\n if (path.length > key.length) return false;\n return path.every((pElem, index) => {\n const kElem = key[key.length - path.length + index];\n return pElem === \"*\" || kElem === pElem;\n });\n }\n\n throw new Error(`Unsupported match type: ${matchType}`);\n }\n\n private filterItems(op: SearchOperation): Item[] {\n const candidates: Item[] = [];\n for (const [namespace, items] of this.data.entries()) {\n if (namespace.startsWith(op.namespacePrefix.join(\":\"))) {\n candidates.push(...items.values());\n }\n }\n\n let filteredCandidates = candidates;\n if (op.filter) {\n filteredCandidates = candidates.filter((item) =>\n Object.entries(op.filter!).every(([key, value]) =>\n compareValues(item.value[key], value)\n )\n );\n }\n return filteredCandidates;\n }\n\n private scoreResults(\n candidates: Item[],\n queryVector: number[],\n offset: number = 0,\n limit: number = 10\n ): SearchItem[] {\n const flatItems: Item[] = [];\n const flatVectors: number[][] = [];\n const scoreless: Item[] = [];\n\n for (const item of candidates) {\n const vectors = this.getVectors(item);\n if (vectors.length) {\n for (const vector of vectors) {\n flatItems.push(item);\n flatVectors.push(vector);\n }\n } else {\n scoreless.push(item);\n }\n }\n\n const scores = this.cosineSimilarity(queryVector, flatVectors);\n\n const sortedResults = scores\n .map((score, i) => [score, flatItems[i]] as [number, Item])\n .sort((a, b) => b[0] - a[0]);\n\n const seen = new Set<string>();\n const kept: Array<[number | undefined, Item]> = [];\n\n for (const [score, item] of sortedResults) {\n const key = `${item.namespace.join(\":\")}:${item.key}`;\n if (seen.has(key)) continue;\n\n const ix = seen.size;\n if (ix >= offset + limit) break;\n if (ix < offset) {\n seen.add(key);\n continue;\n }\n\n seen.add(key);\n kept.push([score, item]);\n }\n\n if (scoreless.length && kept.length < limit) {\n for (const item of scoreless.slice(0, limit - kept.length)) {\n const key = `${item.namespace.join(\":\")}:${item.key}`;\n if (!seen.has(key)) {\n seen.add(key);\n kept.push([undefined, item]);\n }\n }\n }\n return kept.map(([score, item]) => ({\n ...item,\n score,\n }));\n }\n\n private paginateResults(\n results: SearchItem[],\n offset: number,\n limit: number\n ): SearchItem[] {\n return results.slice(offset, offset + limit);\n }\n\n private extractTexts(ops: PutOperation[]): {\n [text: string]: [string[], string, string][];\n } {\n if (!ops.length || !this._indexConfig) {\n return {};\n }\n\n const toEmbed: { [text: string]: [string[], string, string][] } = {};\n\n for (const op of ops) {\n if (op.value !== null && op.index !== false) {\n const paths =\n op.index === null || op.index === undefined\n ? this._indexConfig.__tokenizedFields ?? []\n : op.index.map(\n (ix) => [ix, tokenizePath(ix)] as [string, string[]]\n );\n for (const [path, field] of paths) {\n const texts = getTextAtPath(op.value, field);\n if (texts.length) {\n if (texts.length > 1) {\n texts.forEach((text, i) => {\n if (!toEmbed[text]) toEmbed[text] = [];\n toEmbed[text].push([op.namespace, op.key, `${path}.${i}`]);\n });\n } else {\n if (!toEmbed[texts[0]]) toEmbed[texts[0]] = [];\n toEmbed[texts[0]].push([op.namespace, op.key, path]);\n }\n }\n }\n }\n }\n\n return toEmbed;\n }\n\n private insertVectors(\n texts: { [text: string]: [string[], string, string][] },\n embeddings: number[][]\n ): void {\n for (const [text, metadata] of Object.entries(texts)) {\n const embedding = embeddings.shift();\n if (!embedding) {\n throw new Error(`No embedding found for text: ${text}`);\n }\n\n for (const [namespace, key, field] of metadata) {\n const namespaceKey = namespace.join(\":\");\n if (!this.vectors.has(namespaceKey)) {\n this.vectors.set(namespaceKey, new Map());\n }\n const namespaceMap = this.vectors.get(namespaceKey)!;\n if (!namespaceMap.has(key)) {\n namespaceMap.set(key, new Map());\n }\n const itemMap = namespaceMap.get(key)!;\n itemMap.set(field, embedding);\n }\n }\n }\n\n private getVectors(item: Item): number[][] {\n const namespaceKey = item.namespace.join(\":\");\n const itemKey = item.key;\n if (!this.vectors.has(namespaceKey)) {\n return [];\n }\n const namespaceMap = this.vectors.get(namespaceKey)!;\n if (!namespaceMap.has(itemKey)) {\n return [];\n }\n const itemMap = namespaceMap.get(itemKey)!;\n const vectors = Array.from(itemMap.values());\n if (!vectors.length) {\n return [];\n }\n return vectors;\n }\n\n private cosineSimilarity(X: number[], Y: number[][]): number[] {\n if (!Y.length) return [];\n\n // Calculate dot products for all vectors at once\n const dotProducts = Y.map((vector) =>\n vector.reduce((acc, val, i) => acc + val * X[i], 0)\n );\n\n // Calculate magnitudes\n const magnitude1 = Math.sqrt(X.reduce((acc, val) => acc + val * val, 0));\n const magnitudes2 = Y.map((vector) =>\n Math.sqrt(vector.reduce((acc, val) => acc + val * val, 0))\n );\n\n // Calculate similarities\n return dotProducts.map((dot, i) => {\n const magnitude2 = magnitudes2[i];\n return magnitude1 && magnitude2 ? dot / (magnitude1 * magnitude2) : 0;\n });\n }\n\n public get indexConfig(): IndexConfig | undefined {\n return this._indexConfig;\n }\n}\n\n/** @deprecated Alias for InMemoryStore */\nexport class MemoryStore extends InMemoryStore {}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,IAAa,gBAAb,cAAmC,UAAU;CAC3C,uBAA+C,IAAI,KAAK;CAGxD,0BAAmE,IAAI,KAAK;CAE5E;CAIA,YAAY,SAAmC;AAC7C,SAAO;AACP,MAAI,SAAS,MACX,MAAK,eAAe;GAClB,GAAG,QAAQ;GACX,oBAAoB,QAAQ,MAAM,UAAU,CAAC,IAAI,EAAE,KAAK,MAAM,CAC5D,GACA,MAAM,MAAM,CAAC,EAAE,GAAG,aAAa,EAAE,CAClC,CAAC;GACH;;CAIL,MAAM,MACJ,YAC+B;EAC/B,MAAM,UAAU,EAAE;EAClB,MAAM,yBAAS,IAAI,KAA2B;EAC9C,MAAM,4BAAY,IAAI,KAAwC;AAG9D,OAAK,IAAI,IAAI,GAAG,IAAI,WAAW,QAAQ,KAAK,GAAG;GAC7C,MAAM,KAAK,WAAW;AACtB,OAAI,SAAS,MAAM,eAAe,MAAM,EAAE,WAAW,IAEnD,SAAQ,KAAK,KAAK,aAAa,GAAG,CAAC;YAC1B,qBAAqB,IAAI;IAElC,MAAM,aAAa,KAAK,YAAY,GAAG;AACvC,cAAU,IAAI,GAAG,CAAC,IAAI,WAAW,CAAC;AAClC,YAAQ,KAAK,KAAK;cACT,WAAW,IAAI;IAExB,MAAM,MAAM,GAAG,GAAG,UAAU,KAAK,IAAI,CAAC,GAAG,GAAG;AAC5C,WAAO,IAAI,KA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;;;CAKnC,WAAmB,MAAwB;EACzC,MAAM,eAAe,KAAK,UAAU,KAAK,IAAI;EAC7C,MAAM,UAAU,KAAK;AACrB,MAAI,CAAC,KAAK,QAAQ,IAAI,aAAa,CACjC,QAAO,EAAE;EAEX,MAAM,eAAe,KAAK,QAAQ,IAAI,aAAa;AACnD,MAAI,CAAC,aAAa,IAAI,QAAQ,CAC5B,QAAO,EAAE;EAEX,MAAM,UAAU,aAAa,IAAI,QAAQ;EACzC,MAAM,UAAU,MAAM,KAAK,QAAQ,QAAQ,CAAC;AAC5C,MAAI,CAAC,QAAQ,OACX,QAAO,EAAE;AAEX,SAAO;;CAGT,iBAAyB,GAAa,GAAyB;AAC7D,MAAI,CAAC,EAAE,OAAQ,QAAO,EAAE;EAGxB,MAAM,cAAc,EAAE,KAAK,WACzB,OAAO,QAAQ,KAAK,KAAK,MAAM,MAAM,MAAM,EAAE,IAAI,EAAE,CACpD;EAGD,MAAM,aAAa,KAAK,KAAK,EAAE,QAAQ,KAAK,QAAQ,MAAM,MAAM,KAAK,EAAE,CAAC;EACxE,MAAM,cAAc,EAAE,KAAK,WACzB,KAAK,KAAK,OAAO,QAAQ,KAAK,QAAQ,MAAM,MAAM,KAAK,EAAE,CAAC,CAC3D;AAGD,SAAO,YAAY,KAAK,KAAK,MAAM;GACjC,MAAM,aAAa,YAAY;AAC/B,UAAO,cAAc,aAAa,OAAO,aAAa,cAAc;IACpE;;CAGJ,IAAW,cAAuC;AAChD,SAAO,KAAK;;;;AAKhB,IAAa,cAAb,cAAiC,cAAc"}

@@ -1,2 +0,1 @@

//#region src/store/utils.ts

@@ -69,19 +68,16 @@ /**

function compareValues(itemValue, filterValue) {
if (isFilterOperators(filterValue)) {
const operators = Object.keys(filterValue).filter((k) => k.startsWith("$"));
return operators.every((op) => {
const value = filterValue[op];
switch (op) {
case "$eq": return itemValue === value;
case "$ne": return itemValue !== value;
case "$gt": return Number(itemValue) > Number(value);
case "$gte": return Number(itemValue) >= Number(value);
case "$lt": return Number(itemValue) < Number(value);
case "$lte": return Number(itemValue) <= Number(value);
case "$in": return Array.isArray(value) ? value.includes(itemValue) : false;
case "$nin": return Array.isArray(value) ? !value.includes(itemValue) : true;
default: return false;
}
});
}
if (isFilterOperators(filterValue)) return Object.keys(filterValue).filter((k) => k.startsWith("$")).every((op) => {
const value = filterValue[op];
switch (op) {
case "$eq": return itemValue === value;
case "$ne": return itemValue !== value;
case "$gt": return Number(itemValue) > Number(value);
case "$gte": return Number(itemValue) >= Number(value);
case "$lt": return Number(itemValue) < Number(value);
case "$lte": return Number(itemValue) <= Number(value);
case "$in": return Array.isArray(value) ? value.includes(itemValue) : false;
case "$nin": return Array.isArray(value) ? !value.includes(itemValue) : true;
default: return false;
}
});
return itemValue === filterValue;

@@ -102,20 +98,20 @@ }

const tokens = Array.isArray(path) ? path : tokenizePath(path);
function extractFromObj(obj$1, tokens$1, pos) {
if (pos >= tokens$1.length) {
if (typeof obj$1 === "string" || typeof obj$1 === "number" || typeof obj$1 === "boolean") return [String(obj$1)];
if (obj$1 === null || obj$1 === void 0) return [];
if (Array.isArray(obj$1) || typeof obj$1 === "object") return [JSON.stringify(obj$1, null, 2)];
function extractFromObj(obj, tokens, pos) {
if (pos >= tokens.length) {
if (typeof obj === "string" || typeof obj === "number" || typeof obj === "boolean") return [String(obj)];
if (obj === null || obj === void 0) return [];
if (Array.isArray(obj) || typeof obj === "object") return [JSON.stringify(obj, null, 2)];
return [];
}
const token = tokens$1[pos];
const token = tokens[pos];
const results = [];
if (pos === 0 && token === "$") results.push(JSON.stringify(obj$1, null, 2));
if (pos === 0 && token === "$") results.push(JSON.stringify(obj, null, 2));
if (token.startsWith("[") && token.endsWith("]")) {
if (!Array.isArray(obj$1)) return [];
if (!Array.isArray(obj)) return [];
const index = token.slice(1, -1);
if (index === "*") for (const item of obj$1) results.push(...extractFromObj(item, tokens$1, pos + 1));
if (index === "*") for (const item of obj) results.push(...extractFromObj(item, tokens, pos + 1));
else try {
let idx = parseInt(index, 10);
if (idx < 0) idx = obj$1.length + idx;
if (idx >= 0 && idx < obj$1.length) results.push(...extractFromObj(obj$1[idx], tokens$1, pos + 1));
if (idx < 0) idx = obj.length + idx;
if (idx >= 0 && idx < obj.length) results.push(...extractFromObj(obj[idx], tokens, pos + 1));
} catch {

@@ -125,3 +121,3 @@ return [];

} else if (token.startsWith("{") && token.endsWith("}")) {
if (typeof obj$1 !== "object" || obj$1 === null) return [];
if (typeof obj !== "object" || obj === null) return [];
const fields = token.slice(1, -1).split(",").map((f) => f.trim());

@@ -131,3 +127,3 @@ for (const field of fields) {

if (nestedTokens.length) {
let currentObj = obj$1;
let currentObj = obj;
for (const nestedToken of nestedTokens) if (currentObj && typeof currentObj === "object" && nestedToken in currentObj) currentObj = currentObj[nestedToken];

@@ -145,5 +141,5 @@ else {

} else if (token === "*") {
if (Array.isArray(obj$1)) for (const item of obj$1) results.push(...extractFromObj(item, tokens$1, pos + 1));
else if (typeof obj$1 === "object" && obj$1 !== null) for (const value of Object.values(obj$1)) results.push(...extractFromObj(value, tokens$1, pos + 1));
} else if (typeof obj$1 === "object" && obj$1 !== null && token in obj$1) results.push(...extractFromObj(obj$1[token], tokens$1, pos + 1));
if (Array.isArray(obj)) for (const item of obj) results.push(...extractFromObj(item, tokens, pos + 1));
else if (typeof obj === "object" && obj !== null) for (const value of Object.values(obj)) results.push(...extractFromObj(value, tokens, pos + 1));
} else if (typeof obj === "object" && obj !== null && token in obj) results.push(...extractFromObj(obj[token], tokens, pos + 1));
return results;

@@ -153,3 +149,2 @@ }

}
//#endregion

@@ -159,2 +154,3 @@ exports.compareValues = compareValues;

exports.tokenizePath = tokenizePath;
//# sourceMappingURL=utils.cjs.map

@@ -1,1 +0,1 @@

{"version":3,"file":"utils.cjs","names":["tokens: string[]","current: string[]","tokens","obj","results: string[]"],"sources":["../../src/store/utils.ts"],"sourcesContent":["/**\n * Tokenize a JSON path into parts.\n * @example\n * tokenizePath(\"metadata.title\") // -> [\"metadata\", \"title\"]\n * tokenizePath(\"chapters[*].content\") // -> [\"chapters[*]\", \"content\"]\n */\nexport function tokenizePath(path: string): string[] {\n if (!path) {\n return [];\n }\n\n const tokens: string[] = [];\n let current: string[] = [];\n let i = 0;\n\n while (i < path.length) {\n const char = path[i];\n\n if (char === \"[\") {\n // Handle array index\n if (current.length) {\n tokens.push(current.join(\"\"));\n current = [];\n }\n let bracketCount = 1;\n const indexChars = [\"[\"];\n i += 1;\n while (i < path.length && bracketCount > 0) {\n if (path[i] === \"[\") {\n bracketCount += 1;\n } else if (path[i] === \"]\") {\n bracketCount -= 1;\n }\n indexChars.push(path[i]);\n i += 1;\n }\n tokens.push(indexChars.join(\"\"));\n continue;\n } else if (char === \"{\") {\n // Handle multi-field selection\n if (current.length) {\n tokens.push(current.join(\"\"));\n current = [];\n }\n let braceCount = 1;\n const fieldChars = [\"{\"];\n i += 1;\n while (i < path.length && braceCount > 0) {\n if (path[i] === \"{\") {\n braceCount += 1;\n } else if (path[i] === \"}\") {\n braceCount -= 1;\n }\n fieldChars.push(path[i]);\n i += 1;\n }\n tokens.push(fieldChars.join(\"\"));\n continue;\n } else if (char === \".\") {\n // Handle regular field\n if (current.length) {\n tokens.push(current.join(\"\"));\n current = [];\n }\n } else {\n current.push(char);\n }\n i += 1;\n }\n\n if (current.length) {\n tokens.push(current.join(\"\"));\n }\n\n return tokens;\n}\n\n/**\n * Represents the supported filter operators\n */\ntype FilterOperators = {\n $eq?: unknown;\n $ne?: unknown;\n $gt?: unknown;\n $gte?: unknown;\n $lt?: unknown;\n $lte?: unknown;\n $in?: unknown[];\n $nin?: unknown[];\n};\n\n/**\n * Type guard to check if an object is a FilterOperators\n */\nfunction isFilterOperators(obj: unknown): obj is FilterOperators {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n Object.keys(obj).every(\n (key) =>\n key === \"$eq\" ||\n key === \"$ne\" ||\n key === \"$gt\" ||\n key === \"$gte\" ||\n key === \"$lt\" ||\n key === \"$lte\" ||\n key === \"$in\" ||\n key === \"$nin\"\n )\n );\n}\n\n/**\n * Compare values for filtering, supporting operator-based comparisons.\n */\nexport function compareValues(\n itemValue: unknown,\n filterValue: unknown\n): boolean {\n if (isFilterOperators(filterValue)) {\n const operators = Object.keys(filterValue).filter((k) => k.startsWith(\"$\"));\n return operators.every((op) => {\n const value = filterValue[op as keyof FilterOperators];\n switch (op) {\n case \"$eq\":\n return itemValue === value;\n case \"$ne\":\n return itemValue !== value;\n case \"$gt\":\n return Number(itemValue) > Number(value);\n case \"$gte\":\n return Number(itemValue) >= Number(value);\n case \"$lt\":\n return Number(itemValue) < Number(value);\n case \"$lte\":\n return Number(itemValue) <= Number(value);\n case \"$in\":\n return Array.isArray(value) ? value.includes(itemValue) : false;\n case \"$nin\":\n return Array.isArray(value) ? !value.includes(itemValue) : true;\n default:\n return false;\n }\n });\n }\n\n // If no operators, do a direct comparison\n return itemValue === filterValue;\n}\n\n/**\n * Extract text from a value at a specific JSON path.\n *\n * Supports:\n * - Simple paths: \"field1.field2\"\n * - Array indexing: \"[0]\", \"[*]\", \"[-1]\"\n * - Wildcards: \"*\"\n * - Multi-field selection: \"{field1,field2}\"\n * - Nested paths in multi-field: \"{field1,nested.field2}\"\n */\nexport function getTextAtPath(obj: unknown, path: string[] | string): string[] {\n if (!path || path === \"$\") {\n return [JSON.stringify(obj, null, 2)];\n }\n const tokens = Array.isArray(path) ? path : tokenizePath(path);\n\n function extractFromObj(\n obj: unknown,\n tokens: string[],\n pos: number\n ): string[] {\n if (pos >= tokens.length) {\n if (\n typeof obj === \"string\" ||\n typeof obj === \"number\" ||\n typeof obj === \"boolean\"\n ) {\n return [String(obj)];\n }\n if (obj === null || obj === undefined) {\n return [];\n }\n if (Array.isArray(obj) || typeof obj === \"object\") {\n return [JSON.stringify(obj, null, 2)];\n }\n return [];\n }\n\n const token = tokens[pos];\n const results: string[] = [];\n if (pos === 0 && token === \"$\") {\n results.push(JSON.stringify(obj, null, 2));\n }\n\n if (token.startsWith(\"[\") && token.endsWith(\"]\")) {\n if (!Array.isArray(obj)) return [];\n\n const index = token.slice(1, -1);\n if (index === \"*\") {\n for (const item of obj) {\n results.push(...extractFromObj(item, tokens, pos + 1));\n }\n } else {\n try {\n let idx = parseInt(index, 10);\n if (idx < 0) {\n idx = obj.length + idx;\n }\n if (idx >= 0 && idx < obj.length) {\n results.push(...extractFromObj(obj[idx], tokens, pos + 1));\n }\n } catch {\n return [];\n }\n }\n } else if (token.startsWith(\"{\") && token.endsWith(\"}\")) {\n if (typeof obj !== \"object\" || obj === null) return [];\n\n const fields = token\n .slice(1, -1)\n .split(\",\")\n .map((f) => f.trim());\n for (const field of fields) {\n const nestedTokens = tokenizePath(field);\n if (nestedTokens.length) {\n let currentObj = obj as Record<string, unknown> | undefined;\n for (const nestedToken of nestedTokens) {\n if (\n currentObj &&\n typeof currentObj === \"object\" &&\n nestedToken in currentObj\n ) {\n currentObj = currentObj[nestedToken] as Record<string, unknown>;\n } else {\n currentObj = undefined;\n break;\n }\n }\n if (currentObj !== undefined) {\n if (\n typeof currentObj === \"string\" ||\n typeof currentObj === \"number\" ||\n typeof currentObj === \"boolean\"\n ) {\n results.push(String(currentObj));\n } else if (\n Array.isArray(currentObj) ||\n typeof currentObj === \"object\"\n ) {\n results.push(JSON.stringify(currentObj, null, 2));\n }\n }\n }\n }\n } else if (token === \"*\") {\n if (Array.isArray(obj)) {\n for (const item of obj) {\n results.push(...extractFromObj(item, tokens, pos + 1));\n }\n } else if (typeof obj === \"object\" && obj !== null) {\n for (const value of Object.values(obj)) {\n results.push(...extractFromObj(value, tokens, pos + 1));\n }\n }\n } else {\n if (typeof obj === \"object\" && obj !== null && token in obj) {\n results.push(\n ...extractFromObj(\n (obj as Record<string, unknown>)[token],\n tokens,\n pos + 1\n )\n );\n }\n }\n\n return results;\n }\n\n return extractFromObj(obj, tokens, 0);\n}\n\n/**\n * Calculate cosine similarity between two vectors.\n */\nexport function cosineSimilarity(vector1: number[], vector2: number[]): number {\n if (vector1.length !== vector2.length) {\n throw new Error(\"Vectors must have the same length\");\n }\n\n const dotProduct = vector1.reduce((acc, val, i) => acc + val * vector2[i], 0);\n const magnitude1 = Math.sqrt(\n vector1.reduce((acc, val) => acc + val * val, 0)\n );\n const magnitude2 = Math.sqrt(\n vector2.reduce((acc, val) => acc + val * val, 0)\n );\n\n if (magnitude1 === 0 || magnitude2 === 0) return 0;\n return dotProduct / (magnitude1 * magnitude2);\n}\n"],"mappings":";;;;;;;;AAMA,SAAgB,aAAa,MAAwB;AACnD,KAAI,CAAC,KACH,QAAO;CAGT,MAAMA,SAAmB;CACzB,IAAIC,UAAoB;CACxB,IAAI,IAAI;AAER,QAAO,IAAI,KAAK,QAAQ;EACtB,MAAM,OAAO,KAAK;AAElB,MAAI,SAAS,KAAK;AAEhB,OAAI,QAAQ,QAAQ;AAClB,WAAO,KAAK,QAAQ,KAAK;AACzB,cAAU;;GAEZ,IAAI,eAAe;GACnB,MAAM,aAAa,CAAC;AACpB,QAAK;AACL,UAAO,IAAI,KAAK,UAAU,eAAe,GAAG;AAC1C,QAAI,KAAK,OAAO,IACd,iBAAgB;aACP,KAAK,OAAO,IACrB,iBAAgB;AAElB,eAAW,KAAK,KAAK;AACrB,SAAK;;AAEP,UAAO,KAAK,WAAW,KAAK;AAC5B;aACS,SAAS,KAAK;AAEvB,OAAI,QAAQ,QAAQ;AAClB,WAAO,KAAK,QAAQ,KAAK;AACzB,cAAU;;GAEZ,IAAI,aAAa;GACjB,MAAM,aAAa,CAAC;AACpB,QAAK;AACL,UAAO,IAAI,KAAK,UAAU,aAAa,GAAG;AACxC,QAAI,KAAK,OAAO,IACd,eAAc;aACL,KAAK,OAAO,IACrB,eAAc;AAEhB,eAAW,KAAK,KAAK;AACrB,SAAK;;AAEP,UAAO,KAAK,WAAW,KAAK;AAC5B;aACS,SAAS,KAElB;OAAI,QAAQ,QAAQ;AAClB,WAAO,KAAK,QAAQ,KAAK;AACzB,cAAU;;QAGZ,SAAQ,KAAK;AAEf,OAAK;;AAGP,KAA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OAChB,MAAK,MAAM,QAAQA,MACjB,SAAQ,KAAK,GAAG,eAAe,MAAMD,UAAQ,MAAM;YAE5C,OAAOC,UAAQ,YAAYA,UAAQ,KAC5C,MAAK,MAAM,SAAS,OAAO,OAAOA,OAChC,SAAQ,KAAK,GAAG,eAAe,OAAOD,UAAQ,MAAM;aAIpD,OAAOC,UAAQ,YAAYA,UAAQ,QAAQ,SAASA,MACtD,SAAQ,KACN,GAAG,eACAA,MAAgC,QACjCD,UACA,MAAM;AAMd,SAAO;;AAGT,QAAO,eAAe,KAAK,QAAQ"}
{"version":3,"file":"utils.cjs","names":[],"sources":["../../src/store/utils.ts"],"sourcesContent":["/**\n * Tokenize a JSON path into parts.\n * @example\n * tokenizePath(\"metadata.title\") // -> [\"metadata\", \"title\"]\n * tokenizePath(\"chapters[*].content\") // -> [\"chapters[*]\", \"content\"]\n */\nexport function tokenizePath(path: string): string[] {\n if (!path) {\n return [];\n }\n\n const tokens: string[] = [];\n let current: string[] = [];\n let i = 0;\n\n while (i < path.length) {\n const char = path[i];\n\n if (char === \"[\") {\n // Handle array index\n if (current.length) {\n tokens.push(current.join(\"\"));\n current = [];\n }\n let bracketCount = 1;\n const indexChars = [\"[\"];\n i += 1;\n while (i < path.length && bracketCount > 0) {\n if (path[i] === \"[\") {\n bracketCount += 1;\n } else if (path[i] === \"]\") {\n bracketCount -= 1;\n }\n indexChars.push(path[i]);\n i += 1;\n }\n tokens.push(indexChars.join(\"\"));\n continue;\n } else if (char === \"{\") {\n // Handle multi-field selection\n if (current.length) {\n tokens.push(current.join(\"\"));\n current = [];\n }\n let braceCount = 1;\n const fieldChars = [\"{\"];\n i += 1;\n while (i < path.length && braceCount > 0) {\n if (path[i] === \"{\") {\n braceCount += 1;\n } else if (path[i] === \"}\") {\n braceCount -= 1;\n }\n fieldChars.push(path[i]);\n i += 1;\n }\n tokens.push(fieldChars.join(\"\"));\n continue;\n } else if (char === \".\") {\n // Handle regular field\n if (current.length) {\n tokens.push(current.join(\"\"));\n current = [];\n }\n } else {\n current.push(char);\n }\n i += 1;\n }\n\n if (current.length) {\n tokens.push(current.join(\"\"));\n }\n\n return tokens;\n}\n\n/**\n * Represents the supported filter operators\n */\ntype FilterOperators = {\n $eq?: unknown;\n $ne?: unknown;\n $gt?: unknown;\n $gte?: unknown;\n $lt?: unknown;\n $lte?: unknown;\n $in?: unknown[];\n $nin?: unknown[];\n};\n\n/**\n * Type guard to check if an object is a FilterOperators\n */\nfunction isFilterOperators(obj: unknown): obj is FilterOperators {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n Object.keys(obj).every(\n (key) =>\n key === \"$eq\" ||\n key === \"$ne\" ||\n key === \"$gt\" ||\n key === \"$gte\" ||\n key === \"$lt\" ||\n key === \"$lte\" ||\n key === \"$in\" ||\n key === \"$nin\"\n )\n );\n}\n\n/**\n * Compare values for filtering, supporting operator-based comparisons.\n */\nexport function compareValues(\n itemValue: unknown,\n filterValue: unknown\n): boolean {\n if (isFilterOperators(filterValue)) {\n const operators = Object.keys(filterValue).filter((k) => k.startsWith(\"$\"));\n return operators.every((op) => {\n const value = filterValue[op as keyof FilterOperators];\n switch (op) {\n case \"$eq\":\n return itemValue === value;\n case \"$ne\":\n return itemValue !== value;\n case \"$gt\":\n return Number(itemValue) > Number(value);\n case \"$gte\":\n return Number(itemValue) >= Number(value);\n case \"$lt\":\n return Number(itemValue) < Number(value);\n case \"$lte\":\n return Number(itemValue) <= Number(value);\n case \"$in\":\n return Array.isArray(value) ? value.includes(itemValue) : false;\n case \"$nin\":\n return Array.isArray(value) ? !value.includes(itemValue) : true;\n default:\n return false;\n }\n });\n }\n\n // If no operators, do a direct comparison\n return itemValue === filterValue;\n}\n\n/**\n * Extract text from a value at a specific JSON path.\n *\n * Supports:\n * - Simple paths: \"field1.field2\"\n * - Array indexing: \"[0]\", \"[*]\", \"[-1]\"\n * - Wildcards: \"*\"\n * - Multi-field selection: \"{field1,field2}\"\n * - Nested paths in multi-field: \"{field1,nested.field2}\"\n */\nexport function getTextAtPath(obj: unknown, path: string[] | string): string[] {\n if (!path || path === \"$\") {\n return [JSON.stringify(obj, null, 2)];\n }\n const tokens = Array.isArray(path) ? path : tokenizePath(path);\n\n function extractFromObj(\n obj: unknown,\n tokens: string[],\n pos: number\n ): string[] {\n if (pos >= tokens.length) {\n if (\n typeof obj === \"string\" ||\n typeof obj === \"number\" ||\n typeof obj === \"boolean\"\n ) {\n return [String(obj)];\n }\n if (obj === null || obj === undefined) {\n return [];\n }\n if (Array.isArray(obj) || typeof obj === \"object\") {\n return [JSON.stringify(obj, null, 2)];\n }\n return [];\n }\n\n const token = tokens[pos];\n const results: string[] = [];\n if (pos === 0 && token === \"$\") {\n results.push(JSON.stringify(obj, null, 2));\n }\n\n if (token.startsWith(\"[\") && token.endsWith(\"]\")) {\n if (!Array.isArray(obj)) return [];\n\n const index = token.slice(1, -1);\n if (index === \"*\") {\n for (const item of obj) {\n results.push(...extractFromObj(item, tokens, pos + 1));\n }\n } else {\n try {\n let idx = parseInt(index, 10);\n if (idx < 0) {\n idx = obj.length + idx;\n }\n if (idx >= 0 && idx < obj.length) {\n results.push(...extractFromObj(obj[idx], tokens, pos + 1));\n }\n } catch {\n return [];\n }\n }\n } else if (token.startsWith(\"{\") && token.endsWith(\"}\")) {\n if (typeof obj !== \"object\" || obj === null) return [];\n\n const fields = token\n .slice(1, -1)\n .split(\",\")\n .map((f) => f.trim());\n for (const field of fields) {\n const nestedTokens = tokenizePath(field);\n if (nestedTokens.length) {\n let currentObj = obj as Record<string, unknown> | undefined;\n for (const nestedToken of nestedTokens) {\n if (\n currentObj &&\n typeof currentObj === \"object\" &&\n nestedToken in currentObj\n ) {\n currentObj = currentObj[nestedToken] as Record<string, unknown>;\n } else {\n currentObj = undefined;\n break;\n }\n }\n if (currentObj !== undefined) {\n if (\n typeof currentObj === \"string\" ||\n typeof currentObj === \"number\" ||\n typeof currentObj === \"boolean\"\n ) {\n results.push(String(currentObj));\n } else if (\n Array.isArray(currentObj) ||\n typeof currentObj === \"object\"\n ) {\n results.push(JSON.stringify(currentObj, null, 2));\n }\n }\n }\n }\n } else if (token === \"*\") {\n if (Array.isArray(obj)) {\n for (const item of obj) {\n results.push(...extractFromObj(item, tokens, pos + 1));\n }\n } else if (typeof obj === \"object\" && obj !== null) {\n for (const value of Object.values(obj)) {\n results.push(...extractFromObj(value, tokens, pos + 1));\n }\n }\n } else {\n if (typeof obj === \"object\" && obj !== null && token in obj) {\n results.push(\n ...extractFromObj(\n (obj as Record<string, unknown>)[token],\n tokens,\n pos + 1\n )\n );\n }\n }\n\n return results;\n }\n\n return extractFromObj(obj, tokens, 0);\n}\n\n/**\n * Calculate cosine similarity between two vectors.\n */\nexport function cosineSimilarity(vector1: number[], vector2: number[]): number {\n if (vector1.length !== vector2.length) {\n throw new Error(\"Vectors must have the same length\");\n }\n\n const dotProduct = vector1.reduce((acc, val, i) => acc + val * vector2[i], 0);\n const magnitude1 = Math.sqrt(\n vector1.reduce((acc, val) => acc + val * val, 0)\n );\n const magnitude2 = Math.sqrt(\n vector2.reduce((acc, val) => acc + val * val, 0)\n );\n\n if (magnitude1 === 0 || magnitude2 === 0) return 0;\n return dotProduct / (magnitude1 * magnitude2);\n}\n"],"mappings":";;;;;;;AAMA,SAAgB,aAAa,MAAwB;AACnD,KAAI,CAAC,KACH,QAAO,EAAE;CAGX,MAAM,SAAmB,EAAE;CAC3B,IAAI,UAAoB,EAAE;CAC1B,IAAI,IAAI;AAER,QAAO,IAAI,KAAK,QAAQ;EACtB,MAAM,OAAO,KAAK;AAElB,MAAI,SAAS,KAAK;AAEhB,OAAI,QAAQ,QAAQ;AAClB,WAAO,KAAK,QAAQ,KAAK,GAAG,CAAC;AAC7B,cAAU,EAAE;;GAEd,IAAI,eAAe;GACnB,MAAM,aAAa,CAAC,IAAI;AACxB,QAAK;AACL,UAAO,IAAI,KAAK,UAAU,eAAe,GAAG;AAC1C,QAAI,KAAK,OAAO,IACd,iBAAgB;aACP,KAAK,OAAO,IACrB,iBA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,IAAgC,QACjC,QACA,MAAM,EACP,CACF;AAIL,SAAO;;AAGT,QAAO,eAAe,KAAK,QAAQ,EAAE"}

@@ -68,19 +68,16 @@ //#region src/store/utils.ts

function compareValues(itemValue, filterValue) {
if (isFilterOperators(filterValue)) {
const operators = Object.keys(filterValue).filter((k) => k.startsWith("$"));
return operators.every((op) => {
const value = filterValue[op];
switch (op) {
case "$eq": return itemValue === value;
case "$ne": return itemValue !== value;
case "$gt": return Number(itemValue) > Number(value);
case "$gte": return Number(itemValue) >= Number(value);
case "$lt": return Number(itemValue) < Number(value);
case "$lte": return Number(itemValue) <= Number(value);
case "$in": return Array.isArray(value) ? value.includes(itemValue) : false;
case "$nin": return Array.isArray(value) ? !value.includes(itemValue) : true;
default: return false;
}
});
}
if (isFilterOperators(filterValue)) return Object.keys(filterValue).filter((k) => k.startsWith("$")).every((op) => {
const value = filterValue[op];
switch (op) {
case "$eq": return itemValue === value;
case "$ne": return itemValue !== value;
case "$gt": return Number(itemValue) > Number(value);
case "$gte": return Number(itemValue) >= Number(value);
case "$lt": return Number(itemValue) < Number(value);
case "$lte": return Number(itemValue) <= Number(value);
case "$in": return Array.isArray(value) ? value.includes(itemValue) : false;
case "$nin": return Array.isArray(value) ? !value.includes(itemValue) : true;
default: return false;
}
});
return itemValue === filterValue;

@@ -101,20 +98,20 @@ }

const tokens = Array.isArray(path) ? path : tokenizePath(path);
function extractFromObj(obj$1, tokens$1, pos) {
if (pos >= tokens$1.length) {
if (typeof obj$1 === "string" || typeof obj$1 === "number" || typeof obj$1 === "boolean") return [String(obj$1)];
if (obj$1 === null || obj$1 === void 0) return [];
if (Array.isArray(obj$1) || typeof obj$1 === "object") return [JSON.stringify(obj$1, null, 2)];
function extractFromObj(obj, tokens, pos) {
if (pos >= tokens.length) {
if (typeof obj === "string" || typeof obj === "number" || typeof obj === "boolean") return [String(obj)];
if (obj === null || obj === void 0) return [];
if (Array.isArray(obj) || typeof obj === "object") return [JSON.stringify(obj, null, 2)];
return [];
}
const token = tokens$1[pos];
const token = tokens[pos];
const results = [];
if (pos === 0 && token === "$") results.push(JSON.stringify(obj$1, null, 2));
if (pos === 0 && token === "$") results.push(JSON.stringify(obj, null, 2));
if (token.startsWith("[") && token.endsWith("]")) {
if (!Array.isArray(obj$1)) return [];
if (!Array.isArray(obj)) return [];
const index = token.slice(1, -1);
if (index === "*") for (const item of obj$1) results.push(...extractFromObj(item, tokens$1, pos + 1));
if (index === "*") for (const item of obj) results.push(...extractFromObj(item, tokens, pos + 1));
else try {
let idx = parseInt(index, 10);
if (idx < 0) idx = obj$1.length + idx;
if (idx >= 0 && idx < obj$1.length) results.push(...extractFromObj(obj$1[idx], tokens$1, pos + 1));
if (idx < 0) idx = obj.length + idx;
if (idx >= 0 && idx < obj.length) results.push(...extractFromObj(obj[idx], tokens, pos + 1));
} catch {

@@ -124,3 +121,3 @@ return [];

} else if (token.startsWith("{") && token.endsWith("}")) {
if (typeof obj$1 !== "object" || obj$1 === null) return [];
if (typeof obj !== "object" || obj === null) return [];
const fields = token.slice(1, -1).split(",").map((f) => f.trim());

@@ -130,3 +127,3 @@ for (const field of fields) {

if (nestedTokens.length) {
let currentObj = obj$1;
let currentObj = obj;
for (const nestedToken of nestedTokens) if (currentObj && typeof currentObj === "object" && nestedToken in currentObj) currentObj = currentObj[nestedToken];

@@ -144,5 +141,5 @@ else {

} else if (token === "*") {
if (Array.isArray(obj$1)) for (const item of obj$1) results.push(...extractFromObj(item, tokens$1, pos + 1));
else if (typeof obj$1 === "object" && obj$1 !== null) for (const value of Object.values(obj$1)) results.push(...extractFromObj(value, tokens$1, pos + 1));
} else if (typeof obj$1 === "object" && obj$1 !== null && token in obj$1) results.push(...extractFromObj(obj$1[token], tokens$1, pos + 1));
if (Array.isArray(obj)) for (const item of obj) results.push(...extractFromObj(item, tokens, pos + 1));
else if (typeof obj === "object" && obj !== null) for (const value of Object.values(obj)) results.push(...extractFromObj(value, tokens, pos + 1));
} else if (typeof obj === "object" && obj !== null && token in obj) results.push(...extractFromObj(obj[token], tokens, pos + 1));
return results;

@@ -152,5 +149,5 @@ }

}
//#endregion
export { compareValues, getTextAtPath, tokenizePath };
//# sourceMappingURL=utils.js.map

@@ -1,1 +0,1 @@

{"version":3,"file":"utils.js","names":["tokens: string[]","current: string[]","tokens","obj","results: string[]"],"sources":["../../src/store/utils.ts"],"sourcesContent":["/**\n * Tokenize a JSON path into parts.\n * @example\n * tokenizePath(\"metadata.title\") // -> [\"metadata\", \"title\"]\n * tokenizePath(\"chapters[*].content\") // -> [\"chapters[*]\", \"content\"]\n */\nexport function tokenizePath(path: string): string[] {\n if (!path) {\n return [];\n }\n\n const tokens: string[] = [];\n let current: string[] = [];\n let i = 0;\n\n while (i < path.length) {\n const char = path[i];\n\n if (char === \"[\") {\n // Handle array index\n if (current.length) {\n tokens.push(current.join(\"\"));\n current = [];\n }\n let bracketCount = 1;\n const indexChars = [\"[\"];\n i += 1;\n while (i < path.length && bracketCount > 0) {\n if (path[i] === \"[\") {\n bracketCount += 1;\n } else if (path[i] === \"]\") {\n bracketCount -= 1;\n }\n indexChars.push(path[i]);\n i += 1;\n }\n tokens.push(indexChars.join(\"\"));\n continue;\n } else if (char === \"{\") {\n // Handle multi-field selection\n if (current.length) {\n tokens.push(current.join(\"\"));\n current = [];\n }\n let braceCount = 1;\n const fieldChars = [\"{\"];\n i += 1;\n while (i < path.length && braceCount > 0) {\n if (path[i] === \"{\") {\n braceCount += 1;\n } else if (path[i] === \"}\") {\n braceCount -= 1;\n }\n fieldChars.push(path[i]);\n i += 1;\n }\n tokens.push(fieldChars.join(\"\"));\n continue;\n } else if (char === \".\") {\n // Handle regular field\n if (current.length) {\n tokens.push(current.join(\"\"));\n current = [];\n }\n } else {\n current.push(char);\n }\n i += 1;\n }\n\n if (current.length) {\n tokens.push(current.join(\"\"));\n }\n\n return tokens;\n}\n\n/**\n * Represents the supported filter operators\n */\ntype FilterOperators = {\n $eq?: unknown;\n $ne?: unknown;\n $gt?: unknown;\n $gte?: unknown;\n $lt?: unknown;\n $lte?: unknown;\n $in?: unknown[];\n $nin?: unknown[];\n};\n\n/**\n * Type guard to check if an object is a FilterOperators\n */\nfunction isFilterOperators(obj: unknown): obj is FilterOperators {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n Object.keys(obj).every(\n (key) =>\n key === \"$eq\" ||\n key === \"$ne\" ||\n key === \"$gt\" ||\n key === \"$gte\" ||\n key === \"$lt\" ||\n key === \"$lte\" ||\n key === \"$in\" ||\n key === \"$nin\"\n )\n );\n}\n\n/**\n * Compare values for filtering, supporting operator-based comparisons.\n */\nexport function compareValues(\n itemValue: unknown,\n filterValue: unknown\n): boolean {\n if (isFilterOperators(filterValue)) {\n const operators = Object.keys(filterValue).filter((k) => k.startsWith(\"$\"));\n return operators.every((op) => {\n const value = filterValue[op as keyof FilterOperators];\n switch (op) {\n case \"$eq\":\n return itemValue === value;\n case \"$ne\":\n return itemValue !== value;\n case \"$gt\":\n return Number(itemValue) > Number(value);\n case \"$gte\":\n return Number(itemValue) >= Number(value);\n case \"$lt\":\n return Number(itemValue) < Number(value);\n case \"$lte\":\n return Number(itemValue) <= Number(value);\n case \"$in\":\n return Array.isArray(value) ? value.includes(itemValue) : false;\n case \"$nin\":\n return Array.isArray(value) ? !value.includes(itemValue) : true;\n default:\n return false;\n }\n });\n }\n\n // If no operators, do a direct comparison\n return itemValue === filterValue;\n}\n\n/**\n * Extract text from a value at a specific JSON path.\n *\n * Supports:\n * - Simple paths: \"field1.field2\"\n * - Array indexing: \"[0]\", \"[*]\", \"[-1]\"\n * - Wildcards: \"*\"\n * - Multi-field selection: \"{field1,field2}\"\n * - Nested paths in multi-field: \"{field1,nested.field2}\"\n */\nexport function getTextAtPath(obj: unknown, path: string[] | string): string[] {\n if (!path || path === \"$\") {\n return [JSON.stringify(obj, null, 2)];\n }\n const tokens = Array.isArray(path) ? path : tokenizePath(path);\n\n function extractFromObj(\n obj: unknown,\n tokens: string[],\n pos: number\n ): string[] {\n if (pos >= tokens.length) {\n if (\n typeof obj === \"string\" ||\n typeof obj === \"number\" ||\n typeof obj === \"boolean\"\n ) {\n return [String(obj)];\n }\n if (obj === null || obj === undefined) {\n return [];\n }\n if (Array.isArray(obj) || typeof obj === \"object\") {\n return [JSON.stringify(obj, null, 2)];\n }\n return [];\n }\n\n const token = tokens[pos];\n const results: string[] = [];\n if (pos === 0 && token === \"$\") {\n results.push(JSON.stringify(obj, null, 2));\n }\n\n if (token.startsWith(\"[\") && token.endsWith(\"]\")) {\n if (!Array.isArray(obj)) return [];\n\n const index = token.slice(1, -1);\n if (index === \"*\") {\n for (const item of obj) {\n results.push(...extractFromObj(item, tokens, pos + 1));\n }\n } else {\n try {\n let idx = parseInt(index, 10);\n if (idx < 0) {\n idx = obj.length + idx;\n }\n if (idx >= 0 && idx < obj.length) {\n results.push(...extractFromObj(obj[idx], tokens, pos + 1));\n }\n } catch {\n return [];\n }\n }\n } else if (token.startsWith(\"{\") && token.endsWith(\"}\")) {\n if (typeof obj !== \"object\" || obj === null) return [];\n\n const fields = token\n .slice(1, -1)\n .split(\",\")\n .map((f) => f.trim());\n for (const field of fields) {\n const nestedTokens = tokenizePath(field);\n if (nestedTokens.length) {\n let currentObj = obj as Record<string, unknown> | undefined;\n for (const nestedToken of nestedTokens) {\n if (\n currentObj &&\n typeof currentObj === \"object\" &&\n nestedToken in currentObj\n ) {\n currentObj = currentObj[nestedToken] as Record<string, unknown>;\n } else {\n currentObj = undefined;\n break;\n }\n }\n if (currentObj !== undefined) {\n if (\n typeof currentObj === \"string\" ||\n typeof currentObj === \"number\" ||\n typeof currentObj === \"boolean\"\n ) {\n results.push(String(currentObj));\n } else if (\n Array.isArray(currentObj) ||\n typeof currentObj === \"object\"\n ) {\n results.push(JSON.stringify(currentObj, null, 2));\n }\n }\n }\n }\n } else if (token === \"*\") {\n if (Array.isArray(obj)) {\n for (const item of obj) {\n results.push(...extractFromObj(item, tokens, pos + 1));\n }\n } else if (typeof obj === \"object\" && obj !== null) {\n for (const value of Object.values(obj)) {\n results.push(...extractFromObj(value, tokens, pos + 1));\n }\n }\n } else {\n if (typeof obj === \"object\" && obj !== null && token in obj) {\n results.push(\n ...extractFromObj(\n (obj as Record<string, unknown>)[token],\n tokens,\n pos + 1\n )\n );\n }\n }\n\n return results;\n }\n\n return extractFromObj(obj, tokens, 0);\n}\n\n/**\n * Calculate cosine similarity between two vectors.\n */\nexport function cosineSimilarity(vector1: number[], vector2: number[]): number {\n if (vector1.length !== vector2.length) {\n throw new Error(\"Vectors must have the same length\");\n }\n\n const dotProduct = vector1.reduce((acc, val, i) => acc + val * vector2[i], 0);\n const magnitude1 = Math.sqrt(\n vector1.reduce((acc, val) => acc + val * val, 0)\n );\n const magnitude2 = Math.sqrt(\n vector2.reduce((acc, val) => acc + val * val, 0)\n );\n\n if (magnitude1 === 0 || magnitude2 === 0) return 0;\n return dotProduct / (magnitude1 * magnitude2);\n}\n"],"mappings":";;;;;;;AAMA,SAAgB,aAAa,MAAwB;AACnD,KAAI,CAAC,KACH,QAAO;CAGT,MAAMA,SAAmB;CACzB,IAAIC,UAAoB;CACxB,IAAI,IAAI;AAER,QAAO,IAAI,KAAK,QAAQ;EACtB,MAAM,OAAO,KAAK;AAElB,MAAI,SAAS,KAAK;AAEhB,OAAI,QAAQ,QAAQ;AAClB,WAAO,KAAK,QAAQ,KAAK;AACzB,cAAU;;GAEZ,IAAI,eAAe;GACnB,MAAM,aAAa,CAAC;AACpB,QAAK;AACL,UAAO,IAAI,KAAK,UAAU,eAAe,GAAG;AAC1C,QAAI,KAAK,OAAO,IACd,iBAAgB;aACP,KAAK,OAAO,IACrB,iBAAgB;AAElB,eAAW,KAAK,KAAK;AACrB,SAAK;;AAEP,UAAO,KAAK,WAAW,KAAK;AAC5B;aACS,SAAS,KAAK;AAEvB,OAAI,QAAQ,QAAQ;AAClB,WAAO,KAAK,QAAQ,KAAK;AACzB,cAAU;;GAEZ,IAAI,aAAa;GACjB,MAAM,aAAa,CAAC;AACpB,QAAK;AACL,U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cACA,OAAO,eAAe,YACtB,eAAe,WAEf,cAAa,WAAW;UACnB;AACL,mBAAa;AACb;;AAGJ,SAAI,eAAe,QACjB;UACE,OAAO,eAAe,YACtB,OAAO,eAAe,YACtB,OAAO,eAAe,UAEtB,SAAQ,KAAK,OAAO;eAEpB,MAAM,QAAQ,eACd,OAAO,eAAe,SAEtB,SAAQ,KAAK,KAAK,UAAU,YAAY,MAAM;;;;aAK7C,UAAU,KACnB;OAAI,MAAM,QAAQA,OAChB,MAAK,MAAM,QAAQA,MACjB,SAAQ,KAAK,GAAG,eAAe,MAAMD,UAAQ,MAAM;YAE5C,OAAOC,UAAQ,YAAYA,UAAQ,KAC5C,MAAK,MAAM,SAAS,OAAO,OAAOA,OAChC,SAAQ,KAAK,GAAG,eAAe,OAAOD,UAAQ,MAAM;aAIpD,OAAOC,UAAQ,YAAYA,UAAQ,QAAQ,SAASA,MACtD,SAAQ,KACN,GAAG,eACAA,MAAgC,QACjCD,UACA,MAAM;AAMd,SAAO;;AAGT,QAAO,eAAe,KAAK,QAAQ"}
{"version":3,"file":"utils.js","names":[],"sources":["../../src/store/utils.ts"],"sourcesContent":["/**\n * Tokenize a JSON path into parts.\n * @example\n * tokenizePath(\"metadata.title\") // -> [\"metadata\", \"title\"]\n * tokenizePath(\"chapters[*].content\") // -> [\"chapters[*]\", \"content\"]\n */\nexport function tokenizePath(path: string): string[] {\n if (!path) {\n return [];\n }\n\n const tokens: string[] = [];\n let current: string[] = [];\n let i = 0;\n\n while (i < path.length) {\n const char = path[i];\n\n if (char === \"[\") {\n // Handle array index\n if (current.length) {\n tokens.push(current.join(\"\"));\n current = [];\n }\n let bracketCount = 1;\n const indexChars = [\"[\"];\n i += 1;\n while (i < path.length && bracketCount > 0) {\n if (path[i] === \"[\") {\n bracketCount += 1;\n } else if (path[i] === \"]\") {\n bracketCount -= 1;\n }\n indexChars.push(path[i]);\n i += 1;\n }\n tokens.push(indexChars.join(\"\"));\n continue;\n } else if (char === \"{\") {\n // Handle multi-field selection\n if (current.length) {\n tokens.push(current.join(\"\"));\n current = [];\n }\n let braceCount = 1;\n const fieldChars = [\"{\"];\n i += 1;\n while (i < path.length && braceCount > 0) {\n if (path[i] === \"{\") {\n braceCount += 1;\n } else if (path[i] === \"}\") {\n braceCount -= 1;\n }\n fieldChars.push(path[i]);\n i += 1;\n }\n tokens.push(fieldChars.join(\"\"));\n continue;\n } else if (char === \".\") {\n // Handle regular field\n if (current.length) {\n tokens.push(current.join(\"\"));\n current = [];\n }\n } else {\n current.push(char);\n }\n i += 1;\n }\n\n if (current.length) {\n tokens.push(current.join(\"\"));\n }\n\n return tokens;\n}\n\n/**\n * Represents the supported filter operators\n */\ntype FilterOperators = {\n $eq?: unknown;\n $ne?: unknown;\n $gt?: unknown;\n $gte?: unknown;\n $lt?: unknown;\n $lte?: unknown;\n $in?: unknown[];\n $nin?: unknown[];\n};\n\n/**\n * Type guard to check if an object is a FilterOperators\n */\nfunction isFilterOperators(obj: unknown): obj is FilterOperators {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n Object.keys(obj).every(\n (key) =>\n key === \"$eq\" ||\n key === \"$ne\" ||\n key === \"$gt\" ||\n key === \"$gte\" ||\n key === \"$lt\" ||\n key === \"$lte\" ||\n key === \"$in\" ||\n key === \"$nin\"\n )\n );\n}\n\n/**\n * Compare values for filtering, supporting operator-based comparisons.\n */\nexport function compareValues(\n itemValue: unknown,\n filterValue: unknown\n): boolean {\n if (isFilterOperators(filterValue)) {\n const operators = Object.keys(filterValue).filter((k) => k.startsWith(\"$\"));\n return operators.every((op) => {\n const value = filterValue[op as keyof FilterOperators];\n switch (op) {\n case \"$eq\":\n return itemValue === value;\n case \"$ne\":\n return itemValue !== value;\n case \"$gt\":\n return Number(itemValue) > Number(value);\n case \"$gte\":\n return Number(itemValue) >= Number(value);\n case \"$lt\":\n return Number(itemValue) < Number(value);\n case \"$lte\":\n return Number(itemValue) <= Number(value);\n case \"$in\":\n return Array.isArray(value) ? value.includes(itemValue) : false;\n case \"$nin\":\n return Array.isArray(value) ? !value.includes(itemValue) : true;\n default:\n return false;\n }\n });\n }\n\n // If no operators, do a direct comparison\n return itemValue === filterValue;\n}\n\n/**\n * Extract text from a value at a specific JSON path.\n *\n * Supports:\n * - Simple paths: \"field1.field2\"\n * - Array indexing: \"[0]\", \"[*]\", \"[-1]\"\n * - Wildcards: \"*\"\n * - Multi-field selection: \"{field1,field2}\"\n * - Nested paths in multi-field: \"{field1,nested.field2}\"\n */\nexport function getTextAtPath(obj: unknown, path: string[] | string): string[] {\n if (!path || path === \"$\") {\n return [JSON.stringify(obj, null, 2)];\n }\n const tokens = Array.isArray(path) ? path : tokenizePath(path);\n\n function extractFromObj(\n obj: unknown,\n tokens: string[],\n pos: number\n ): string[] {\n if (pos >= tokens.length) {\n if (\n typeof obj === \"string\" ||\n typeof obj === \"number\" ||\n typeof obj === \"boolean\"\n ) {\n return [String(obj)];\n }\n if (obj === null || obj === undefined) {\n return [];\n }\n if (Array.isArray(obj) || typeof obj === \"object\") {\n return [JSON.stringify(obj, null, 2)];\n }\n return [];\n }\n\n const token = tokens[pos];\n const results: string[] = [];\n if (pos === 0 && token === \"$\") {\n results.push(JSON.stringify(obj, null, 2));\n }\n\n if (token.startsWith(\"[\") && token.endsWith(\"]\")) {\n if (!Array.isArray(obj)) return [];\n\n const index = token.slice(1, -1);\n if (index === \"*\") {\n for (const item of obj) {\n results.push(...extractFromObj(item, tokens, pos + 1));\n }\n } else {\n try {\n let idx = parseInt(index, 10);\n if (idx < 0) {\n idx = obj.length + idx;\n }\n if (idx >= 0 && idx < obj.length) {\n results.push(...extractFromObj(obj[idx], tokens, pos + 1));\n }\n } catch {\n return [];\n }\n }\n } else if (token.startsWith(\"{\") && token.endsWith(\"}\")) {\n if (typeof obj !== \"object\" || obj === null) return [];\n\n const fields = token\n .slice(1, -1)\n .split(\",\")\n .map((f) => f.trim());\n for (const field of fields) {\n const nestedTokens = tokenizePath(field);\n if (nestedTokens.length) {\n let currentObj = obj as Record<string, unknown> | undefined;\n for (const nestedToken of nestedTokens) {\n if (\n currentObj &&\n typeof currentObj === \"object\" &&\n nestedToken in currentObj\n ) {\n currentObj = currentObj[nestedToken] as Record<string, unknown>;\n } else {\n currentObj = undefined;\n break;\n }\n }\n if (currentObj !== undefined) {\n if (\n typeof currentObj === \"string\" ||\n typeof currentObj === \"number\" ||\n typeof currentObj === \"boolean\"\n ) {\n results.push(String(currentObj));\n } else if (\n Array.isArray(currentObj) ||\n typeof currentObj === \"object\"\n ) {\n results.push(JSON.stringify(currentObj, null, 2));\n }\n }\n }\n }\n } else if (token === \"*\") {\n if (Array.isArray(obj)) {\n for (const item of obj) {\n results.push(...extractFromObj(item, tokens, pos + 1));\n }\n } else if (typeof obj === \"object\" && obj !== null) {\n for (const value of Object.values(obj)) {\n results.push(...extractFromObj(value, tokens, pos + 1));\n }\n }\n } else {\n if (typeof obj === \"object\" && obj !== null && token in obj) {\n results.push(\n ...extractFromObj(\n (obj as Record<string, unknown>)[token],\n tokens,\n pos + 1\n )\n );\n }\n }\n\n return results;\n }\n\n return extractFromObj(obj, tokens, 0);\n}\n\n/**\n * Calculate cosine similarity between two vectors.\n */\nexport function cosineSimilarity(vector1: number[], vector2: number[]): number {\n if (vector1.length !== vector2.length) {\n throw new Error(\"Vectors must have the same length\");\n }\n\n const dotProduct = vector1.reduce((acc, val, i) => acc + val * vector2[i], 0);\n const magnitude1 = Math.sqrt(\n vector1.reduce((acc, val) => acc + val * val, 0)\n );\n const magnitude2 = Math.sqrt(\n vector2.reduce((acc, val) => acc + val * val, 0)\n );\n\n if (magnitude1 === 0 || magnitude2 === 0) return 0;\n return dotProduct / (magnitude1 * magnitude2);\n}\n"],"mappings":";;;;;;;AAMA,SAAgB,aAAa,MAAwB;AACnD,KAAI,CAAC,KACH,QAAO,EAAE;CAGX,MAAM,SAAmB,EAAE;CAC3B,IAAI,UAAoB,EAAE;CAC1B,IAAI,IAAI;AAER,QAAO,IAAI,KAAK,QAAQ;EACtB,MA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,MAAK,MAAM,QAAQ,IACjB,SAAQ,KAAK,GAAG,eAAe,MAAM,QAAQ,MAAM,EAAE,CAAC;YAE/C,OAAO,QAAQ,YAAY,QAAQ,KAC5C,MAAK,MAAM,SAAS,OAAO,OAAO,IAAI,CACpC,SAAQ,KAAK,GAAG,eAAe,OAAO,QAAQ,MAAM,EAAE,CAAC;aAIvD,OAAO,QAAQ,YAAY,QAAQ,QAAQ,SAAS,IACtD,SAAQ,KACN,GAAG,eACA,IAAgC,QACjC,QACA,MAAM,EACP,CACF;AAIL,SAAO;;AAGT,QAAO,eAAe,KAAK,QAAQ,EAAE"}

@@ -1,1 +0,1 @@

{"version":3,"file":"types.d.cts","names":["All","PendingWriteValue","PendingWrite","Channel","CheckpointPendingWrite","TaskId","CheckpointMetadata","Record","ExtraProperties"],"sources":["../src/types.d.ts"],"sourcesContent":["export type All = \"*\";\nexport type PendingWriteValue = unknown;\nexport type PendingWrite<Channel = string> = [Channel, PendingWriteValue];\nexport type CheckpointPendingWrite<TaskId = string> = [\n TaskId,\n ...PendingWrite<string>\n];\n/**\n * Additional details about the checkpoint, including the source, step, writes, and parents.\n *\n * @typeParam ExtraProperties - Optional additional properties to include in the metadata.\n */\nexport type CheckpointMetadata<ExtraProperties extends object = object> = {\n /**\n * The source of the checkpoint.\n * - \"input\": The checkpoint was created from an input to invoke/stream/batch.\n * - \"loop\": The checkpoint was created from inside the pregel loop.\n * - \"update\": The checkpoint was created from a manual state update.\n * - \"fork\": The checkpoint was created as a copy of another checkpoint.\n */\n source: \"input\" | \"loop\" | \"update\" | \"fork\";\n /**\n * The step number of the checkpoint.\n * -1 for the first \"input\" checkpoint.\n * 0 for the first \"loop\" checkpoint.\n * ... for the nth checkpoint afterwards.\n */\n step: number;\n /**\n * The IDs of the parent checkpoints.\n * Mapping from checkpoint namespace to checkpoint ID.\n */\n parents: Record<string, string>;\n} & ExtraProperties;\n"],"mappings":";KAAYA,GAAAA;AAAAA,KACAC,iBAAAA,GADG,OAAA;AACHA,KACAC,YADiB,CAAA,UAAA,MAAA,CAAA,GAAA,CACiBC,OADjB,EAC0BF,iBAD1B,CAAA;AACjBC,KACAE,sBADY,CAAA,SAAA,MAAA,CAAA,GAAA,CAEpBC,MAFoB,KAGjBH,YAHuCC,CAAAA,MAAAA,CAAAA;;AAC9C;;;;KASYG;EAAAA;;;;;;;;;;;;;;;;;;;WAoBCC;IACTC"}
{"version":3,"file":"types.d.cts","names":[],"sources":["../src/types.ts"],"mappings":";KAAY,GAAA;AAAA,KAEA,iBAAA;AAAA,KAEA,YAAA,sBAAkC,OAAA,EAAS,iBAAA;AAAA,KAE3C,sBAAA,qBACV,MAAA,KACG,YAAA;;;;;AAJL;KAYY,kBAAA;EAZY;;;;;;;EAoBtB,MAAA;EAlBgC;;;;;;EA0BhC,IAAA;EAxBe;AAQjB;;;EAsBE,OAAA,EAAS,MAAA;AAAA,IACP,eAAA"}

@@ -1,1 +0,1 @@

{"version":3,"file":"types.d.ts","names":["All","PendingWriteValue","PendingWrite","Channel","CheckpointPendingWrite","TaskId","CheckpointMetadata","Record","ExtraProperties"],"sources":["../src/types.d.ts"],"sourcesContent":["export type All = \"*\";\nexport type PendingWriteValue = unknown;\nexport type PendingWrite<Channel = string> = [Channel, PendingWriteValue];\nexport type CheckpointPendingWrite<TaskId = string> = [\n TaskId,\n ...PendingWrite<string>\n];\n/**\n * Additional details about the checkpoint, including the source, step, writes, and parents.\n *\n * @typeParam ExtraProperties - Optional additional properties to include in the metadata.\n */\nexport type CheckpointMetadata<ExtraProperties extends object = object> = {\n /**\n * The source of the checkpoint.\n * - \"input\": The checkpoint was created from an input to invoke/stream/batch.\n * - \"loop\": The checkpoint was created from inside the pregel loop.\n * - \"update\": The checkpoint was created from a manual state update.\n * - \"fork\": The checkpoint was created as a copy of another checkpoint.\n */\n source: \"input\" | \"loop\" | \"update\" | \"fork\";\n /**\n * The step number of the checkpoint.\n * -1 for the first \"input\" checkpoint.\n * 0 for the first \"loop\" checkpoint.\n * ... for the nth checkpoint afterwards.\n */\n step: number;\n /**\n * The IDs of the parent checkpoints.\n * Mapping from checkpoint namespace to checkpoint ID.\n */\n parents: Record<string, string>;\n} & ExtraProperties;\n"],"mappings":";KAAYA,GAAAA;AAAAA,KACAC,iBAAAA,GADG,OAAA;AACHA,KACAC,YADiB,CAAA,UAAA,MAAA,CAAA,GAAA,CACiBC,OADjB,EAC0BF,iBAD1B,CAAA;AACjBC,KACAE,sBADY,CAAA,SAAA,MAAA,CAAA,GAAA,CAEpBC,MAFoB,KAGjBH,YAHuCC,CAAAA,MAAAA,CAAAA;;AAC9C;;;;KASYG;EAAAA;;;;;;;;;;;;;;;;;;;WAoBCC;IACTC"}
{"version":3,"file":"types.d.ts","names":[],"sources":["../src/types.ts"],"mappings":";KAAY,GAAA;AAAA,KAEA,iBAAA;AAAA,KAEA,YAAA,sBAAkC,OAAA,EAAS,iBAAA;AAAA,KAE3C,sBAAA,qBACV,MAAA,KACG,YAAA;;;;;AAJL;KAYY,kBAAA;EAZY;;;;;;;EAoBtB,MAAA;EAlBgC;;;;;;EA0BhC,IAAA;EAxBe;AAQjB;;;EAsBE,OAAA,EAAS,MAAA;AAAA,IACP,eAAA"}
{
"name": "@langchain/langgraph-checkpoint",
"version": "1.0.0",
"version": "1.0.1",
"description": "Library with base interfaces for LangGraph checkpoint savers.",

@@ -13,19 +13,5 @@ "type": "module",

"type": "git",
"url": "git@github.com:langchain-ai/langgraphjs.git"
"url": "git+ssh://git@github.com/langchain-ai/langgraphjs.git",
"directory": "libs/checkpoint"
},
"scripts": {
"build": "yarn turbo:command build:internal --filter=@langchain/langgraph-checkpoint",
"build:internal": "yarn workspace @langchain/build compile @langchain/langgraph-checkpoint",
"clean": "rm -rf dist/ dist-cjs/ .turbo/",
"lint:eslint": "NODE_OPTIONS=--max-old-space-size=4096 eslint --cache --ext .ts,.js src/",
"lint:dpdm": "dpdm --exit-code circular:1 --no-warning --no-tree src/*.ts src/**/*.ts",
"lint": "yarn lint:eslint && yarn lint:dpdm",
"lint:fix": "yarn lint:eslint --fix && yarn lint:dpdm",
"prepublish": "yarn build",
"test": "vitest run",
"test:watch": "vitest watch",
"test:int": "vitest run --mode int",
"format": "prettier --config .prettierrc --write \"src\"",
"format:check": "prettier --config .prettierrc --check \"src\""
},
"author": "LangChain",

@@ -57,3 +43,3 @@ "license": "MIT",

"typescript": "^4.9.5 || ^5.4.5",
"vitest": "^3.1.2"
"vitest": "^3.2.4"
},

@@ -81,3 +67,18 @@ "publishConfig": {

"dist/"
]
],
"scripts": {
"build": "pnpm turbo build:internal --filter=@langchain/langgraph-checkpoint",
"build:internal": "pnpm --filter @langchain/build compile @langchain/langgraph-checkpoint",
"clean": "rm -rf dist/ dist-cjs/ .turbo/",
"lint:eslint": "NODE_OPTIONS=--max-old-space-size=4096 eslint --cache --ext .ts,.js src/",
"lint:dpdm": "dpdm --exit-code circular:1 --no-warning --no-tree src/*.ts src/**/*.ts",
"lint": "pnpm lint:eslint && pnpm lint:dpdm",
"lint:fix": "pnpm lint:eslint --fix && pnpm lint:dpdm",
"prepublish": "pnpm build",
"test": "vitest run",
"test:watch": "vitest watch",
"test:int": "vitest run --mode int",
"format": "prettier --config .prettierrc --write \"src\"",
"format:check": "prettier --config .prettierrc --check \"src\""
}
}
# @langchain/langgraph-checkpoint
## 1.0.0
### Major Changes
- 1e1ecbb: This release updates the package for compatibility with LangGraph v1.0. See the [v1.0 release notes](https://docs.langchain.com/oss/javascript/releases/langgraph-v1) for details on what's new.
## 0.1.1
### Patch Changes
- 11c7807: Add support for @langchain/core 1.0.0-alpha
## 0.1.0
### Minor Changes
- 10f292a: Remove pending_sends from parent checkpoints in favour of TASKS channel
- 3fd7f73: Allow asynchronous serialization and deserialization
- 773ec0d: Remove Checkpoint.writes
### Patch Changes
- ccbcbc1: Add delete thread method to checkpointers
//#region rolldown:runtime
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
key = keys[i];
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: ((k) => from[k]).bind(null, key),
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
value: mod,
enumerable: true
}) : target, mod));
//#endregion
exports.__toESM = __toESM;